From 45897fab9be1ebd7494a95ee996c4c4435418cde Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?J=C3=A9r=C3=B4me=20Krell?= Date: Thu, 10 Oct 2019 14:22:30 +0200 Subject: [PATCH] Reformat Code by PyCharm-Community MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Signed-off-by: Jérôme Krell --- Assembler/assembler.py | 476 +- Binary Coefficients.py | 27 +- Binary_search.py | 54 +- BlackJack_game/blackjack.py | 140 +- BlackJack_game/blackjack_rr.py | 202 +- BruteForce.py | 38 +- CRC/crc.py | 71 +- Classification_human_orr_horse.py | 53 +- Colors/primary_colors.py | 301 +- Compression_Analysis/PSNR.py | 46 +- CountMillionCharacter.py | 13 +- CountMillionCharacters-2.0.py | 2 +- .../variation1.py | 7 +- Cricket_score.py | 3 +- Day_of_week.py | 14 +- Decimal_To_Binary.py | 50 +- EncryptionTool.py | 5 +- .../Background.py | 114 +- Flappy Bird - created with tkinter/Bird.py | 177 +- .../Flappy Bird.py | 313 +- .../Settings.py | 64 +- Flappy Bird - created with tkinter/Tubes.py | 217 +- Google_Image_Downloader/create_dir.py | 18 +- Google_Image_Downloader/image_grapper.py | 45 +- Google_News.py | 26 +- GroupSms_Way2.py | 8 +- Guess_the_number_game.py | 17 +- Guessing_Game.py | 29 +- Infix_to_Postfix.py | 179 +- Koch Curve/koch curve.py | 41 +- Memory_game.py | 27 +- Merge-sort.py | 54 +- MobiusFunction.py | 8 +- MySQL_Databses.py | 15 +- Organise.py | 76 +- PDF/basic.py | 18 +- PDF/header_footer.py | 22 +- PDF/images.py | 17 +- PONG_GAME.py | 111 +- PORT SCANNER.PY | 10 +- Palindrome_Checker.py | 9 +- Polyline.py | 16 +- Print_List_of_Even_Numbers.py | 20 +- Print_List_of_Odd_Numbers.py | 22 +- Program to print table of given number.py | 6 +- QuadraticCalc.py | 62 +- Quick_Sort.py | 67 +- RandomDice.py | 20 +- ReadFromCSV.py | 19 +- Shivaansh.py | 8 +- SimpleCalculator.py | 34 +- SimpleStopWatch.py | 8 +- Streaming Tweets from Twitter to Database.py | 36 +- TTS.py | 31 +- TicTacToe.py | 48 +- Weather Scrapper/weather.py | 42 +- WikipediaModule.py | 83 +- Windows_Wallpaper_Script/wallpaper_extract.py | 2 + XORcipher/XOR_cipher.py | 244 +- XORcipher/test_XOR_cipher.py | 24 +- alexa_news_headlines.py | 25 +- async_downloader/async_downloader.py | 9 +- bank_managment_system/backend.py | 219 +- bank_managment_system/frontend.py | 574 +- batch_file_rename.py | 2 +- blackJackGUI.py | 74 +- blackjack.py | 141 +- brickout-game/brickout-game.py | 165 +- changemac.py | 123 +- check_file.py | 3 +- check_for_sqlite_files.py | 1 + check_internet_con.py | 1 + classicIndianCardMatch.py | 29 +- communication/file.py | 20 +- communication/pipe.py | 20 +- communication/socket_conn.py | 19 +- cricket_live_score.py | 4 +- daily_checks.py | 3 +- days_from_date.py | 39 +- dir_test.py | 1 + factor.py | 6 +- factorial.py | 6 +- factors.py | 8 +- fibonacci.py | 78 +- fileinfo.py | 49 +- find_prime.py | 16 +- folder_size.py | 23 +- four_digit_num_combination.py | 2 + ftp_send_receive.py | 16 +- gambler.py | 8 +- game_of_life/game_o_life.py | 79 +- gcd.py | 28 +- get_crypto_price.py | 49 +- get_likes_on_FB.py | 34 +- get_youtube_view.py | 23 +- google.py | 43 +- insta_monitering/insta_api.py | 21 +- insta_monitering/insta_datafetcher.py | 73 +- insta_monitering/subpinsta.py | 14 +- internet_connection_py3.py | 20 +- jee_result.py | 57 +- kmp_str_search.py | 3 +- linear-algebra-python/src/lib.py | 146 +- linear-algebra-python/src/tests.py | 151 +- live_sketch.py | 6 +- logs.py | 21 +- magic8ball.py | 25 +- meme_maker.py | 12 +- merge.py | 21 +- move_files_over_x_days.py | 21 +- movie_details.py | 18 +- multiplication_table.py | 24 +- nDigitNumberCombinations.py | 20 +- new_script.py | 65 +- news_intent_schema.json | 94 +- nmap_scan.py | 49 +- nodepad/notepad.py | 75 +- nodepad/notepad_support.py | 42 +- nslookup_check.py | 6 +- osinfo.py | 31 +- other_pepole/get_ip_gui | 99 +- pan.py | 236 +- passwordGen.py | 22 +- passwordGenerator.py | 34 +- password_cracker.py | 54 +- ph_email.py | 48 +- ping_servers.py | 76 +- ping_subnet.py | 44 +- polygon.py | 5 +- portscanner.py | 108 +- powerdown_startup.py | 59 +- powerup_checks.py | 158 +- primelib/primelib.py | 511 +- prison_break_scrapper.py | 49 +- pscheck.py | 32 +- psunotify.py | 61 +- puttylogs.py | 28 +- pythonVideoDownloader.py | 54 +- python_sms.py | 95 +- random-sentences.py | 23 +- randomloadingmessage.py | 318 +- read_excel_file.py | 8 +- rearrange-files/rearrange-files.py | 16 +- recyclebin.py | 80 +- replacetext.py | 14 +- rock_paper_scissor_game.py | 25 +- rook.py | 74 +- scrap_file.py | 31 +- script_count.py | 113 +- script_listing.py | 22 +- sendemail.py | 32 +- serial_scanner.py | 33 +- sha1.py | 24 +- sierpinski_triangle.py | 44 +- site_health.py | 65 +- snake.py | 38 +- socket-programming/client.py | 25 +- socket-programming/server.py | 19 +- spiralmatrix.py | 68 +- spotlight.py | 43 +- sqlite_check.py | 35 +- sqlite_table_check.py | 42 +- start-server.py | 3 +- tar.py | 66 +- testlines.py | 9 +- text_cleaning_comparisson.py | 55 +- tf_idf_generator.py | 79 +- .../Nose.xml | 117486 +++++++++------ .../face.xml | 87540 +++++++---- .../mustache-add-on-face.py | 11 +- .../utils.py | 28 +- thread_signal.py | 9 +- tic_tak_toe.py | 78 +- tik_tak.py | 151 +- timymodule.py | 14 +- tweeter.py | 82 +- video-operations/slow-motion.py | 10 +- video-operations/timelapse.py | 10 +- webcam.py | 7 +- wiki_random.py | 24 +- work_connect.py | 53 +- write_excel_file.py | 1 - xkcd_downloader.py | 29 +- youtube-downloader fast.py | 2 +- youtube.py | 9 +- 185 files changed, 128830 insertions(+), 86755 deletions(-) diff --git a/Assembler/assembler.py b/Assembler/assembler.py index 7321af87852..956a146b829 100644 --- a/Assembler/assembler.py +++ b/Assembler/assembler.py @@ -1,10 +1,11 @@ from __future__ import print_function + import sys -lines = [] # contains the lines of the file. -tokens = [] # contains all tokens of the source code. +lines = [] # contains the lines of the file. +tokens = [] # contains all tokens of the source code. -#register eax, ebx,..., ecx +# register eax, ebx,..., ecx eax = 0 ebx = 0 ecx = 0 @@ -29,13 +30,14 @@ # simple exception class -class InvalidSyntax (Exception): - def __init__ (self): +class InvalidSyntax(Exception): + def __init__(self): pass + # class for represent a token class Token(): - def __init__ (self, token, t): + def __init__(self, token, t): self.token = token self.t = t @@ -63,108 +65,108 @@ def scanner(string): """ global tokens token = "" - state = 0 # init state + state = 0 # init state for ch in string: if state == 0: - if ch == 'm': # catch mov-command + if ch == 'm': # catch mov-command state = 1 token += 'm' - elif ch == 'e': # catch register + elif ch == 'e': # catch register state = 4 token += 'e' - elif (ch >= '1' and ch <= '9') or ch == '-': # catch a number + elif (ch >= '1' and ch <= '9') or ch == '-': # catch a number state = 6 token += ch - elif ch == '0': # catch a number or hex-code + elif ch == '0': # catch a number or hex-code state = 17 token += ch - elif ch == 'a': # catch add-command + elif ch == 'a': # catch add-command state = 7 token += ch - elif ch == 's': # catch sub command + elif ch == 's': # catch sub command state = 10 token += ch - elif ch == 'i': # capture int command + elif ch == 'i': # capture int command state = 14 token += ch - elif ch == 'p': # capture push or pop command + elif ch == 'p': # capture push or pop command state = 19 token += ch - elif ch == 'l': # capture label + elif ch == 'l': # capture label state = 25 token += ch - elif ch == 'j': # capture jmp command + elif ch == 'j': # capture jmp command state = 26 token += ch - elif ch == 'c': # catch cmp-command + elif ch == 'c': # catch cmp-command state = 29 token += ch - elif ch == ';': # capture comment + elif ch == ';': # capture comment state = 33 - - elif ch == '"': # catch a string + + elif ch == '"': # catch a string state = 34 # without " - elif ch.isupper(): # capture identifier + elif ch.isupper(): # capture identifier state = 35 token += ch - elif ch == 'd': # capture db keyword + elif ch == 'd': # capture db keyword state = 36 token += ch - elif ch == "$": # catch variable with prefix $ + elif ch == "$": # catch variable with prefix $ state = 38 # not catching $ - elif ch == '_': # catch label for subprogram + elif ch == '_': # catch label for subprogram state = 40 # not catches the character _ - elif ch == 'r': # catch ret-command + elif ch == 'r': # catch ret-command state = 44 token += ch - - else: # other characters like space-characters etc. + + else: # other characters like space-characters etc. state = 0 token = "" - - elif state == 1: # state 1 + + elif state == 1: # state 1 if ch == 'o': @@ -176,62 +178,62 @@ def scanner(string): state = 47 token += ch - else: # error case + else: # error case state = 0 token = "" raise InvalidSyntax() - elif state == 2: # state 2 + elif state == 2: # state 2 if ch == 'v': state = 3 token += 'v' - else: # error case + else: # error case state = 0 token = "" raise InvalidSyntax() - elif state == 3: # state 3 + elif state == 3: # state 3 if ch.isspace(): state = 0 - tokens.append(Token(token,"command")) + tokens.append(Token(token, "command")) token = "" - else: # error case + else: # error case state = 0 token = "" raise InvalidSyntax() - elif state == 4: # state 4 + elif state == 4: # state 4 if (ch >= 'a' and ch <= 'd'): state = 5 token += ch - else: # error case + else: # error case state = 0 token = "" raise InvalidSyntax() - elif state == 5: # state 5 + elif state == 5: # state 5 if ch == 'x': state = 13 token += ch - - else: # error case + + else: # error case state = 0 token = "" raise InvalidSyntax() - elif state == 6: # state 6 + elif state == 6: # state 6 if ch.isdigit(): @@ -241,136 +243,136 @@ def scanner(string): elif ch.isspace(): state = 0 - tokens.append(Token(token,"value")) + tokens.append(Token(token, "value")) token = "" - else: # error case + else: # error case state = 0 token = "" raise InvalidSyntax() - elif state == 7: # state 7 + elif state == 7: # state 7 if ch == 'd': state = 8 token += ch - else: # error case + else: # error case state = 0 token = "" raise InvalidSyntax() - elif state == 8: # state 8 + elif state == 8: # state 8 if ch == 'd': state = 9 token += ch - else: # error case + else: # error case state = 0 token = "" raise InvalidSyntax() - elif state == 9: # state 9 + elif state == 9: # state 9 if ch.isspace(): state = 0 - tokens.append(Token(token,"command")) + tokens.append(Token(token, "command")) token = "" - else: # error case + else: # error case state = 0 token = "" raise InvalidSyntax() - elif state == 10: # state 10 + elif state == 10: # state 10 if ch == 'u': state = 11 token += ch - else: # error case - + else: # error case + state = 0 token = "" raise InvalidSyntax() - elif state == 11: # state 11 + elif state == 11: # state 11 if ch == 'b': state = 12 token += ch - else: # error case + else: # error case state = 0 token = "" raise InvalidSyntax() - elif state == 12: # state 12 + elif state == 12: # state 12 if ch.isspace(): state = 0 - tokens.append(Token(token,"command")) + tokens.append(Token(token, "command")) token = "" - else: # error case + else: # error case state = 0 token = "" raise InvalidSyntax() - elif state == 13: # state 13 + elif state == 13: # state 13 if ch == ',' or ch.isspace(): state = 0 - tokens.append(Token(token,"register")) + tokens.append(Token(token, "register")) token = "" - else: # error case + else: # error case state = 0 token = "" raise InvalidSyntax() - elif state == 14: # state 14 + elif state == 14: # state 14 if ch == 'n': state = 15 token += ch - else: # error case + else: # error case state = 0 token = "" raise InvalidSyntax() - elif state == 15: # state 15 + elif state == 15: # state 15 if ch == 't': state = 16 token += ch - else: # error case + else: # error case state = 0 token = "" raise InvalidSyntax() - elif state == 16: # state 16 + elif state == 16: # state 16 if ch.isspace(): @@ -378,13 +380,13 @@ def scanner(string): tokens.append(Token(token, "command")) token = "" - else: # error case + else: # error case state = 0 token = "" raise InvalidSyntax() - elif state == 17: # state 17 + elif state == 17: # state 17 if ch == 'x': @@ -397,13 +399,13 @@ def scanner(string): tokens.append(Token(token, "value")) token = "" - else: # error case + else: # error case state = 0 token = "" raise InvalidSyntax() - elif state == 18: # state 18 + elif state == 18: # state 18 if ch.isdigit() or (ch >= 'a' and ch <= 'f'): @@ -413,16 +415,16 @@ def scanner(string): elif ch.isspace(): state = 0 - tokens.append(Token(token,"value")) + tokens.append(Token(token, "value")) token = "" - else: # error case + else: # error case state = 0 token = "" raise InvalidSyntax() - elif state == 19: # state 19 + elif state == 19: # state 19 if ch == 'u': @@ -434,80 +436,80 @@ def scanner(string): state = 23 token += ch - else: # error case + else: # error case state = 0 token = "" raise InvalidSyntax() - elif state == 20: # state 20 + elif state == 20: # state 20 if ch == 's': state = 21 token += ch - else: # error case + else: # error case state = 0 token = "" raise InvalidSyntax() - elif state == 21: # state 21 + elif state == 21: # state 21 if ch == 'h': state = 22 token += ch - else: # error case + else: # error case state = 0 token = "" raise InvalidSyntax() - elif state == 22: # state 22 + elif state == 22: # state 22 if ch.isspace(): state = 0 - tokens.append(Token(token,"command")) + tokens.append(Token(token, "command")) token = "" - else: # error case + else: # error case state = 0 token = "" raise InvalidSyntax() - elif state == 23: # state 23 + elif state == 23: # state 23 if ch == 'p': state = 24 token += ch - else: # error case + else: # error case state = 0 token = "" raise InvalidSyntax() - elif state == 24: # state 24 + elif state == 24: # state 24 if ch.isspace(): state = 0 - tokens.append(Token(token,"command")) + tokens.append(Token(token, "command")) token = "" - else: # error case + else: # error case state = 0 token = "" raise InvalidSyntax() - elif state == 25: # state 25 + elif state == 25: # state 25 if ch.isdigit(): @@ -517,47 +519,47 @@ def scanner(string): elif ch == ':' or ch.isspace(): state = 0 - tokens.append(Token(token,"label")) + tokens.append(Token(token, "label")) token = "" - else: # error case + else: # error case state = 0 token = "" raise InvalidSyntax() - elif state == 26: # state 26 + elif state == 26: # state 26 if ch == 'm': state = 27 token += ch - elif ch == 'e': # catch je command + elif ch == 'e': # catch je command state = 32 token += ch - else: # error case + else: # error case state = 0 token = "" raise InvalidSyntax() - elif state == 27: # state 27 + elif state == 27: # state 27 if ch == 'p': state = 28 token += ch - else: # error case + else: # error case state = 0 token = "" raise InvalidSyntax() - elif state == 28: # state 28 + elif state == 28: # state 28 if ch.isspace(): @@ -565,94 +567,94 @@ def scanner(string): tokens.append(Token(token, "command")) token = "" - else: # error case + else: # error case state = 0 token = "" raise InvalidSyntax() - elif state == 29: # state 29 + elif state == 29: # state 29 if ch == 'm': state = 30 token += ch - elif ch == 'a': # catch call-command + elif ch == 'a': # catch call-command state = 41 token += ch - else: # error case + else: # error case state = 0 token = "" raise InvalidSyntax() - elif state == 30: # state 30 + elif state == 30: # state 30 if ch == 'p': state = 31 token += ch - else: # error case + else: # error case state = 0 token = "" raise InvalidSyntax() - elif state == 31: # state 31 + elif state == 31: # state 31 if ch.isspace(): state = 0 - tokens.append(Token(token,"command")) + tokens.append(Token(token, "command")) token = "" - else: # error case + else: # error case state = 0 token = "" raise InvalidSyntax() - elif state == 32: # state 32 + elif state == 32: # state 32 if ch.isspace(): state = 0 - tokens.append(Token(token,"command")) + tokens.append(Token(token, "command")) token = "" - else: # error case + else: # error case state = 0 token = "" raise InvalidSyntax() - elif state == 33: # state 33 + elif state == 33: # state 33 if ch.isdigit() or ch.isalpha() or (ch.isspace() and ch != '\n') \ - or ch == '"': + or ch == '"': state = 33 - + elif ch == '\n': state = 0 - else: # error case + else: # error case state = 0 token = "" raise InvalidSyntax() - elif state == 34: # state 34 + elif state == 34: # state 34 if ch.isdigit() or ch.isalpha() or ch.isspace(): @@ -662,16 +664,16 @@ def scanner(string): elif ch == '"': state = 0 - tokens.append(Token(token,"string")) + tokens.append(Token(token, "string")) token = "" - else: # error case + else: # error case state = 0 token = "" raise InvalidSyntax() - elif state == 35: # state 35 + elif state == 35: # state 35 if ch.isdigit() or ch.isupper(): @@ -681,17 +683,17 @@ def scanner(string): elif ch == ' ' or ch == '\n': state = 0 - tokens.append(Token(token,"identifier")) + tokens.append(Token(token, "identifier")) token = "" - else: # error case + else: # error case state = 0 token = "" raise InvalidSyntax() - elif state == 36: # state 36 + elif state == 36: # state 36 if ch == 'b': @@ -703,40 +705,40 @@ def scanner(string): state = 49 token += ch - else: # error case + else: # error case state = 0 token = "" raise InvalidSyntax() - elif state == 37: # state 37 + elif state == 37: # state 37 if ch.isspace(): state = 0 - tokens.append(Token (token, "command")) + tokens.append(Token(token, "command")) token = "" - else: # error case + else: # error case state = 0 token = "" raise InvalidSyntax() - elif state == 38: # state 38 + elif state == 38: # state 38 if ch.isalpha(): state = 39 token += ch - else: # error case + else: # error case state = 0 token = "" raise InvalidSyntax() - elif state == 39: # state 39 + elif state == 39: # state 39 if ch.isalpha() or ch.isdigit(): @@ -746,212 +748,210 @@ def scanner(string): elif ch.isspace(): state = 0 - tokens.append(Token (token,"identifier")) + tokens.append(Token(token, "identifier")) token = "" - else: # error case + else: # error case state = 0 token = "" raise InvalidSyntax() - elif state == 40: # state 40 + elif state == 40: # state 40 - if (ch >= 'a' and ch <='z') or (ch >= 'A' and ch <= 'Z') or (ch >= '0' and ch <= '9'): + if (ch >= 'a' and ch <= 'z') or (ch >= 'A' and ch <= 'Z') or (ch >= '0' and ch <= '9'): state = 40 token += ch elif ch == ':' or ch.isspace(): - + state = 0 - tokens.append(Token (token,"subprogram")) + tokens.append(Token(token, "subprogram")) token = "" - else: # error case + else: # error case state = 0 token = "" raise InvalidSyntax() - elif state == 41: # state 41 + elif state == 41: # state 41 if ch == 'l': state = 42 token += ch - else: # error case + else: # error case state = 0 token = "" raise InvalidSyntax() - elif state == 42: # state 42 + elif state == 42: # state 42 if ch == 'l': state = 43 token += ch - else: # error case + else: # error case state = 0 token = "" raise InvalidSyntax() - elif state == 43: # state 43 + elif state == 43: # state 43 if ch.isspace(): state = 0 - tokens.append(Token(token,"command")) + tokens.append(Token(token, "command")) token = "" - else: # error case + else: # error case state = 0 token = "" raise InvalidSyntax() - elif state == 44: # state 44 + elif state == 44: # state 44 if ch == 'e': state = 45 token += ch - else: # error case + else: # error case state = 0 token = "" raise InvalidSyntax() - elif state == 45: # state 45 + elif state == 45: # state 45 if ch == 't': state = 46 token += ch - else: # error case + else: # error case state = 0 token = "" raise InvalidSyntax() - elif state == 46: # state 46 + elif state == 46: # state 46 if ch.isspace(): state = 0 - tokens.append(Token(token,"command")) + tokens.append(Token(token, "command")) token = "" - else: # error case + else: # error case state = 0 token = "" raise InvalidSyntax() - elif state == 47: # state 47 + elif state == 47: # state 47 if ch == 'l': state = 48 token += ch - else: # error case + else: # error case state = 0 token = "" raise InvalidSyntax() - elif state == 48: # state 48 + elif state == 48: # state 48 if ch.isspace(): state = 0 - tokens.append(Token(token,"command")) + tokens.append(Token(token, "command")) token = "" - - else: # error case + + else: # error case state = 0 token = "" raise InvalidSyntax() - elif state == 49: # state 49 + elif state == 49: # state 49 if ch == 'v': state = 50 token += ch - else: # error case + else: # error case state = 0 token = "" raise InvalidSyntax() - elif state == 50: # state 50 + elif state == 50: # state 50 if ch.isspace(): state = 0 - tokens.append(Token(token,"command")) + tokens.append(Token(token, "command")) token = "" - - else: # error case + + else: # error case state = 0 token = "" raise InvalidSyntax() - - - def scan(): """ scan: applys function scanner() to each line of the source code. """ global lines - assert len(lines) > 0 , "no lines" + assert len(lines) > 0, "no lines" for line in lines: try: scanner(line) except InvalidSyntax: - print("line=",line) - + print("line=", line) + + def parser(): """ parser: parses the tokens of the list 'tokens' """ global tokens - global eax,ebx,ecx,edx + global eax, ebx, ecx, edx - assert len(tokens) > 0 , "no tokens" + assert len(tokens) > 0, "no tokens" - pointer = 0 # pointer for tokens - token = Token("","") - tmpToken = Token("","") + pointer = 0 # pointer for tokens + token = Token("", "") + tmpToken = Token("", "") while pointer < len(tokens): token = tokens[pointer] - if token.token == "mov": # mov commando + if token.token == "mov": # mov commando # it must follow a register - if pointer+1 < len(tokens): + if pointer + 1 < len(tokens): pointer += 1 token = tokens[pointer] else: @@ -964,7 +964,7 @@ def parser(): tmpToken = token # it must follow a value / string / register / variable - if pointer+1 < len(tokens): + if pointer + 1 < len(tokens): pointer += 1 token = tokens[pointer] else: @@ -973,7 +973,7 @@ def parser(): # converts the token into float, if token contains only digits. # TODO response of float - if token.t == "identifier": # for variables + if token.t == "identifier": # for variables # check of exists of variable if token.token in variables: @@ -990,7 +990,7 @@ def parser(): elif token.token[0] == '-' and token.token[1:].isdigit(): token.token = float(token.token[1:]) token.token *= -1 - elif token.t == "register": # loads out of register + elif token.t == "register": # loads out of register if token.token == "eax": token.token = eax elif token.token == "ebx": @@ -1000,8 +1000,6 @@ def parser(): elif token.token == "edx": token.token = edx - - if tmpToken.token == "eax": eax = token.token elif tmpToken.token == "ebx": @@ -1016,7 +1014,7 @@ def parser(): print("Error: No found register!") return - elif token.token == "add": # add commando + elif token.token == "add": # add commando pointer += 1 token = tokens[pointer] @@ -1025,17 +1023,16 @@ def parser(): tmpToken = token - if pointer+1 < len(tokens): + if pointer + 1 < len(tokens): pointer += 1 token = tokens[pointer] else: print("Error: Not found number!") return - # converts the token into float, if token contains only digits. if token.t == "register": - + # for the case that token is register if token.token == "eax": token.token = eax @@ -1052,11 +1049,9 @@ def parser(): token.token = float(token.token[1:]) token.token *= -1 else: - print("Error: ", token," is not a number!") + print("Error: ", token, " is not a number!") return - - if tmpToken.token == "eax": eax += token.token @@ -1089,7 +1084,7 @@ def parser(): zeroFlag = True else: zeroFlag = False - + else: @@ -1106,7 +1101,7 @@ def parser(): tmpToken = token - if pointer+1 < len(tokens): + if pointer + 1 < len(tokens): pointer += 1 token = tokens[pointer] else: @@ -1125,7 +1120,7 @@ def parser(): token.token = ecx elif token.token == "edx": token.token = edx - + elif isinstance(token.token, float): pass elif token.token.isdigit(): @@ -1134,10 +1129,9 @@ def parser(): token.token = float(token.token[1:]) token.token *= -1 else: - print("Error: ", token.token," is not a number!") + print("Error: ", token.token, " is not a number!") return - if tmpToken.token == "eax": eax -= token.token @@ -1176,20 +1170,20 @@ def parser(): print("Error: No found register!") return - elif token.token == "int": # int commando + elif token.token == "int": # int commando tmpToken = token - if pointer+1 < len(tokens): + if pointer + 1 < len(tokens): pointer += 1 token = tokens[pointer] else: print("Error: Not found argument!") return - if token.token == "0x80": # system interrupt 0x80 - - if eax == 1: # exit program + if token.token == "0x80": # system interrupt 0x80 + + if eax == 1: # exit program if ebx == 0: print("END PROGRAM") @@ -1202,17 +1196,17 @@ def parser(): ecx = float(input(">> ")) - elif eax == 4: # output informations + elif eax == 4: # output informations print(ecx) - - elif token.token == "push": # push commando + + elif token.token == "push": # push commando tmpToken = token # it must follow a register - if pointer+1 < len(tokens): + if pointer + 1 < len(tokens): pointer += 1 token = tokens[pointer] else: @@ -1237,12 +1231,12 @@ def parser(): stack.append(edx) - elif token.token == "pop": # pop commando + elif token.token == "pop": # pop commando tmpToken = token # it must follow a register - if pointer+1 < len(tokens): + if pointer + 1 < len(tokens): pointer += 1 token = tokens[pointer] else: @@ -1266,14 +1260,14 @@ def parser(): edx = stack.pop() - elif token.t == "label": # capture label + elif token.t == "label": # capture label jumps[token.token] = pointer - elif token.token == "jmp": # capture jmp command + elif token.token == "jmp": # capture jmp command # it must follow a label - if pointer+1 < len(tokens): + if pointer + 1 < len(tokens): pointer += 1 token = tokens[pointer] else: @@ -1282,7 +1276,7 @@ def parser(): if token.t == "label": - pointer = jumps[token.token] + pointer = jumps[token.token] else: print("Error: expected a label!") @@ -1290,9 +1284,9 @@ def parser(): elif token.token == "cmp": # TODO - + # it must follow a register - if pointer+1 < len(tokens): + if pointer + 1 < len(tokens): pointer += 1 token = tokens[pointer] else: @@ -1301,11 +1295,10 @@ def parser(): if token.t == "register": - # it must follow a register - if pointer+1 < len(tokens): + if pointer + 1 < len(tokens): pointer += 1 - tmpToken = tokens[pointer] # next register + tmpToken = tokens[pointer] # next register else: print("Error: Not found register!") return @@ -1372,7 +1365,7 @@ def parser(): else: zeroFlag = False - + elif token.token == "ecx": if tmpToken.token == "eax": @@ -1403,7 +1396,7 @@ def parser(): else: zeroFlag = False - + elif token.token == "edx": if tmpToken.token == "eax": @@ -1434,18 +1427,18 @@ def parser(): else: zeroFlag = False - + else: print("Error: Not found register!") return - + elif token.token == "je": # it must follow a label - if pointer+1 < len(tokens): + if pointer + 1 < len(tokens): pointer += 1 - token = tokens[pointer] # next register + token = tokens[pointer] # next register else: print("Error: Not found argument") return @@ -1455,13 +1448,12 @@ def parser(): # actual jump if zeroFlag: - pointer = jumps[token.token] else: - print("Error: Not found label") - return + print("Error: Not found label") + return elif token.t == "identifier": @@ -1470,9 +1462,9 @@ def parser(): if token.token not in variables: # it must follow a command - if pointer+1 < len(tokens): + if pointer + 1 < len(tokens): pointer += 1 - tmpToken = tokens[pointer] # next register + tmpToken = tokens[pointer] # next register else: print("Error: Not found argument") return @@ -1480,9 +1472,9 @@ def parser(): if tmpToken.t == "command" and tmpToken.token == "db": # it must follow a value (string) - if pointer+1 < len(tokens): + if pointer + 1 < len(tokens): pointer += 1 - tmpToken = tokens[pointer] # next register + tmpToken = tokens[pointer] # next register else: print("Error: Not found argument") return @@ -1493,51 +1485,50 @@ def parser(): variables[token.token] = float(tmpToken.token) elif tmpToken.t == "string": variables[token.token] = tmpToken.token - + else: print("Error: Not found db-keyword") return - elif token.token == "call": # catch the call-command + elif token.token == "call": # catch the call-command # it must follow a subprogram label - if pointer+1 < len(tokens): + if pointer + 1 < len(tokens): pointer += 1 - token = tokens[pointer] # next register + token = tokens[pointer] # next register else: print("Error: Not found subprogram label") return - if token.t == "subprogram": if token.token in jumps: # save the current pointer - returnStack.append(pointer) # eventuell pointer + 1 + returnStack.append(pointer) # eventuell pointer + 1 # jump to the subprogram pointer = jumps[token.token] - - else: # error case + + else: # error case print("Error: Unknow subprogram!") return - else: # error case + else: # error case print("Error: Not found subprogram") return - + elif token.token == "ret": # catch the ret-command if len(returnStack) >= 1: - pointer = returnStack.pop() + pointer = returnStack.pop() - else: # error case + else: # error case print("Error: No return adress on stack") return @@ -1546,13 +1537,13 @@ def parser(): pass - - elif token.token == "mul": # catch mul-command + + elif token.token == "mul": # catch mul-command # it must follow a register - if pointer+1 < len(tokens): + if pointer + 1 < len(tokens): pointer += 1 - token = tokens[pointer] # next register + token = tokens[pointer] # next register else: print("Error: Not found argument") return @@ -1585,9 +1576,9 @@ def parser(): elif token.token == "div": # it must follow a register - if pointer+1 < len(tokens): + if pointer + 1 < len(tokens): pointer += 1 - token = tokens[pointer] # next register + token = tokens[pointer] # next register else: print("Error: Not found argument") return @@ -1615,8 +1606,6 @@ def parser(): print("Error: Not found register") return - - # increment pointer for fetching next token. pointer += 1 @@ -1630,7 +1619,7 @@ def registerLabels(): jumps[tokens[i].token] = i elif tokens[i].t == "subprogram": jumps[tokens[i].token] = i - + def resetInterpreter(): """ @@ -1650,6 +1639,7 @@ def resetInterpreter(): tokens = [] returnStack = [] + # DEBUG FUNCTION # def printTokens(): # for token in tokens: diff --git a/Binary Coefficients.py b/Binary Coefficients.py index 1d6f9fb4104..4c8d3316e0d 100644 --- a/Binary Coefficients.py +++ b/Binary Coefficients.py @@ -1,21 +1,20 @@ -def pascal_triangle( lineNumber ) : +def pascal_triangle(lineNumber): list1 = list() list1.append([1]) - i=1 - while(i<=lineNumber): - j=1 - l=[] + i = 1 + while (i <= lineNumber): + j = 1 + l = [] l.append(1) - while(j 21: - print("You are BUSTED !\n **************Dealer Wins !!******************\n") - exit() + print("You are BUSTED !\n **************Dealer Wins !!******************\n") + exit() if sum(d_cards) > 21: - print("Dealer is BUSTED !\n ************** You are the Winner !!******************\n") - exit() + print("Dealer is BUSTED !\n ************** You are the Winner !!******************\n") + exit() if sum(d_cards) == 21: - print("***********************Dealer is the Winner !!******************") - exit() + print("***********************Dealer is the Winner !!******************") + exit() if sum(d_cards) == 21 and sum(p_cards) == 21: - print("*****************The match is tie !!*************************") - exit() + print("*****************The match is tie !!*************************") + exit() def dealer_choice(): - if sum(d_cards) < 17: - while sum(d_cards) < 17: - random.shuffle(deck) - d_cards.append(deck.pop()) - - - print("Dealer has total "+ str(sum(d_cards))+"with the cards ",d_cards) - - if sum(p_cards) == sum(d_cards): - print("***************The match is tie !!****************") - exit() - - - if sum(d_cards) == 21: - if sum(p_cards) < 21: - print("***********************Dealer is the Winner !!******************") - elif sum(p_cards) == 21: - print("********************There is tie !!**************************") - else: - print("***********************Dealer is the Winner !!******************") - - elif sum(d_cards) <21: - if sum(p_cards) < 21 and sum(p_cards) < sum(d_cards): - print("***********************Dealer is the Winner !!******************") - if sum(p_cards) == 21: - print("**********************Player is winner !!**********************") - if sum(p_cards) < 21 and sum(p_cards) > sum(d_cards): - print("**********************Player is winner !!**********************") - - else: - if sum(p_cards) < 21: - print("**********************Player is winner !!**********************") - elif sum(p_cards) == 21: - print("**********************Player is winner !!**********************") - else: - print("***********************Dealer is the Winner !!******************") - + if sum(d_cards) < 17: + while sum(d_cards) < 17: + random.shuffle(deck) + d_cards.append(deck.pop()) + + print("Dealer has total " + str(sum(d_cards)) + "with the cards ", d_cards) + + if sum(p_cards) == sum(d_cards): + print("***************The match is tie !!****************") + exit() + + if sum(d_cards) == 21: + if sum(p_cards) < 21: + print("***********************Dealer is the Winner !!******************") + elif sum(p_cards) == 21: + print("********************There is tie !!**************************") + else: + print("***********************Dealer is the Winner !!******************") + + elif sum(d_cards) < 21: + if sum(p_cards) < 21 and sum(p_cards) < sum(d_cards): + print("***********************Dealer is the Winner !!******************") + if sum(p_cards) == 21: + print("**********************Player is winner !!**********************") + if sum(p_cards) < 21 and sum(p_cards) > sum(d_cards): + print("**********************Player is winner !!**********************") + else: + if sum(p_cards) < 21: + print("**********************Player is winner !!**********************") + elif sum(p_cards) == 21: + print("**********************Player is winner !!**********************") + else: + print("***********************Dealer is the Winner !!******************") while sum(p_cards) < 21: @@ -96,16 +90,14 @@ def dealer_choice(): if k == 1: random.shuffle(deck) p_cards.append(deck.pop()) - print ('You have a total of ' + str(sum(p_cards)) - + ' with the cards ', p_cards) + print('You have a total of ' + str(sum(p_cards)) + + ' with the cards ', p_cards) if sum(p_cards) > 21: - print ('*************You are BUSTED !*************\n Dealer Wins !!') + print('*************You are BUSTED !*************\n Dealer Wins !!') if sum(p_cards) == 21: - print ('*******************You are the Winner !!*****************************') + print('*******************You are the Winner !!*****************************') - - else: - dealer_choice() - break - + else: + dealer_choice() + break diff --git a/BlackJack_game/blackjack_rr.py b/BlackJack_game/blackjack_rr.py index a7a5ae4c6e3..a73218b9a13 100644 --- a/BlackJack_game/blackjack_rr.py +++ b/BlackJack_game/blackjack_rr.py @@ -2,99 +2,103 @@ suits = ('Hearts', 'Diamonds', 'Spades', 'Clubs') ranks = ('Two', 'Three', 'Four', 'Five', 'Six', 'Seven', 'Eight', 'Nine', 'Ten', 'Jack', 'Queen', 'King', 'Ace') -values = {'Two':2, 'Three':3, 'Four':4, 'Five':5, 'Six':6, 'Seven':7, 'Eight':8, - 'Nine':9, 'Ten':10, 'Jack':10, 'Queen':10, 'King':10, 'Ace':11} +values = {'Two': 2, 'Three': 3, 'Four': 4, 'Five': 5, 'Six': 6, 'Seven': 7, 'Eight': 8, + 'Nine': 9, 'Ten': 10, 'Jack': 10, 'Queen': 10, 'King': 10, 'Ace': 11} playing = True + class Card: - - def __init__(self,suit,rank): + + def __init__(self, suit, rank): self.suit = suit self.rank = rank - + def __str__(self): return self.rank + ' of ' + self.suit - + class Deck: - + def __init__(self): - self.deck = [] + self.deck = [] for suit in suits: for rank in ranks: - self.deck.append(Card(suit,rank)) - + self.deck.append(Card(suit, rank)) + def __str__(self): - deck_comp = '' + deck_comp = '' for card in self.deck: - deck_comp += '\n '+card.__str__() - + deck_comp += '\n ' + card.__str__() + def shuffle(self): random.shuffle(self.deck) - + def deal(self): single_card = self.deck.pop() return single_card - + class Hand: - + def __init__(self): - self.cards = [] - self.value = 0 - self.aces = 0 #to keep track of aces - - def add_card(self,card): + self.cards = [] + self.value = 0 + self.aces = 0 # to keep track of aces + + def add_card(self, card): self.cards.append(card) self.value += values[card.rank] if card.rank == 'Ace': - self.aces += 1 - + self.aces += 1 + def adjust_for_ace(self): while self.value > 21 and self.aces: self.value -= 10 self.aces -= 1 - + class Chips: - + def __init__(self): self.total = 100 self.bet = 0 - + def win_bet(self): self.total += self.bet - + def lose_bet(self): self.total -= self.bet - -def take_bet(chips): +def take_bet(chips): while True: try: chips.bet = int(input('How many chips would you like to bet? ')) except ValueError: print('Your bet must be an integer! Try again.') else: - if chips.bet > chips.total or chips.bet<=0: - print("Your bet cannot exceed your balance and you have to enter a positive bet! Your current balance is: ",chips.total) + if chips.bet > chips.total or chips.bet <= 0: + print( + "Your bet cannot exceed your balance and you have to enter a positive bet! Your current balance is: ", + chips.total) else: break -def hit(deck,hand): + +def hit(deck, hand): hand.add_card(deck.deal()) hand.adjust_for_ace() - -def hit_or_stand(deck,hand): + + +def hit_or_stand(deck, hand): global playing - + while True: x = input("Would you like to Hit or Stand? Enter '1' or '0' ") - + if x.lower() == '1': - hit(deck,hand) + hit(deck, hand) elif x.lower() == '0': print("You chose to stand. Dealer will hit.") @@ -105,44 +109,52 @@ def hit_or_stand(deck,hand): continue break - -def show_some(player,dealer): + +def show_some(player, dealer): print("\nDealer's Hand:") print(" { hidden card }") - print('',dealer.cards[1]) + print('', dealer.cards[1]) print("\nYour Hand:", *player.cards, sep='\n ') - -def show_all(player,dealer): + + +def show_all(player, dealer): print("\nDealer's Hand:", *dealer.cards, sep='\n ') - print("Dealer's Hand =",dealer.value) + print("Dealer's Hand =", dealer.value) print("\nYour Hand:", *player.cards, sep='\n ') - print("Your Hand =",player.value) - -def player_busts(player,dealer,chips): + print("Your Hand =", player.value) + + +def player_busts(player, dealer, chips): print("You are BUSTED !") chips.lose_bet() -def player_wins(player,dealer,chips): + +def player_wins(player, dealer, chips): print("You are the winner!") chips.win_bet() -def dealer_busts(player,dealer,chips): + +def dealer_busts(player, dealer, chips): print("Dealer has BUSTED !") chips.win_bet() - -def dealer_wins(player,dealer,chips): + + +def dealer_wins(player, dealer, chips): print("Dealer is the winner!") chips.lose_bet() - -def push(player,dealer): + + +def push(player, dealer): print("The match is tie !") - + + # GAMEPLAY while True: print("\t **********************************************************") - print("\t Welcome to the game Casino - BLACK JACK ! ") + print( + "\t Welcome to the game Casino - BLACK JACK ! ") print("\t **********************************************************") print("\t ***************") print("\t * A *") @@ -155,69 +167,67 @@ def push(player,dealer): print("\t * *") print("\t * *") print("\t ***************") - - print('\nRULES: Get as close to 21 as you can but if you get more than 21 you will lose!\n Aces count as 1 or 11.') - + deck = Deck() deck.shuffle() - + player_hand = Hand() player_hand.add_card(deck.deal()) player_hand.add_card(deck.deal()) - + dealer_hand = Hand() dealer_hand.add_card(deck.deal()) dealer_hand.add_card(deck.deal()) - - player_chips = Chips() - - + + player_chips = Chips() + take_bet(player_chips) - - - show_some(player_hand,dealer_hand) - - while playing: - - hit_or_stand(deck,player_hand) - show_some(player_hand,dealer_hand) - + + show_some(player_hand, dealer_hand) + + while playing: + + hit_or_stand(deck, player_hand) + show_some(player_hand, dealer_hand) + if player_hand.value > 21: - player_busts(player_hand,dealer_hand,player_chips) + player_busts(player_hand, dealer_hand, player_chips) break - + if player_hand.value <= 21: - + while dealer_hand.value < 17: - hit(deck,dealer_hand) - - show_all(player_hand,dealer_hand) - + hit(deck, dealer_hand) + + show_all(player_hand, dealer_hand) + if dealer_hand.value > 21: - dealer_busts(player_hand,dealer_hand,player_chips) + dealer_busts(player_hand, dealer_hand, player_chips) elif dealer_hand.value > player_hand.value: - dealer_wins(player_hand,dealer_hand,player_chips) + dealer_wins(player_hand, dealer_hand, player_chips) elif dealer_hand.value < player_hand.value: - player_wins(player_hand,dealer_hand,player_chips) + player_wins(player_hand, dealer_hand, player_chips) + + else: + push(player_hand, dealer_hand) + print("\nYour current balance stands at", player_chips.total) + + if player_chips.total > 0: + new_game = input("Would you like to play another hand? Enter '1' or '0' ") + if new_game.lower() == '1': + playing = True + continue else: - push(player_hand,dealer_hand) - - - print("\nYour current balance stands at",player_chips.total) - - if player_chips.total>0: - new_game = input("Would you like to play another hand? Enter '1' or '0' ") - if new_game.lower()=='1': - playing=True - continue - else: - print("Thanks for playing!\n \t$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$\n \t Congratulations! You won {} coins!\n\t$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$\n ".format(player_chips.total)) - break + print( + "Thanks for playing!\n \t$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$\n \t Congratulations! You won {} coins!\n\t$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$\n ".format( + player_chips.total)) + break else: - print("Oops! You have bet all your chips and we are sorry you can't play more.\nThanks for playing! Do come again to Casino BLACK JACK!") + print( + "Oops! You have bet all your chips and we are sorry you can't play more.\nThanks for playing! Do come again to Casino BLACK JACK!") break diff --git a/BruteForce.py b/BruteForce.py index b434eb07d46..3bffbc260fe 100644 --- a/BruteForce.py +++ b/BruteForce.py @@ -1,6 +1,7 @@ from itertools import product -def findPassword(chars,function,show=50,format_="%s"): + +def findPassword(chars, function, show=50, format_="%s"): """ Essa função encontra e retorna uma senha e retorna o número de tentativas. @@ -19,17 +20,17 @@ def findPassword(chars,function,show=50,format_="%s"): attempts = 0 size = 1 stop = False - + while not stop: # Obtém todas as combinações possíveis com os dígitos do parâmetro "chars". - for pw in product(chars,repeat=size): - + for pw in product(chars, repeat=size): + password = "".join(pw) - + # Imprime a senha que será tentada. if attempts % show == 0: - print(format_%password) + print(format_ % password) # Verifica se a senha é a correta. if function(password): @@ -38,8 +39,8 @@ def findPassword(chars,function,show=50,format_="%s"): else: attempts += 1 size += 1 - - return password,attempts + + return password, attempts def getChars(): @@ -50,19 +51,18 @@ def getChars(): chars = [] # Acrescenta à lista todas as letras maiúsculas - for id_ in range(ord("A"),ord("Z")+1): + for id_ in range(ord("A"), ord("Z") + 1): chars.append(chr(id_)) # Acrescenta à lista todas as letras minúsculas - for id_ in range(ord("a"),ord("z")+1): + for id_ in range(ord("a"), ord("z") + 1): chars.append(chr(id_)) # Acrescenta à lista todos os números for number in range(10): chars.append(str(number)) - - return chars + return chars # Se este módulo não for importado, o programa será testado. @@ -72,11 +72,12 @@ def getChars(): import datetime import time - + # Pede ao usuário uma senha pw = input("\n Type a password: ") print("\n") + def testFunction(password): """ Função que será usada para fazer o teste. @@ -87,7 +88,9 @@ def testFunction(password): global pw if password == pw: return True - else: return False + else: + return False + # Obtém os dígitos que uma senha pode ter chars = getChars() @@ -95,8 +98,7 @@ def testFunction(password): t = time.process_time() # Obtém a senha encontrada e o múmero de tentativas - password,attempts = findPassword(chars,testFunction,show=1000,format_=" Trying %s") - - t = datetime.timedelta(seconds=int(time.process_time()-t)) - input("\n\n Password found: {}\n Attempts: {}\n Time: {}\n".format(password,attempts,t)) + password, attempts = findPassword(chars, testFunction, show=1000, format_=" Trying %s") + t = datetime.timedelta(seconds=int(time.process_time() - t)) + input("\n\n Password found: {}\n Attempts: {}\n Time: {}\n".format(password, attempts, t)) diff --git a/CRC/crc.py b/CRC/crc.py index 27e6cc6f0e2..a1dce358013 100644 --- a/CRC/crc.py +++ b/CRC/crc.py @@ -1,49 +1,50 @@ -def crc_check(data,div): - l=len(div) - ct=0 - data=[int(i) for i in data] - div=[int(i) for i in div] - zero=[0 for i in range(l)] - temp_data=[data[i] for i in range(l)] - result=[] - for j in range(len(data)-len(div)+1): - print("Temp_dividend",temp_data) - msb=temp_data[0] - if msb==0: +def crc_check(data, div): + l = len(div) + ct = 0 + data = [int(i) for i in data] + div = [int(i) for i in div] + zero = [0 for i in range(l)] + temp_data = [data[i] for i in range(l)] + result = [] + for j in range(len(data) - len(div) + 1): + print("Temp_dividend", temp_data) + msb = temp_data[0] + if msb == 0: result.append(0) - for i in range(l-1,-1,-1): - temp_data[i]=temp_data[i] ^ zero[i] + for i in range(l - 1, -1, -1): + temp_data[i] = temp_data[i] ^ zero[i] else: result.append(1) - for i in range(l-1,-1,-1): - temp_data[i]=temp_data[i] ^ div[i] + for i in range(l - 1, -1, -1): + temp_data[i] = temp_data[i] ^ div[i] temp_data.pop(0) - if (l+j0: + +while 1 > 0: print("Enter data: ") - data=input() + data = input() print("Enter divisor") - div=input() - original_data=data - data=data+("0"*(len(div)-1)) - crc=crc_check(data,div) - crc_str="" + div = input() + original_data = data + data = data + ("0" * (len(div) - 1)) + crc = crc_check(data, div) + crc_str = "" for i in range(len(crc)): - crc_str+=str(crc[i]) - print("Sent data: ",original_data+crc_str) - sent_data=original_data+crc_str + crc_str += str(crc[i]) + print("Sent data: ", original_data + crc_str) + sent_data = original_data + crc_str print("If again applying CRC algorithm, the remainder/CRC must be zero if errorless.") - crc=crc_check(sent_data,div) - remainder=crc - print("Receiver side remainder: ",remainder) + crc = crc_check(sent_data, div) + remainder = crc + print("Receiver side remainder: ", remainder) print("Continue [Y/N]:") - ch=input() - if ch=='N' or ch=='n': + ch = input() + if ch == 'N' or ch == 'n': break else: continue diff --git a/Classification_human_orr_horse.py b/Classification_human_orr_horse.py index b4844b1d878..af08de8cbf9 100644 --- a/Classification_human_orr_horse.py +++ b/Classification_human_orr_horse.py @@ -1,37 +1,39 @@ -import tensorflow as tf -from tensorflow import keras import pickle -model=tf.keras.models.Sequential([tf.keras.layers.Conv2D(16,(3,3),activation='relu',input_shape=(200,200,3)), - tf.keras.layers.MaxPooling2D(2,2), - tf.keras.layers.Conv2D(16,(3,3),activation='relu'), - tf.keras.layers.MaxPooling2D(2,2), - tf.keras.layers.Conv2D(16,(3,3),activation='relu'), - tf.keras.layers.MaxPooling2D(2,2), - tf.keras.layers.Flatten(), - tf.keras.layers.Dense(512,activation='relu'), - tf.keras.layers.Dense(1,activation="sigmoid") - ]) + +import tensorflow as tf + +model = tf.keras.models.Sequential([tf.keras.layers.Conv2D(16, (3, 3), activation='relu', input_shape=(200, 200, 3)), + tf.keras.layers.MaxPooling2D(2, 2), + tf.keras.layers.Conv2D(16, (3, 3), activation='relu'), + tf.keras.layers.MaxPooling2D(2, 2), + tf.keras.layers.Conv2D(16, (3, 3), activation='relu'), + tf.keras.layers.MaxPooling2D(2, 2), + tf.keras.layers.Flatten(), + tf.keras.layers.Dense(512, activation='relu'), + tf.keras.layers.Dense(1, activation="sigmoid") + ]) model.summary() from tensorflow.keras.optimizers import RMSprop -model.compile(optimizer=RMSprop(lr=0.001),loss='binary_crossentropy',metrics=['acc']) + +model.compile(optimizer=RMSprop(lr=0.001), loss='binary_crossentropy', metrics=['acc']) from tensorflow.keras.preprocessing.image import ImageDataGenerator -train_datagen=ImageDataGenerator(rescale=1/255) -train_generator=train_datagen.flow_from_directory('E:/ARYAN/Desktop/python_tensorflow/Classification_human-or-horse', - target_size=(200,200), - batch_size=222, - class_mode='binary') -model.fit_generator(train_generator,steps_per_epoch=6,epochs=1,verbose=1) -filename="myTf1.sav" -pickle.dump(model,open(filename,'wb')) + +train_datagen = ImageDataGenerator(rescale=1 / 255) +train_generator = train_datagen.flow_from_directory('E:/ARYAN/Desktop/python_tensorflow/Classification_human-or-horse', + target_size=(200, 200), + batch_size=222, + class_mode='binary') +model.fit_generator(train_generator, steps_per_epoch=6, epochs=1, verbose=1) +filename = "myTf1.sav" +pickle.dump(model, open(filename, 'wb')) from tkinter import Tk from tkinter.filedialog import askopenfilename from keras.preprocessing import image import numpy as np -import cv2 -Tk().withdraw() -filename = askopenfilename() +Tk().withdraw() +filename = askopenfilename() print(filename) img = image.load_img(filename, target_size=(200, 200)) x = image.img_to_array(img) @@ -39,8 +41,7 @@ images = np.vstack([x]) classes = model.predict(images, batch_size=10) print(classes[0]) -if classes[0]>0.5: +if classes[0] > 0.5: print(filename + " is a human") else: print(filename + " is a horse") - diff --git a/Colors/primary_colors.py b/Colors/primary_colors.py index 6a1c674c0dd..1bc3adbcd8e 100644 --- a/Colors/primary_colors.py +++ b/Colors/primary_colors.py @@ -1,173 +1,174 @@ -def simpleColor(r,g,b): -""" simpleColor obtiene el nombre del color mas general al cual se acerca su formato R G B """ - r=int(r) - g=int(g) - b=int(b) - try: - #ROJO -------------------------------------------------- - if r > g and r > b: - - rg = diff(r,g) #distancia rojo a verde - rb = diff(r,b) #distancia rojo a azul - - if g < 65 and b < 65 and rg > 60: #azul y verde sin luz - return "ROJO" - - gb=diff(g,b) #distancia de verde a azul - - if rg < rb: # Verde mayor que Azul - if gb < rg: #Verde mas cerca de Azul - if gb >=30 and rg >= 80: - return "NARANJA" - elif gb<=20 and rg >= 80: - return "ROJO" - elif gb<=20 and b > 175: - return "CREMA" - - else: - return "CHOCOLATE" - else: #Verde mas cerca de Rojo - if rg > 60: - return "NARANJA*" - elif r > 125: - return "AMARILLO" - else: - return "COCHOLATE" - elif rg > rb: #Azul mayor que verde - if bg < rb: #Verde mas cerca de Azul - if gb < 60: - if r >150: - return "ROJO 2" - else: - return "MARRON" - elif g > 125: - return "ROSADO" +def simpleColor(r, g, b): + + + """ simpleColor obtiene el nombre del color mas general al cual se acerca su formato R G B """ +r = int(r) +g = int(g) +b = int(b) +try: + # ROJO -------------------------------------------------- + if r > g and r > b: + + rg = diff(r, g) # distancia rojo a verde + rb = diff(r, b) # distancia rojo a azul + + if g < 65 and b < 65 and rg > 60: # azul y verde sin luz + return "ROJO" + + gb = diff(g, b) # distancia de verde a azul + + if rg < rb: # Verde mayor que Azul + if gb < rg: # Verde mas cerca de Azul + if gb >= 30 and rg >= 80: + return "NARANJA" + elif gb <= 20 and rg >= 80: + return "ROJO" + elif gb <= 20 and b > 175: + return "CREMA" + + else: + return "CHOCOLATE" + else: # Verde mas cerca de Rojo + if rg > 60: + return "NARANJA*" + elif r > 125: + return "AMARILLO" + else: + return "COCHOLATE" + elif rg > rb: # Azul mayor que verde + if bg < rb: # Verde mas cerca de Azul + if gb < 60: + if r > 150: + return "ROJO 2" else: - return "ROJO 3" - else: #Verde mas cerca de Rojo - if rb < 60: - if r > 160: - return "ROSADO*" - else: - return "ROJO" + return "MARRON" + elif g > 125: + return "ROSADO" + else: + return "ROJO 3" + else: # Verde mas cerca de Rojo + if rb < 60: + if r > 160: + return "ROSADO*" else: return "ROJO" - - else: # g y b iguales - if rg > 20: - if r>=100 and b <60: - return "ROJO" - elif r >=100: - return "ROJO" - else: - return "MARRON" - else: - return "GRIS" - # VERDE --------------------------------------------------- - elif g > r and g > b: - gb = diff(g,b) #distancia verde a azul - gr = diff(g,r) #distancia verde a rojo + return "ROJO" + + else: # g y b iguales + if rg > 20: + if r >= 100 and b < 60: + return "ROJO" + elif r >= 100: + return "ROJO" + else: + return "MARRON" - if r < 65 and b < 65 and gb > 60: #rojo y azul sin luz - return "VERDE" - - rb=diff(r,b) #distancia de rojo a azul - - if r > b: #ROJO > AZUL - if gr < gb: #Verde con Rojo - - if rb>=150 and gr <=20: - return "AMARILLO" - else: - return "VERDE" - else: #...Verde - return "VERDE" + else: + return "GRIS" + # VERDE --------------------------------------------------- + elif g > r and g > b: + gb = diff(g, b) # distancia verde a azul + gr = diff(g, r) # distancia verde a rojo - elif r < b: #AZUL > ROJO - if gb < gr: #Verde con Azul - - if gb<=20: - return "TURQUESA" - else: - return "VERDE" - else: #...Verde - return "VERDE" - - else: #r y b iguales - if gb > 10: + if r < 65 and b < 65 and gb > 60: # rojo y azul sin luz + return "VERDE" + + rb = diff(r, b) # distancia de rojo a azul + + if r > b: # ROJO > AZUL + if gr < gb: # Verde con Rojo + + if rb >= 150 and gr <= 20: + return "AMARILLO" + else: return "VERDE" + else: # ...Verde + return "VERDE" + + elif r < b: # AZUL > ROJO + if gb < gr: # Verde con Azul + + if gb <= 20: + return "TURQUESA" else: - return "GRIS" + return "VERDE" + else: # ...Verde + return "VERDE" + else: # r y b iguales + if gb > 10: + return "VERDE" + else: + return "GRIS" - #AZUL ------------------------------------------------------ - elif b > r and b > g: - bg = diff(b,g) #distancia azul a verde - br = diff(b,r) #distancia azul a rojo - if r < 65 and g < 65 and bg > 60: #rojo y verde sin luz - return "AZUL" - - rg=diff(r,g) #distancia de rojo a verde + # AZUL ------------------------------------------------------ + elif b > r and b > g: + bg = diff(b, g) # distancia azul a verde + br = diff(b, r) # distancia azul a rojo - if g < r: # ROJO > VERDE - if bg < rg: #Azul con Verde - if bg<=20: - return "TURQUESA" - else: - return "CELESTE" - else: #...Azul - if rg <= 20: - if r >= 150: - return "LILA" - else: - return "AZUL *************" - else: - return "AZUL" + if r < 65 and g < 65 and bg > 60: # rojo y verde sin luz + return "AZUL" + + rg = diff(r, g) # distancia de rojo a verde - elif g > r: # VERDE > ROJO - if br < rg: #Azul con rojo - if br <=20: - if r > 150 and g < 75: - return "ROSADO FIUSHA" - elif ir > 150: - return "LILA" - else: - return "MORADO" + if g < r: # ROJO > VERDE + if bg < rg: # Azul con Verde + if bg <= 20: + return "TURQUESA" + else: + return "CELESTE" + else: # ...Azul + if rg <= 20: + if r >= 150: + return "LILA" + else: + return "AZUL *************" + else: + return "AZUL" + + elif g > r: # VERDE > ROJO + if br < rg: # Azul con rojo + if br <= 20: + if r > 150 and g < 75: + return "ROSADO FIUSHA" + elif ir > 150: + return "LILA" else: return "MORADO" - - - else: #...Azul - if rg <= 20: - if bg <=20: - return "GRIS" - else: - return "AZUL" - else: #r y g iguales - if bg > 20: - if r>=100 and b <60: - return "ROJO" - elif r >=100: - return "ROJO" + else: + return "MORADO" + + + else: # ...Azul + if rg <= 20: + if bg <= 20: + return "GRIS" else: - return "MARRON" + return "AZUL" + else: # r y g iguales + if bg > 20: + if r >= 100 and b < 60: + return "ROJO" + elif r >= 100: + return "ROJO" else: - return "GRIS" - + return "MARRON" + else: + return "GRIS" - # IGUALES--------------------------------------- - else: - return "GRIS" - except: + # IGUALES--------------------------------------- + else: + return "GRIS" - return "Not Color" +except: + return "Not Color" -#--------------------------------------------------------------------------------------------------- +# --------------------------------------------------------------------------------------------------- # Puedes probar asi: python primary_colors.py 120,0,0 , esto resultara en un ROJO como respuesta -#-------------------------------------------------------------------------------------------------- -if __name__=='__main__': - print(simpleColor(sys.argv[1],sys.argv[2],sys.argv[3])) +# -------------------------------------------------------------------------------------------------- +if __name__ == '__main__': + print(simpleColor(sys.argv[1], sys.argv[2], sys.argv[3])) diff --git a/Compression_Analysis/PSNR.py b/Compression_Analysis/PSNR.py index 1585c8cfc96..277e43cc125 100644 --- a/Compression_Analysis/PSNR.py +++ b/Compression_Analysis/PSNR.py @@ -1,38 +1,40 @@ -import numpy as np import math + import cv2 +import numpy as np + + +def Representational(r, g, b): + return (0.299 * r + 0.287 * g + 0.114 * b) -def Representational(r,g,b): - return (0.299*r+0.287*g+0.114*b) def calculate(img): - b,g,r = cv2.split(img) - pixelAt = Representational(r,g,b) - return pixelAt + b, g, r = cv2.split(img) + pixelAt = Representational(r, g, b) + return pixelAt + def main(): - - #Loading images (orignal image and compressed image) - orignal_image = cv2.imread('orignal_image.png',1) - compressed_image = cv2.imread('compressed_image.png',1) + # Loading images (orignal image and compressed image) + orignal_image = cv2.imread('orignal_image.png', 1) + compressed_image = cv2.imread('compressed_image.png', 1) - #Getting image height and width - height,width = orignal_image.shape[:2] + # Getting image height and width + height, width = orignal_image.shape[:2] - orignalPixelAt = calculate(orignal_image) - compressedPixelAt = calculate(compressed_image) + orignalPixelAt = calculate(orignal_image) + compressedPixelAt = calculate(compressed_image) - diff = orignalPixelAt - compressedPixelAt - error = np.sum(np.abs(diff) ** 2) + diff = orignalPixelAt - compressedPixelAt + error = np.sum(np.abs(diff) ** 2) - error = error/(height*width) + error = error / (height * width) - #MSR = error_sum/(height*width) - PSNR = -(10*math.log10(error/(255*255))) + # MSR = error_sum/(height*width) + PSNR = -(10 * math.log10(error / (255 * 255))) - print("PSNR value is {}".format(PSNR)) + print("PSNR value is {}".format(PSNR)) if __name__ == '__main__': - main() - + main() diff --git a/CountMillionCharacter.py b/CountMillionCharacter.py index 75f94a75826..3b893f02cb8 100644 --- a/CountMillionCharacter.py +++ b/CountMillionCharacter.py @@ -7,6 +7,7 @@ frequency code used below. I just merged the two ideas. """ import re + pattern = re.compile("\W") wordstring = '''SCENE I. Yorkshire. Gaultree Forest. Enter the ARCHBISHOP OF YORK, MOWBRAY, LORD HASTINGS, and others @@ -295,12 +296,12 @@ wordlist = wordstring.split() for x, y in enumerate(wordlist): - special_character = pattern.search(y[-1:]) - try: - if special_character.group(): - wordlist[x] = y[:-1] - except: - continue + special_character = pattern.search(y[-1:]) + try: + if special_character.group(): + wordlist[x] = y[:-1] + except: + continue wordfreq = [wordlist.count(w) for w in wordlist] diff --git a/CountMillionCharacters-2.0.py b/CountMillionCharacters-2.0.py index 0e9a7091155..84dd27fc9e5 100644 --- a/CountMillionCharacters-2.0.py +++ b/CountMillionCharacters-2.0.py @@ -4,8 +4,8 @@ of the txt file in which you have the desired text. """ -import pprint import collections +import pprint def main(): diff --git a/CountMillionCharacters-Variations/variation1.py b/CountMillionCharacters-Variations/variation1.py index 4a1bb809b47..f294512697b 100644 --- a/CountMillionCharacters-Variations/variation1.py +++ b/CountMillionCharacters-Variations/variation1.py @@ -14,10 +14,11 @@ def count_chars(filename): return count + def main(): - is_exist=True - #Try to open file if exist else raise exception and try again - while(is_exist): + is_exist = True + # Try to open file if exist else raise exception and try again + while (is_exist): try: inputFile = input("File Name / (0)exit : ").strip() if inputFile == "0": diff --git a/Cricket_score.py b/Cricket_score.py index a683a3a3ba8..0f42115ac22 100644 --- a/Cricket_score.py +++ b/Cricket_score.py @@ -1,5 +1,6 @@ -import bs4 #Beautiful Soup for Web Scraping from urllib import request + +import bs4 # Beautiful Soup for Web Scraping from win10toast import ToastNotifier toaster = ToastNotifier() diff --git a/Day_of_week.py b/Day_of_week.py index 8284ac5fe19..eb0bda17eb0 100644 --- a/Day_of_week.py +++ b/Day_of_week.py @@ -1,12 +1,14 @@ # Python program to Find day of # the week for a given date -import datetime -import calendar +import calendar +import datetime + + +def findDay(date): + born = datetime.datetime.strptime(date, '%d %m %Y').weekday() + return (calendar.day_name[born]) -def findDay(date): - born = datetime.datetime.strptime(date, '%d %m %Y').weekday() - return (calendar.day_name[born]) # Driver program date = '03 02 2019' -print(findDay(date)) +print(findDay(date)) diff --git a/Decimal_To_Binary.py b/Decimal_To_Binary.py index 3105244ff26..c7a9385146c 100644 --- a/Decimal_To_Binary.py +++ b/Decimal_To_Binary.py @@ -9,34 +9,34 @@ decimal_accuracy = 7 -def dtbconverter(num): # Function inputs a float value and returns a list as output - # Reasoning for list instead of integer: to avoid integer overflow error. - - whole= [] # The part before decimal point - fractional = ['.'] # The part after decimal point - - decimal = round(num%1, decimal_accuracy) # Extract fractional number part of decimal - w_num = int(num) # Extract whole number part of decimal. - - i=0 # Some fractional decimal numbers have infinite binary values, so we limit this loop below. - - #Loop to find binary of decimal part - while(decimal!=1 and i= self.__height+20: + # Se o pássaro tiver ultrapassado a borda de baixo do background, ele será declarado morto + if position[3] >= self.__height + 20: self.__isAlive = False - #Se o pássaro tiver ultrapassado a borda de cima do background, ele será declarado morto + # Se o pássaro tiver ultrapassado a borda de cima do background, ele será declarado morto if position[1] <= -20: self.__isAlive = False - #Dá uma margem de erro ao pássaro de X pixels - position[0] += int(25/78*self.width) - position[1] += int(25/77*self.height) - position[2] -= int(20/78*self.width) - position[3] -= int(10/77*self.width) + # Dá uma margem de erro ao pássaro de X pixels + position[0] += int(25 / 78 * self.width) + position[1] += int(25 / 77 * self.height) + position[2] -= int(20 / 78 * self.width) + position[3] -= int(10 / 77 * self.width) - #Define os objetos a serem ignorados em colisões + # Define os objetos a serem ignorados em colisões ignored_collisions = self.__canvas.getBackgroundID() ignored_collisions.append(self.__birdID) - #Verifica possíveis colisões com o pássaro + # Verifica possíveis colisões com o pássaro possible_collisions = list(self.__canvas.find_overlapping(*position)) - #Remove das possíveis colisões os objetos ignorados + # Remove das possíveis colisões os objetos ignorados for _id in ignored_collisions: - try: possible_collisions.remove(_id) - except: continue - - #Se houver alguma colisão o pássaro morre + try: + possible_collisions.remove(_id) + except: + continue + + # Se houver alguma colisão o pássaro morre if len(possible_collisions) >= 1: self.__isAlive = False return not self.__isAlive - def getTag(self): """ Método para retornar a tag do pássaro @@ -114,10 +118,8 @@ def getTag(self): return self.__tag - @staticmethod - - def getPhotoImage(image=None,image_path=None,width=None,height=None,closeAfter=False): + def getPhotoImage(image=None, image_path=None, width=None, height=None, closeAfter=False): """ Retorna um objeto da classe PIL.ImageTk.PhotoImage de uma imagem e as imagens criadas de PIL.Image (photoImage, new, original) @@ -131,68 +133,65 @@ def getPhotoImage(image=None,image_path=None,width=None,height=None,closeAfter=F if not image: if not image_path: return - - #Abre a imagem utilizando o caminho dela + + # Abre a imagem utilizando o caminho dela image = openImage(image_path) - #Será redimesionada a imagem somente se existir um width ou height + # Será redimesionada a imagem somente se existir um width ou height if not width: width = image.width if not height: height = image.height - #Cria uma nova imagem já redimensionada - newImage = image.resize([width,height]) + # Cria uma nova imagem já redimensionada + newImage = image.resize([width, height]) - #Cria um photoImage + # Cria um photoImage photoImage = PhotoImage(newImage) - #Se closeAfter for True, ele fecha as imagens + # Se closeAfter for True, ele fecha as imagens if closeAfter: - - #Fecha a imagem nova + # Fecha a imagem nova newImage.close() newImage = None - #Fecha a imagem original + # Fecha a imagem original image.close() image = None - #Retorna o PhotoImage da imagem,a nova imagem que foi utilizada e a imagem original - return photoImage,newImage,image - + # Retorna o PhotoImage da imagem,a nova imagem que foi utilizada e a imagem original + return photoImage, newImage, image - def jumps(self,event=None): + def jumps(self, event=None): """ Método para fazer o pássaro pular """ - #Verifica se o pássaro saiu da área do background + # Verifica se o pássaro saiu da área do background self.checkCollision() - #Se o pássaro estiver morto, esse método não pode ser executado + # Se o pássaro estiver morto, esse método não pode ser executado if not self.__isAlive or not self.__running: - self.__going_up = False + self.__going_up = False return - - #Declara que o pássaro está subindo + + # Declara que o pássaro está subindo self.__going_up = True self.__going_down = 0 - #Move o pássaro enquanto o limite de subida por animação não tiver excedido + # Move o pássaro enquanto o limite de subida por animação não tiver excedido if self.__times_skipped < self.climbsUp: - - #Move o pássaro para cima - self.__canvas.move(self.__tag,0,-1) - self.__times_skipped+=1 - #Executa o método novamente - self.__canvas.after(3,self.jumps) + # Move o pássaro para cima + self.__canvas.move(self.__tag, 0, -1) + self.__times_skipped += 1 + + # Executa o método novamente + self.__canvas.after(3, self.jumps) else: - - #Declara que o pássaro não está mais subindo - self.__going_up = False - self.__times_skipped = 0 + # Declara que o pássaro não está mais subindo + self.__going_up = False + self.__times_skipped = 0 def kill(self): """ @@ -201,7 +200,6 @@ def kill(self): self.__isAlive = False - def run(self): """ #Método para iniciar a animação do passáro caindo @@ -209,28 +207,25 @@ def run(self): self.__running = True - #Verifica se o pássaro saiu da área do background + # Verifica se o pássaro saiu da área do background self.checkCollision() - #Enquanto o pássaro não tiver chegado em sua velocidade máxima, a velocidade aumentará em 0.05 + # Enquanto o pássaro não tiver chegado em sua velocidade máxima, a velocidade aumentará em 0.05 if self.__going_down < self.decends: self.__going_down += 0.05 - - #Executa a animação de descida somente se o pássaro estiver vivo + + # Executa a animação de descida somente se o pássaro estiver vivo if self.__isAlive: - #Executa a animação de descida somente se o pássaro não estiver subindo + # Executa a animação de descida somente se o pássaro não estiver subindo if not self.__going_up: + # Move o pássaro para baixo + self.__canvas.move(self.__tag, 0, self.__going_down) + + # Executa novamente o método + self.__canvas.after(self.__descend_speed, self.run) - #Move o pássaro para baixo - self.__canvas.move(self.__tag,0,self.__going_down) - - #Executa novamente o método - self.__canvas.after(self.__descend_speed,self.run) - - #Se o pássaro estiver morto, será executado um método de fim de jogo + # Se o pássaro estiver morto, será executado um método de fim de jogo else: self.__running = False self.gameover_method() - - diff --git a/Flappy Bird - created with tkinter/Flappy Bird.py b/Flappy Bird - created with tkinter/Flappy Bird.py index b9abcfaf806..cfa0a6479d7 100644 --- a/Flappy Bird - created with tkinter/Flappy Bird.py +++ b/Flappy Bird - created with tkinter/Flappy Bird.py @@ -1,117 +1,115 @@ - __author__ = "Jean Loui Bernard Silva de Jesus" __version__ = "1.0" -from Settings import Settings -from Background import Background -from Tubes import Tubes -from Bird import Bird +import os.path from datetime import timedelta from time import time -from tkinter import Tk,Button,PhotoImage -import os.path +from tkinter import Tk, Button + +from Background import Background +from Bird import Bird +from Settings import Settings +from Tubes import Tubes -class App(Tk,Settings): + +class App(Tk, Settings): """ Classe principal do jogo onde tudo será executado """ - #Variáveis privadas e ajustes internos + # Variáveis privadas e ajustes internos __background_animation_speed = 720 __bestScore = 0 - __bird_descend_speed = 38.4 + __bird_descend_speed = 38.4 __buttons = [] __playing = False __score = 0 __time = "%H:%M:%S" - def __init__(self): Tk.__init__(self) self.setOptions() - #Se o tamanho da largura e altura da janela forem definidos, eles serão usados no jogo. - #Caso eles tenham o valor None, o tamanho da janela será o tamanho do monitor do usuário. + # Se o tamanho da largura e altura da janela forem definidos, eles serão usados no jogo. + # Caso eles tenham o valor None, o tamanho da janela será o tamanho do monitor do usuário. - if all([self.window_width,self.window_height]): + if all([self.window_width, self.window_height]): self.__width = self.window_width self.__height = self.window_height else: self.__width = self.winfo_screenwidth() self.__height = self.winfo_screenheight() - #Configura a janela do programa + # Configura a janela do programa self.title(self.window_name) - self.geometry("{}x{}".format(self.__width,self.__height)) + self.geometry("{}x{}".format(self.__width, self.__height)) self.resizable(*self.window_rz) - self.attributes("-fullscreen",self.window_fullscreen) + self.attributes("-fullscreen", self.window_fullscreen) self["bg"] = "black" - #Verifica se existem as imagens do jogo + # Verifica se existem as imagens do jogo for file in self.images_fp: if not os.path.exists(file): raise FileNotFoundError("The following file was not found:\n{}".format(file)) - - #Carrega a imagem do botão para começar o jogo + + # Carrega a imagem do botão para começar o jogo self.__startButton_image = Background.getPhotoImage( image_path=self.startButton_fp, - width=(self.__width//100)*self.button_width, - height=(self.__height//100)*self.button_height, + width=(self.__width // 100) * self.button_width, + height=(self.__height // 100) * self.button_height, closeAfter=True - )[0] + )[0] - #Carrega a imagem do botão para sair do jogo + # Carrega a imagem do botão para sair do jogo self.__exitButton_image = Background.getPhotoImage( image_path=self.exitButton_fp, - width=(self.__width//100)*self.button_width, - height=(self.__height//100)*self.button_height, + width=(self.__width // 100) * self.button_width, + height=(self.__height // 100) * self.button_height, closeAfter=True - )[0] + )[0] - #Carrega a imagem do título do jogo + # Carrega a imagem do título do jogo self.__title_image = Background.getPhotoImage( image_path=self.title_fp, - width=(self.__width//100)*self.title_width, - height=(self.__height//100)*self.title_height, + width=(self.__width // 100) * self.title_width, + height=(self.__height // 100) * self.title_height, closeAfter=True - )[0] - - #Carrega a imagem do placar do jogo + )[0] + + # Carrega a imagem do placar do jogo self.__scoreboard_image = Background.getPhotoImage( image_path=self.scoreboard_fp, - width=(self.__width//100)*self.scoreboard_width, - height=(self.__height//100)*self.scoreboard_height, + width=(self.__width // 100) * self.scoreboard_width, + height=(self.__height // 100) * self.scoreboard_height, closeAfter=True - )[0] + )[0] - #Define a velocidade da animação do background com base na largura da janela - self.__background_animation_speed //= self.__width/100 + # Define a velocidade da animação do background com base na largura da janela + self.__background_animation_speed //= self.__width / 100 self.__background_animation_speed = int(self.__background_animation_speed) - #Define a velocidade de descida do pássaro com base na altura da janela - self.__bird_descend_speed //= self.__height/100 + # Define a velocidade de descida do pássaro com base na altura da janela + self.__bird_descend_speed //= self.__height / 100 self.__bird_descend_speed = int(self.__bird_descend_speed) - - def changeFullscreenOption(self,event=None): + def changeFullscreenOption(self, event=None): """ Método para colocar o jogo no modo "fullscreen" ou "window" """ self.window_fullscreen = not self.window_fullscreen - self.attributes("-fullscreen",self.window_fullscreen) + self.attributes("-fullscreen", self.window_fullscreen) - - def close(self,event=None): + def close(self, event=None): """ Método para fechar o jogo """ - #Salva a melhor pontuação do jogador antes de sair do jogo + # Salva a melhor pontuação do jogador antes de sair do jogo self.saveScore() - #Tenta interromper os processos + # Tenta interromper os processos try: self.__background.stop() self.__bird.kill() @@ -119,39 +117,37 @@ def close(self,event=None): finally: quit() - def createMenuButtons(self): """ Método para criar os botões de menu """ - #Define o tamanho do botão em porcentagem com base no tamanho da janela - width = (self.__width//100)*self.button_width - height = (self.__height//100)*self.button_height + # Define o tamanho do botão em porcentagem com base no tamanho da janela + width = (self.__width // 100) * self.button_width + height = (self.__height // 100) * self.button_height - #Cria um botão para começar o jogo + # Cria um botão para começar o jogo startButton = Button( - self,image=self.__startButton_image,bd=0,command=self.start,cursor=self.button_cursor, - bg=self.button_bg,activebackground=self.button_activebackground - ) - #Coloca o botão dentro do background ( Canvas ) + self, image=self.__startButton_image, bd=0, command=self.start, cursor=self.button_cursor, + bg=self.button_bg, activebackground=self.button_activebackground + ) + # Coloca o botão dentro do background ( Canvas ) self.__buttons.append( - self.__background.create_window((self.__width//2)-width//1.5, - int(self.__height/100*self.button_position_y), - window=startButton)) + self.__background.create_window((self.__width // 2) - width // 1.5, + int(self.__height / 100 * self.button_position_y), + window=startButton)) - #Cria um botão para sair do jogo + # Cria um botão para sair do jogo exitButton = Button( - self,image=self.__exitButton_image,bd=0,command=self.close,cursor=self.button_cursor, - bg=self.button_bg,activebackground=self.button_activebackground - ) + self, image=self.__exitButton_image, bd=0, command=self.close, cursor=self.button_cursor, + bg=self.button_bg, activebackground=self.button_activebackground + ) - #Coloca o botão dentro do background ( Canvas ) + # Coloca o botão dentro do background ( Canvas ) self.__buttons.append( - self.__background.create_window((self.__width//2)+width//1.5, - int(self.__height/100*self.button_position_y), - window=exitButton)) - + self.__background.create_window((self.__width // 2) + width // 1.5, + int(self.__height / 100 * self.button_position_y), + window=exitButton)) def createScoreBoard(self): """ @@ -159,98 +155,95 @@ def createScoreBoard(self): junto com as informações do jogador. """ - #Define a posição X e Y - x = self.__width//2 - y = (self.__height//100)*self.scoreboard_position_y + # Define a posição X e Y + x = self.__width // 2 + y = (self.__height // 100) * self.scoreboard_position_y - #Calcula o tamanho da imagem do placar - scoreboard_w = (self.__width//100)*self.scoreboard_width - scoreboard_h = (self.__width//100)*self.scoreboard_height + # Calcula o tamanho da imagem do placar + scoreboard_w = (self.__width // 100) * self.scoreboard_width + scoreboard_h = (self.__width // 100) * self.scoreboard_height - #Calcula a posição X e Y do texto da pontuação do último jogo - score_x = x - scoreboard_w/100*60/2 - score_y = y + scoreboard_h/100*10/2 + # Calcula a posição X e Y do texto da pontuação do último jogo + score_x = x - scoreboard_w / 100 * 60 / 2 + score_y = y + scoreboard_h / 100 * 10 / 2 - #Calcula a posição X e Y do texto da melhor pontuação do jogador - bestScore_x = x + scoreboard_w/100*35/2 - bestScore_y = y + scoreboard_h/100*10/2 + # Calcula a posição X e Y do texto da melhor pontuação do jogador + bestScore_x = x + scoreboard_w / 100 * 35 / 2 + bestScore_y = y + scoreboard_h / 100 * 10 / 2 - #Calcula a posição X e Y do texto do tempo de jogo + # Calcula a posição X e Y do texto do tempo de jogo time_x = x - time_y = y + scoreboard_h/100*35/2 + time_y = y + scoreboard_h / 100 * 35 / 2 - #Define a fonte dos textos - font = (self.text_font,int(0.02196*self.__width+0.5)) + # Define a fonte dos textos + font = (self.text_font, int(0.02196 * self.__width + 0.5)) - #Cria a imagem do placar no background - self.__background.create_image(x,y,image=self.__scoreboard_image) + # Cria a imagem do placar no background + self.__background.create_image(x, y, image=self.__scoreboard_image) - #Cria texto para mostrar o score do último jogo + # Cria texto para mostrar o score do último jogo self.__background.create_text( - score_x,score_y,text="Score: %s"%self.__score, - fill=self.text_fill,font=font - ) + score_x, score_y, text="Score: %s" % self.__score, + fill=self.text_fill, font=font + ) - #Cria texto para mostrar a melhor pontuação do jogador + # Cria texto para mostrar a melhor pontuação do jogador self.__background.create_text( - bestScore_x,bestScore_y,text="Best Score: %s"%self.__bestScore, - fill=self.text_fill,font=font - ) + bestScore_x, bestScore_y, text="Best Score: %s" % self.__bestScore, + fill=self.text_fill, font=font + ) - #Cria texto para mostrar o tempo de jogo + # Cria texto para mostrar o tempo de jogo self.__background.create_text( - time_x,time_y,text="Time: %s"%self.__time, - fill=self.text_fill,font=font - ) - + time_x, time_y, text="Time: %s" % self.__time, + fill=self.text_fill, font=font + ) def createTitleImage(self): """ Método para criar a imagem do título do jogo no background """ - self.__background.create_image(self.__width//2,(self.__height//100)*self.title_position_y,image=self.__title_image) - + self.__background.create_image(self.__width // 2, (self.__height // 100) * self.title_position_y, + image=self.__title_image) def deleteMenuButtons(self): """ Método para deletar os botões de menu """ - #Deleta cada botão criado dentro do background + # Deleta cada botão criado dentro do background for item in self.__buttons: self.__background.delete(item) - #Limpa a lista de botões + # Limpa a lista de botões self.__buttons.clear() - def gameOver(self): """ Método de fim de jogo """ - #Calcula o tempo jogado em segundos e depois o formata + # Calcula o tempo jogado em segundos e depois o formata self.__time = int(time() - self.__time) self.__time = str(timedelta(seconds=self.__time)) - #Interrompe a animação do plano de fundo e a animação dos tubos + # Interrompe a animação do plano de fundo e a animação dos tubos self.__background.stop() self.__tubes.stop() - #Declara que o jogo não está mais em execução + # Declara que o jogo não está mais em execução self.__playing = False - #Cria os botões inciais + # Cria os botões inciais self.createMenuButtons() - #Cria image do título do jogo + # Cria image do título do jogo self.createTitleImage() - #Cria imagem do placar e mostra as informações do jogo passado + # Cria imagem do placar e mostra as informações do jogo passado self.createScoreBoard() - def increaseScore(self): """ Método para aumentar a pontuação do jogo atual do jogador @@ -260,121 +253,115 @@ def increaseScore(self): if self.__score > self.__bestScore: self.__bestScore = self.__score - def init(self): """ Método para iniciar o programa em si, criando toda a parte gráfica inicial do jogo """ - - #self.createMenuButtons() + + # self.createMenuButtons() self.loadScore() - #Cria o plano de fundo do jogo + # Cria o plano de fundo do jogo self.__background = Background( - self,self.__width,self.__height,fp=self.background_fp,animation_speed=self.__background_animation_speed - ) + self, self.__width, self.__height, fp=self.background_fp, animation_speed=self.__background_animation_speed + ) - #Foca o plano de fundo para que seja possível definir os eventos + # Foca o plano de fundo para que seja possível definir os eventos self.__background.focus_force() - #Define evento para trocar o modo de janela para "fullscreen" ou "window" - self.__background.bind(self.window_fullscreen_event,self.changeFullscreenOption) - #Define evento para começar o jogo - self.__background.bind(self.window_start_event,self.start) - #Define evento para sair do jogo - self.__background.bind(self.window_exit_event,self.close) - - #Define um método caso o usuário feche a janela do jogo + # Define evento para trocar o modo de janela para "fullscreen" ou "window" + self.__background.bind(self.window_fullscreen_event, self.changeFullscreenOption) + # Define evento para começar o jogo + self.__background.bind(self.window_start_event, self.start) + # Define evento para sair do jogo + self.__background.bind(self.window_exit_event, self.close) + + # Define um método caso o usuário feche a janela do jogo self.protocol("WM_DELETE_WINDOW", self.close) - #Empacota o objeto background + # Empacota o objeto background self.__background.pack() - #Cria os botões do menu do jogo + # Cria os botões do menu do jogo self.createMenuButtons() - #Cria imagem do título do jogo + # Cria imagem do título do jogo self.createTitleImage() - #Cria um pássaro inicial no jogo + # Cria um pássaro inicial no jogo self.__bird = Bird( - self.__background,self.gameOver,self.__width,self.__height, - fp=self.bird_fp,event=self.bird_event,descend_speed=self.__bird_descend_speed - ) - + self.__background, self.gameOver, self.__width, self.__height, + fp=self.bird_fp, event=self.bird_event, descend_speed=self.__bird_descend_speed + ) def loadScore(self): """ Método para carregar a pontuação do jogador """ - #Tenta carregar o placar do usuário + # Tenta carregar o placar do usuário try: file = open(self.score_fp) - self.__bestScore = int(file.read(),2) + self.__bestScore = int(file.read(), 2) file.close() - #Se não for possível, será criado um arquivo para guardar o placar + # Se não for possível, será criado um arquivo para guardar o placar except: - file = open(self.score_fp,'w') + file = open(self.score_fp, 'w') file.write(bin(self.__bestScore)) file.close() - def saveScore(self): """ Método para salvar a pontuação do jogador """ - with open(self.score_fp,'w') as file: + with open(self.score_fp, 'w') as file: file.write(bin(self.__bestScore)) - - def start(self,event=None): + def start(self, event=None): """ Método para inicializar o jogo """ - #Este método é executado somente se o jogador não estiver já jogando + # Este método é executado somente se o jogador não estiver já jogando if self.__playing: return - - #Reinicia o placar + + # Reinicia o placar self.__score = 0 self.__time = time() - #Remove os botões de menu + # Remove os botões de menu self.deleteMenuButtons() - #Reinicia o background + # Reinicia o background self.__background.reset() - #Inicializa a animação do background se True + # Inicializa a animação do background se True if self.background_animation: self.__background.run() - #Cria um pássaro no jogo + # Cria um pássaro no jogo self.__bird = Bird( - self.__background,self.gameOver,self.__width,self.__height, - fp=self.bird_fp,event=self.bird_event,descend_speed=self.__bird_descend_speed - ) - - #Cria tubos no jogo + self.__background, self.gameOver, self.__width, self.__height, + fp=self.bird_fp, event=self.bird_event, descend_speed=self.__bird_descend_speed + ) + + # Cria tubos no jogo self.__tubes = Tubes( - self.__background,self.__bird,self.increaseScore,self.__width,self.__height, - fp=self.tube_fp,animation_speed=self.__background_animation_speed - ) - - #Inicializa a animação do pássaro e dos tubos + self.__background, self.__bird, self.increaseScore, self.__width, self.__height, + fp=self.tube_fp, animation_speed=self.__background_animation_speed + ) + + # Inicializa a animação do pássaro e dos tubos self.__bird.start() self.__tubes.start() - -if __name__ == "__main__": +if __name__ == "__main__": try: app = App() app.init() app.mainloop() - except FileNotFoundError as error: + except FileNotFoundError as error: print(error) - diff --git a/Flappy Bird - created with tkinter/Settings.py b/Flappy Bird - created with tkinter/Settings.py index c8d9e3a5590..f3a9fee6ddb 100644 --- a/Flappy Bird - created with tkinter/Settings.py +++ b/Flappy Bird - created with tkinter/Settings.py @@ -1,6 +1,6 @@ +import os from json import dumps from json import loads -import os class Settings(object): @@ -8,60 +8,59 @@ class Settings(object): Classe com todas as configurações do jogo """ - #Configurações da janela + # Configurações da janela window_name = "Flappy Bird" - window_rz = (False,False) + window_rz = (False, False) window_fullscreen = True window_width = None window_height = None - #Configurações dos botões + # Configurações dos botões button_width = 22 button_height = 17 button_bg = "black" button_fg = "white" button_activebackground = "black" - button_font = ("Impact",40) + button_font = ("Impact", 40) button_position_y = 85 button_cursor = "hand2" - #Configurações da imagem do placar do jogador + # Configurações da imagem do placar do jogador scoreboard_width = 40 scoreboard_height = 40 scoreboard_position_y = 50 - #Configurações de texto do placar + # Configurações de texto do placar text_font = "Autumn" text_fill = "White" - #Configurações do título do jogo + # Configurações do título do jogo title_width = 35 title_height = 15 title_position_y = 15 - #Eventos - bird_event = "" + # Eventos + bird_event = "" window_fullscreen_event = "" window_start_event = "" window_exit_event = "" - #Caminhos de arquivos + # Caminhos de arquivos background_fp = "Images/background.png" bird_fp = "Images/bird.png" startButton_fp = "Images/start_button.png" exitButton_fp = "Images/exit_button.png" - tube_fp = ["Images/tube.png","Images/tube_mouth.png"] + tube_fp = ["Images/tube.png", "Images/tube_mouth.png"] title_fp = "Images/title.png" scoreboard_fp = "Images/scoreboard.png" score_fp = "Data/scr.txt" settings_fp = "Data/settings.json" - #Configurações de animação + # Configurações de animação background_animation = True - #Junta todos os diretórios em uma lista - images_fp = [background_fp,bird_fp,startButton_fp,exitButton_fp,tube_fp[0],tube_fp[1],title_fp] - + # Junta todos os diretórios em uma lista + images_fp = [background_fp, bird_fp, startButton_fp, exitButton_fp, tube_fp[0], tube_fp[1], title_fp] def setOptions(self): """ @@ -69,41 +68,40 @@ def setOptions(self): Caso o arquivo não exista, será criado um com as configurações padrões. """ - #Alguns atributos que podem ser alterados + # Alguns atributos que podem ser alterados attributes = "window_fullscreen,window_width,window_height".split(',') - #Tenta abrir o arquivo parar leitura + # Tenta abrir o arquivo parar leitura try: - file = open(self.settings_fp,'r') + file = open(self.settings_fp, 'r') data = loads(file.read()) file.close() - #Define os atributos com os valores obtidos do arquivo desde que sejam - #referentes à eventos ou estejam na lista de atributos permitidos. + # Define os atributos com os valores obtidos do arquivo desde que sejam + # referentes à eventos ou estejam na lista de atributos permitidos. for attr in data: - if "event" in attr or attr in attributes: - setattr(Settings,attr,data[attr]) + if "event" in attr or attr in attributes: + setattr(Settings, attr, data[attr]) - #Caso não exista um arquivo para obter as configurações, ele será criado + # Caso não exista um arquivo para obter as configurações, ele será criado except: - #Caso não exista o diretório, o mesmo será criado. + # Caso não exista o diretório, o mesmo será criado. if not os.path.exists(os.path.split(self.settings_fp)[0]): os.mkdir(os.path.split(self.settings_fp)[0]) - - file = open(self.settings_fp,'w') + + file = open(self.settings_fp, 'w') data = dict() - #Armazena no arquivo atributos com seus valores padrões desde que sejam - #referentes à eventos ou estejam na lista de atributos permitidos. + # Armazena no arquivo atributos com seus valores padrões desde que sejam + # referentes à eventos ou estejam na lista de atributos permitidos. for attr in Settings.__dict__: if "event" in attr or attr in attributes: data[attr] = Settings.__dict__[attr] - - #Coloca as informações no arquivo e o fecha - file.write(dumps(data,indent=2)) + + # Coloca as informações no arquivo e o fecha + file.write(dumps(data, indent=2)) file.close() - diff --git a/Flappy Bird - created with tkinter/Tubes.py b/Flappy Bird - created with tkinter/Tubes.py index 27b2f783235..e6eb32ef69e 100644 --- a/Flappy Bird - created with tkinter/Tubes.py +++ b/Flappy Bird - created with tkinter/Tubes.py @@ -1,149 +1,152 @@ +from random import randint +from threading import Thread + from Background import Background from Bird import Bird from PIL.Image import open as openImage from PIL.ImageTk import PhotoImage -from threading import Thread -from random import randint + class Tubes(Thread): """ Classe para criar tubos """ - + __distance = 0 __move = 10 __pastTubes = [] - def __init__(self,background,bird,score_function=None,*screen_geometry,fp=("tube.png","tube_mourth"),animation_speed=50): + def __init__(self, background, bird, score_function=None, *screen_geometry, fp=("tube.png", "tube_mourth"), + animation_speed=50): - #Verifica os parâmetros passados e lança um erro caso algo esteja incorreto - if not isinstance(background,Background): raise TypeError("The background argument must be an instance of Background.") - if not len(fp) == 2: raise TypeError("The parameter fp should be a sequence containing the path of the images of the tube body and the tube mouth.") - if not isinstance(bird,Bird): raise TypeError("The birdargument must be an instance of Bird.") - if not callable(score_function): raise TypeError("The score_function argument must be a callable object.") + # Verifica os parâmetros passados e lança um erro caso algo esteja incorreto + if not isinstance(background, Background): raise TypeError( + "The background argument must be an instance of Background.") + if not len(fp) == 2: raise TypeError( + "The parameter fp should be a sequence containing the path of the images of the tube body and the tube mouth.") + if not isinstance(bird, Bird): raise TypeError("The birdargument must be an instance of Bird.") + if not callable(score_function): raise TypeError("The score_function argument must be a callable object.") Thread.__init__(self) - #Instância os parâmetros + # Instância os parâmetros self.__background = background self.image_path = fp self.__animation_speed = animation_speed self.__score_method = score_function - #Recebe a largura e altura do background + # Recebe a largura e altura do background self.__width = screen_geometry[0] self.__height = screen_geometry[1] - #Recebe o tamanho do pássaro + # Recebe o tamanho do pássaro self.__bird_w = bird.width self.__bird_h = bird.height - #Calcula a largura e altura da imagem - self.__imageWidth = (self.__width//100 ) * 10 - self.__imageHeight = (self.__height//100) * 5 + # Calcula a largura e altura da imagem + self.__imageWidth = (self.__width // 100) * 10 + self.__imageHeight = (self.__height // 100) * 5 - #Cria uma lista para guardar imagens dos tubos + # Cria uma lista para guardar imagens dos tubos try: self.deleteAll() except: self.__background.tubeImages = [] - #Cria uma lista somente para guardar as imagens futuras dos corpos dos tubos gerados - self.__background.tubeImages.append([]) + # Cria uma lista somente para guardar as imagens futuras dos corpos dos tubos gerados + self.__background.tubeImages.append([]) - #Carrega a imagem da boca do tubo + # Carrega a imagem da boca do tubo self.__background.tubeImages.append( self.getPhotoImage( image_path=self.image_path[1], width=self.__imageWidth, height=self.__imageHeight, closeAfter=True)[0] - ) + ) - #Carrega imagem do corpo do tubo + # Carrega imagem do corpo do tubo self.__background.tubeImages.append( self.getPhotoImage( image_path=self.image_path[0], width=self.__imageWidth, height=self.__imageHeight)[1] - ) + ) - #Calcula a distância mínima inicial entre os tubos - self.__minDistance = int(self.__imageWidth*4.5) + # Calcula a distância mínima inicial entre os tubos + self.__minDistance = int(self.__imageWidth * 4.5) self.__stop = False self.__tubes = [] - def createNewTubes(self): """ Método para criar 2 novos tubos (baixo e cima) numa mesma posição X """ - #Cria uma lista para armazenar as partes do corpo do tubo de cima + # Cria uma lista para armazenar as partes do corpo do tubo de cima tube1 = [] - #Define a posição X que o tubo de cima aparecerá inicialmente no background - width = self.__width+(self.__imageWidth) + # Define a posição X que o tubo de cima aparecerá inicialmente no background + width = self.__width + (self.__imageWidth) - #Define uma posição Y para o tubo aleatóriamente respeitando algumas regras que são: - #Espaço para o pássaro passar e espaço para adicionar o tubo de baixo. + # Define uma posição Y para o tubo aleatóriamente respeitando algumas regras que são: + # Espaço para o pássaro passar e espaço para adicionar o tubo de baixo. - height = randint(self.__imageHeight//2,self.__height-(self.__bird_h*2)-self.__imageHeight) + height = randint(self.__imageHeight // 2, self.__height - (self.__bird_h * 2) - self.__imageHeight) - #Cria e adiciona à lista do corpo do tubo de cima, a boca do tubo - tube1.append(self.__background.create_image(width,height,image=self.__background.tubeImages[1])) + # Cria e adiciona à lista do corpo do tubo de cima, a boca do tubo + tube1.append(self.__background.create_image(width, height, image=self.__background.tubeImages[1])) - #Cria uma nova imagem na lista de imagens com a altura sendo igual a posição Y do tubo de cima + # Cria uma nova imagem na lista de imagens com a altura sendo igual a posição Y do tubo de cima self.__background.tubeImages[0].append( - [self.getPhotoImage(image=self.__background.tubeImages[2],width=self.__imageWidth,height=height)[0],] - ) + [self.getPhotoImage(image=self.__background.tubeImages[2], width=self.__imageWidth, height=height)[0], ] + ) + + # Define a posição Y do corpo do tubo de cima + y = (height // 2) + 1 - (self.__imageHeight // 2) - #Define a posição Y do corpo do tubo de cima - y = (height//2)+1-(self.__imageHeight//2) + # Cria e adiciona à lista do corpo do tubo de cima, o corpo do tubo + tube1.append(self.__background.create_image(width, y, image=self.__background.tubeImages[0][-1][0])) - #Cria e adiciona à lista do corpo do tubo de cima, o corpo do tubo - tube1.append(self.__background.create_image(width,y,image=self.__background.tubeImages[0][-1][0])) - ############################################################################################################### ############################################################################################################### - #Cria uma lista para armazenar as partes do corpo do tubo de baixo + # Cria uma lista para armazenar as partes do corpo do tubo de baixo tube2 = [] - #A posição Y do tubo de baixo é calculada com base na posição do tubo de cima, mais o tamanho do pássaro - height = height + (self.__bird_h*2) + self.__imageHeight-1 - - #Cria e adiciona à lista do corpo do tubo de baixo, a boca do tubo - tube2.append(self.__background.create_image(width,height,image=self.__background.tubeImages[1])) + # A posição Y do tubo de baixo é calculada com base na posição do tubo de cima, mais o tamanho do pássaro + height = height + (self.__bird_h * 2) + self.__imageHeight - 1 - #Define a altura da imagem do corpo do tubo de baixo + # Cria e adiciona à lista do corpo do tubo de baixo, a boca do tubo + tube2.append(self.__background.create_image(width, height, image=self.__background.tubeImages[1])) + + # Define a altura da imagem do corpo do tubo de baixo height = self.__height - height - #Cria uma nova imagem na lista de imagens com a altura sendo igual a posição Y do tubo de baixo + # Cria uma nova imagem na lista de imagens com a altura sendo igual a posição Y do tubo de baixo self.__background.tubeImages[0][-1].append( - self.getPhotoImage(image=self.__background.tubeImages[2],width=self.__imageWidth,height=height)[0] - ) + self.getPhotoImage(image=self.__background.tubeImages[2], width=self.__imageWidth, height=height)[0] + ) - #Define a posição Y do corpo do tubo de baixo - y = (self.__height - (height//2)) + self.__imageHeight//2 + # Define a posição Y do corpo do tubo de baixo + y = (self.__height - (height // 2)) + self.__imageHeight // 2 - #Cria e adiciona à lista do corpo do tubo de baixo, o corpo do tubo - tube2.append(self.__background.create_image(width,y,image=self.__background.tubeImages[0][-1][1])) + # Cria e adiciona à lista do corpo do tubo de baixo, o corpo do tubo + tube2.append(self.__background.create_image(width, y, image=self.__background.tubeImages[0][-1][1])) - #Adiciona à lista de tubos os tubos de cima e de baixo da posição X - self.__tubes.append([tube1,tube2]) + # Adiciona à lista de tubos os tubos de cima e de baixo da posição X + self.__tubes.append([tube1, tube2]) - #Define a distância como sendo ZERO + # Define a distância como sendo ZERO self.__distance = 0 - def deleteAll(self): """ Método para deletar todos os tubos gerados """ - #Deleta os tubos gerados no background + # Deleta os tubos gerados no background for tubes in self.__tubes: for tube in tubes: for body in tube: @@ -152,10 +155,8 @@ def deleteAll(self): self.__background.clear() self.__background.tubeImages.clear() - @staticmethod - - def getPhotoImage(image=None,image_path=None,width=None,height=None,closeAfter=False): + def getPhotoImage(image=None, image_path=None, width=None, height=None, closeAfter=False): """ Retorna um objeto da classe PIL.ImageTk.PhotoImage de uma imagem e as imagens criadas de PIL.Image (photoImage, new, original) @@ -169,115 +170,109 @@ def getPhotoImage(image=None,image_path=None,width=None,height=None,closeAfter=F if not image: if not image_path: return - - #Abre a imagem utilizando o caminho dela + + # Abre a imagem utilizando o caminho dela image = openImage(image_path) - #Será redimesionada a imagem somente se existir um width ou height + # Será redimesionada a imagem somente se existir um width ou height if not width: width = image.width if not height: height = image.height - #Cria uma nova imagem já redimensionada - newImage = image.resize([width,height]) + # Cria uma nova imagem já redimensionada + newImage = image.resize([width, height]) - #Cria um photoImage + # Cria um photoImage photoImage = PhotoImage(newImage) - #Se closeAfter for True, ele fecha as imagens + # Se closeAfter for True, ele fecha as imagens if closeAfter: - - #Fecha a imagem nova + # Fecha a imagem nova newImage.close() newImage = None - #Fecha a imagem original + # Fecha a imagem original image.close() image = None - #Retorna o PhotoImage da imagem,a nova imagem que foi utilizada e a imagem original - return photoImage,newImage,image - + # Retorna o PhotoImage da imagem,a nova imagem que foi utilizada e a imagem original + return photoImage, newImage, image def move(self): """ Método para mover todos os tubos """ - #Cria uma variável auxilar para checar se o método de pontuar foi executado + # Cria uma variável auxilar para checar se o método de pontuar foi executado scored = False - #Move os tubos gerados no background + # Move os tubos gerados no background for tubes in self.__tubes: for tube in tubes: - - #Verifica se o pássaro passou do tubo. Caso sim, o método para pontuar será executado + + # Verifica se o pássaro passou do tubo. Caso sim, o método para pontuar será executado if not scored: - #Recebe a posição do cano + # Recebe a posição do cano x2 = self.__background.bbox(tube[0])[2] - #Se a posição "x2" do tubo for menor que a posição "x1" do pássaro e se ainda não tiver sido - #pontuado este mesmo cano, o método para pontuar será chamado. + # Se a posição "x2" do tubo for menor que a posição "x1" do pássaro e se ainda não tiver sido + # pontuado este mesmo cano, o método para pontuar será chamado. - if (self.__width/2)-(self.__bird_w/2)-self.__move < x2: - if x2 <= (self.__width/2)-(self.__bird_w/2): + if (self.__width / 2) - (self.__bird_w / 2) - self.__move < x2: + if x2 <= (self.__width / 2) - (self.__bird_w / 2): - #Verifica se o tubo está na lista de tubos passados + # Verifica se o tubo está na lista de tubos passados if not tube[0] in self.__pastTubes: - - #Chama o método para pontuar e adiciona o tubo pontuado à lista de tubos passados + # Chama o método para pontuar e adiciona o tubo pontuado à lista de tubos passados self.__score_method() self.__pastTubes.append(tube[0]) scored = True - #Move cada parte do copo do tubo no background + # Move cada parte do copo do tubo no background for body in tube: - self.__background.move(body,-self.__move,0) - + self.__background.move(body, -self.__move, 0) def run(self): """ Método para gerar os tubos no background e fazer a sua animação em um loop infinito """ - #Se o método "stop" tiver sido chamado, a animação será encerrada - if self.__stop: return + # Se o método "stop" tiver sido chamado, a animação será encerrada + if self.__stop: return - #Se os tubos ( cima e baixo ) de uma posição X tiverem sumido da área do background, + # Se os tubos ( cima e baixo ) de uma posição X tiverem sumido da área do background, # eles serão apagados juntamente com suas imagens e todos os seus dados. if len(self.__tubes) >= 1 and self.__background.bbox(self.__tubes[0][0][0])[2] <= 0: - #Apaga todo o corpo do tubo dentro do background + # Apaga todo o corpo do tubo dentro do background for tube in self.__tubes[0]: for body in tube: self.__background.delete(body) - #Remove os tubos ( cima e baixo ) da lista de tubos + # Remove os tubos ( cima e baixo ) da lista de tubos self.__background.tubeImages[0].remove(self.__background.tubeImages[0][0]) - #Remove a imagem do corpo do tubo da lista de imagens + # Remove a imagem do corpo do tubo da lista de imagens self.__tubes.remove(self.__tubes[0]) - #Remove o primeiro objeto da lista de tubos passados + # Remove o primeiro objeto da lista de tubos passados self.__pastTubes.remove(self.__pastTubes[0]) - - #Se a distancia entre o último tubo criado e o lado "x2" do background for maior que a distância - #mínima estabelecida, então um novo tubo será criado. + # Se a distancia entre o último tubo criado e o lado "x2" do background for maior que a distância + # mínima estabelecida, então um novo tubo será criado. if self.__distance >= self.__minDistance: self.createNewTubes() - else: - #Aumenta a distancia conforme os tubos se movem - self.__distance +=self.__move - - #Move os tubos + else: + # Aumenta a distancia conforme os tubos se movem + self.__distance += self.__move + + # Move os tubos self.move() - - #Executa novamente o método em um determinado tempo - self.__background.after(self.__animation_speed,self.run) - + + # Executa novamente o método em um determinado tempo + self.__background.after(self.__animation_speed, self.run) def stop(self): """ @@ -285,5 +280,3 @@ def stop(self): """ self.__stop = True - - diff --git a/Google_Image_Downloader/create_dir.py b/Google_Image_Downloader/create_dir.py index f8c80418278..e03ee49fefd 100644 --- a/Google_Image_Downloader/create_dir.py +++ b/Google_Image_Downloader/create_dir.py @@ -10,22 +10,22 @@ project directory. """ -from shutil import copytree -from shutil import move from os import chdir -from os.path import exists -from os.path import pardir from os import makedirs from os import removedirs from os import rename +from os.path import exists +from os.path import pardir +from shutil import copytree +from shutil import move # Creates a directory def create_directory(name): - if exists(pardir+"\\"+name): + if exists(pardir + "\\" + name): print('Folder already exists... Cannot Overwrite this') else: - makedirs(pardir+"\\"+name) + makedirs(pardir + "\\" + name) # Deletes a directory @@ -51,9 +51,9 @@ def backup_files(name_dir, folder): # Move folder to specific location # Overwrites the file if it already exists def move_folder(filename, name_dir, folder): - if not exists(name_dir+":\\"+folder): - makedirs(name_dir+':\\'+folder) - move(filename, name_dir+":\\"+folder+'\\') + if not exists(name_dir + ":\\" + folder): + makedirs(name_dir + ':\\' + folder) + move(filename, name_dir + ":\\" + folder + '\\') """ diff --git a/Google_Image_Downloader/image_grapper.py b/Google_Image_Downloader/image_grapper.py index d6e19018f7c..6cee33ea576 100644 --- a/Google_Image_Downloader/image_grapper.py +++ b/Google_Image_Downloader/image_grapper.py @@ -1,15 +1,15 @@ #!/usr/bin/python # -*- coding: utf-8 -*- +import json from os import chdir, system -import requests -from bs4 import BeautifulSoup -from urllib.request import urlopen, Request -from urllib.parse import urlencode from os import walk -import json from os.path import curdir -from urllib.request import urlretrieve from os.path import pardir +from urllib.parse import urlencode +from urllib.request import urlopen, Request + +import requests +from bs4 import BeautifulSoup from create_dir import create_directory GOOGLE_IMAGE = \ @@ -22,7 +22,7 @@ 'Accept-Encoding': 'none', 'Accept-Language': 'en-US,en;q=0.8', 'Connection': 'keep-alive', - } +} FX = { 1: 'search_for_image', @@ -30,17 +30,17 @@ 3: 'view_images_directory', 4: 'set_directory', 5: 'quit', - } +} # Download images from google images def search_for_image(): - print ('Enter data to download Images: ') + print('Enter data to download Images: ') data = input() search_query = {'q': data} search = urlencode(search_query) - print (search) + print(search) g = GOOGLE_IMAGE + search request = Request(g, headers=usr_agent) r = urlopen(request).read() @@ -70,11 +70,11 @@ def download_wallpapers_1080p(): cont = set() # Stores the links of images temp = set() # Refines the links to download images - print ('Enter data to download wallpapers: ') + print('Enter data to download wallpapers: ') data = input() search_query = {'q': data} search = urlencode(search_query) - print (search) + print(search) g = WALLPAPERS_KRAFT + search request = Request(g, headers=usr_agent) r = urlopen(request).read() @@ -84,12 +84,11 @@ def download_wallpapers_1080p(): if 'wallpaperscraft.com/download' in links.get('href'): cont.add(links.get('href')) for re in cont: - # print all valid links # print('https://wallpaperscraft.com/image/' + re[31:-10] + '_' + re[-9:] + '.jpg') temp.add('https://wallpaperscraft.com/image/' + re[31:-10] + '_' - + re[-9:] + '.jpg') + + re[-9:] + '.jpg') # Goes to Each link and downloads high resolution images @@ -104,28 +103,29 @@ def download_wallpapers_1080p(): return True + ################### def view_images_directory(): for (folders, subfolder, files) in walk(curdir): for folder in subfolder: - print (folder) + print(folder) return True - ############# def set_directory(): - print ('Enter the directory to be set: ') + print('Enter the directory to be set: ') data = input() chdir(data + ':\\') - print ('Enter name for the folder: ') + print('Enter name for the folder: ') data = input() create_directory(data) return True + ############## def quit(): - print (''' + print(''' -------------------------***Thank You For Using***------------------------- ''') return False @@ -133,7 +133,7 @@ def quit(): run = True -print (''' +print(''' ***********[First Creating Folder To Save Your Images}*********** ''') @@ -142,7 +142,7 @@ def quit(): chdir(DEFAULT_DIRECTORY) count = 0 while run: - print (''' + print(''' -------------------------WELCOME------------------------- 1. Search for image 2. Download Wallpapers 1080p @@ -163,5 +163,4 @@ def quit(): else: system('clear') print("You have attemted 5 times , try again later") - run = False - + run = False diff --git a/Google_News.py b/Google_News.py index 1f5484b14ba..eef39400e90 100644 --- a/Google_News.py +++ b/Google_News.py @@ -1,34 +1,34 @@ -import bs4 -import lxml #xml parser import ssl -from bs4 import BeautifulSoup as soup from urllib.request import urlopen -def news(xml_news_url): +from bs4 import BeautifulSoup as soup + +def news(xml_news_url): '''Print select details from a html response containing xml @param xml_news_url: url to parse ''' context = ssl._create_unverified_context() - Client=urlopen(xml_news_url, context=context) - xml_page=Client.read() + Client = urlopen(xml_news_url, context=context) + xml_page = Client.read() Client.close() - soup_page=soup(xml_page,"xml") + soup_page = soup(xml_page, "xml") - news_list=soup_page.findAll("item") + news_list = soup_page.findAll("item") for news in news_list: print(f'news title: {news.title.text}') print(f'news link: {news.link.text}') print(f'news pubDate: {news.pubDate.text}') - print("+-"*20,"\n\n") + print("+-" * 20, "\n\n") + -#you can add google news 'xml' URL here for any country/category -news_url="https://news.google.com/news/rss/?ned=us&gl=US&hl=en" -sports_url="https://news.google.com/news/rss/headlines/section/topic/SPORTS.en_in/Sports?ned=in&hl=en-IN&gl=IN" +# you can add google news 'xml' URL here for any country/category +news_url = "https://news.google.com/news/rss/?ned=us&gl=US&hl=en" +sports_url = "https://news.google.com/news/rss/headlines/section/topic/SPORTS.en_in/Sports?ned=in&hl=en-IN&gl=IN" -#now call news function with any of these url or BOTH +# now call news function with any of these url or BOTH news(news_url) news(sports_url) diff --git a/GroupSms_Way2.py b/GroupSms_Way2.py index b02a737bd3c..6e05d7dcfb8 100644 --- a/GroupSms_Way2.py +++ b/GroupSms_Way2.py @@ -1,8 +1,10 @@ from __future__ import print_function -import urllib2 -import cookielib -from getpass import getpass + import sys +from getpass import getpass + +import cookielib +import urllib2 try: input = raw_input diff --git a/Guess_the_number_game.py b/Guess_the_number_game.py index 251e6a3c63b..e5887c59688 100644 --- a/Guess_the_number_game.py +++ b/Guess_the_number_game.py @@ -1,8 +1,9 @@ # using codeSkulpter -import simplegui import random +import simplegui + def new_game(): global num @@ -11,19 +12,19 @@ def new_game(): def range_of_100(): global num - num = random.randrange(0,100) + num = random.randrange(0, 100) print("your range is 0-100") def range_of_1000(): global num - num = random.randrange(0,1000) + num = random.randrange(0, 1000) print("range is 0-1000") def input_guess(guess): global num - print("Your Guess is " , guess) + print("Your Guess is ", guess) num1 = int(guess) if num1 == num: print("Correct") @@ -33,9 +34,9 @@ def input_guess(guess): print("Lower") -frame = simplegui.create_frame("Guess The Number",200,200) -frame.add_button("range[0-1000)",range(1000)) -frame.add_button("range[0-100)",range(100)) -frame.add_input("enter your guess",input_guess,200) +frame = simplegui.create_frame("Guess The Number", 200, 200) +frame.add_button("range[0-1000)", range(1000)) +frame.add_button("range[0-100)", range(100)) +frame.add_input("enter your guess", input_guess, 200) frame.start() new_game() diff --git a/Guessing_Game.py b/Guessing_Game.py index 66663390d0c..0ace9919f0c 100644 --- a/Guessing_Game.py +++ b/Guessing_Game.py @@ -1,20 +1,19 @@ import random -a = comGuess = random.randint(0,100) #a and comGuess is initialised with a random number between 0 and 100 +a = comGuess = random.randint(0, 100) # a and comGuess is initialised with a random number between 0 and 100 +while True: # loop will run until encountered with the break statement(user enters the right answer) + userGuess = int(input("Enter your guessed no. b/w 0-100:")) # user input for guessing the number + if userGuess < comGuess: # if number guessed by user is lesser than the random number than the user is told to guess higher and the random number comGuess is changed to a new random number between a and 100 + print("Guess Higher") + comGuess = random.randint(a, 100) + a += 1 -while True: #loop will run until encountered with the break statement(user enters the right answer) - userGuess = int(input("Enter your guessed no. b/w 0-100:")) #user input for guessing the number - if userGuess < comGuess: #if number guessed by user is lesser than the random number than the user is told to guess higher and the random number comGuess is changed to a new random number between a and 100 - print("Guess Higher") - comGuess = random.randint(a,100) - a += 1 + elif userGuess > comGuess: # if number guessed by user is greater than the random number than the user is told to guess lower and the random number comGuess is changed to a new random number between 0 and a + print("Guess Lower") + comGuess = random.randint(0, a) + a += 1 - elif userGuess > comGuess:#if number guessed by user is greater than the random number than the user is told to guess lower and the random number comGuess is changed to a new random number between 0 and a - print("Guess Lower") - comGuess = random.randint(0,a) - a += 1 - - else : #if guessed correctly the loop will break and the player will win - print ("Guessed Corectly") - break + else: # if guessed correctly the loop will break and the player will win + print("Guessed Corectly") + break diff --git a/Infix_to_Postfix.py b/Infix_to_Postfix.py index df343d59ab9..f97d575a658 100644 --- a/Infix_to_Postfix.py +++ b/Infix_to_Postfix.py @@ -1,95 +1,94 @@ # Python program to convert infix expression to postfix # Class to convert the expression -class Conversion: - - # Constructor to initialize the class variables - def __init__(self, capacity): - self.top = -1 - self.capacity = capacity - # This array is used a stack - self.array = [] - # Precedence setting - self.output = [] - self.precedence = {'+':1, '-':1, '*':2, '/':2, '^':3} - - # check if the stack is empty - def isEmpty(self): - return True if self.top == -1 else False - - # Return the value of the top of the stack - def peek(self): - return self.array[-1] - - # Pop the element from the stack - def pop(self): - if not self.isEmpty(): - self.top -= 1 - return self.array.pop() - else: - return "$" - - # Push the element to the stack - def push(self, op): - self.top += 1 - self.array.append(op) - - # A utility function to check is the given character - # is operand - def isOperand(self, ch): - return ch.isalpha() - - # Check if the precedence of operator is strictly - # less than top of stack or not - def notGreater(self, i): - try: - a = self.precedence[i] - b = self.precedence[self.peek()] - return True if a <= b else False - except KeyError: - return False - - # The main function that converts given infix expression - # to postfix expression - def infixToPostfix(self, exp): - - # Iterate over the expression for conversion - for i in exp: - # If the character is an operand, - # add it to output - if self.isOperand(i): - self.output.append(i) - - # If the character is an '(', push it to stack - elif i == '(': - self.push(i) - - # If the scanned character is an ')', pop and - # output from the stack until and '(' is found - elif i == ')': - while( (not self.isEmpty()) and self.peek() != '('): - a = self.pop() - self.output.append(a) - if (not self.isEmpty() and self.peek() != '('): - return -1 - else: - self.pop() - - # An operator is encountered - else: - while(not self.isEmpty() and self.notGreater(i)): - self.output.append(self.pop()) - self.push(i) - - # pop all the operator from the stack - while not self.isEmpty(): - self.output.append(self.pop()) - - print("".join(self.output)) - -# Driver program to test above function -exp = "a+b*(c^d-e)^(f+g*h)-i" -obj = Conversion(len(exp)) -obj.infixToPostfix(exp) +class Conversion: + + # Constructor to initialize the class variables + def __init__(self, capacity): + self.top = -1 + self.capacity = capacity + # This array is used a stack + self.array = [] + # Precedence setting + self.output = [] + self.precedence = {'+': 1, '-': 1, '*': 2, '/': 2, '^': 3} + + # check if the stack is empty + def isEmpty(self): + return True if self.top == -1 else False + + # Return the value of the top of the stack + def peek(self): + return self.array[-1] + + # Pop the element from the stack + def pop(self): + if not self.isEmpty(): + self.top -= 1 + return self.array.pop() + else: + return "$" + + # Push the element to the stack + def push(self, op): + self.top += 1 + self.array.append(op) + + # A utility function to check is the given character + # is operand + def isOperand(self, ch): + return ch.isalpha() + + # Check if the precedence of operator is strictly + # less than top of stack or not + def notGreater(self, i): + try: + a = self.precedence[i] + b = self.precedence[self.peek()] + return True if a <= b else False + except KeyError: + return False + # The main function that converts given infix expression + # to postfix expression + def infixToPostfix(self, exp): + # Iterate over the expression for conversion + for i in exp: + # If the character is an operand, + # add it to output + if self.isOperand(i): + self.output.append(i) + + # If the character is an '(', push it to stack + elif i == '(': + self.push(i) + + # If the scanned character is an ')', pop and + # output from the stack until and '(' is found + elif i == ')': + while ((not self.isEmpty()) and self.peek() != '('): + a = self.pop() + self.output.append(a) + if (not self.isEmpty() and self.peek() != '('): + return -1 + else: + self.pop() + + # An operator is encountered + else: + while (not self.isEmpty() and self.notGreater(i)): + self.output.append(self.pop()) + self.push(i) + + # pop all the operator from the stack + while not self.isEmpty(): + self.output.append(self.pop()) + + print("".join(self.output)) + + +# Driver program to test above function +exp = "a+b*(c^d-e)^(f+g*h)-i" +obj = Conversion(len(exp)) +obj.infixToPostfix(exp) diff --git a/Koch Curve/koch curve.py b/Koch Curve/koch curve.py index af58c9f1828..42c8cdb5132 100644 --- a/Koch Curve/koch curve.py +++ b/Koch Curve/koch curve.py @@ -1,33 +1,34 @@ -#importing the libraries -#turtle standard graphics library for python -from turtle import * +# importing the libraries +# turtle standard graphics library for python -#function to create koch snowflake or koch curve + +# function to create koch snowflake or koch curve def snowflake(lengthSide, levels): if levels == 0: forward(lengthSide) return lengthSide /= 3.0 - snowflake(lengthSide, levels-1) + snowflake(lengthSide, levels - 1) left(60) - snowflake(lengthSide, levels-1) + snowflake(lengthSide, levels - 1) right(120) - snowflake(lengthSide, levels-1) + snowflake(lengthSide, levels - 1) left(60) - snowflake(lengthSide, levels-1) + snowflake(lengthSide, levels - 1) + -#main function +# main function if __name__ == "__main__": - speed(0) #defining the speed of the turtle - length = 300.0 # - penup() #Pull the pen up – no drawing when moving. - #Move the turtle backward by distance, opposite to the direction the turtle is headed. - #Do not change the turtle’s heading. - backward(length/2.0) + speed(0) # defining the speed of the turtle + length = 300.0 # + penup() # Pull the pen up – no drawing when moving. + # Move the turtle backward by distance, opposite to the direction the turtle is headed. + # Do not change the turtle’s heading. + backward(length / 2.0) pendown() for i in range(3): - #Pull the pen down – drawing when moving. - snowflake(length, 4) - right(120) - #To control the closing windows of the turtle - mainloop() \ No newline at end of file + # Pull the pen down – drawing when moving. + snowflake(length, 4) + right(120) + # To control the closing windows of the turtle + mainloop() diff --git a/Memory_game.py b/Memory_game.py index 1a95616be09..470310e95ed 100644 --- a/Memory_game.py +++ b/Memory_game.py @@ -1,15 +1,19 @@ -import simplegui import random +import simplegui + + def new_game(): global card3, po, state, exposed, card1 + def create(card): while len(card) != 8: - num = random.randrange(0 ,8) + num = random.randrange(0, 8) if num not in card: card.append(num) return card - card3 = [] + + card3 = [] card1 = [] card2 = [] po = [] @@ -19,35 +23,38 @@ def create(card): random.shuffle(card1) state = 0 exposed = [] - for i in range(0,16,1): + for i in range(0, 16, 1): exposed.insert(i, False) - + + def mouseclick(pos): global card3, po, state, exposed, card1 if state == 2: if card3[0] != card3[1]: exposed[po[0]] = False exposed[po[1]] = False - card3 = [] + card3 = [] state = 0 po = [] - ind = pos[0]//50 + ind = pos[0] // 50 card3.append(card1[ind]) po.append(ind) if exposed[ind] == False and state < 2: exposed[ind] = True state += 1 + def draw(canvas): global card1 gap = 0 - for i in range(0,16,1): + for i in range(0, 16, 1): if exposed[i] == False: - canvas.draw_polygon( [ [0 + gap,0], [0 + gap,100] ,[50 + gap,100],[50 + gap,0]],1 ,"Black","Green") + canvas.draw_polygon([[0 + gap, 0], [0 + gap, 100], [50 + gap, 100], [50 + gap, 0]], 1, "Black", "Green") elif exposed[i] == True: - canvas.draw_text( str(card1[i]), [ 15 + gap, 65], 50, 'White') + canvas.draw_text(str(card1[i]), [15 + gap, 65], 50, 'White') gap += 50 + frame = simplegui.create_frame("Memory", 800, 100) frame.add_button("Reset", new_game) label = frame.add_label("Turns = 0") diff --git a/Merge-sort.py b/Merge-sort.py index e9a4eaf2424..22b86ac2e2e 100644 --- a/Merge-sort.py +++ b/Merge-sort.py @@ -1,47 +1,52 @@ -#merge sort +# merge sort -l = [] #declaring list l +l = [] # declaring list l -n = int(input("Enter number of elements in the list: "))# taking value from user +n = int(input("Enter number of elements in the list: ")) # taking value from user for i in range(n): - temp = int(input("Enter element"+str(i+1)+': ')) + temp = int(input("Enter element" + str(i + 1) + ': ')) l += [temp] -def merge_sort(L): - mid = int( (len(L) - 1)/2 ) #calculated value of middle index of array +def merge_sort(L): + mid = int((len(L) - 1) / 2) # calculated value of middle index of array - if len(L) >mid+2: #this loop will run when length of array is greater than 2 - a = merge_sort(L[0:mid]) #a is initialised with left side of the array taking reference as middle index - b = merge_sort(L[mid:len(L)]) #b is initialised with right side of the array taking reference as middle index + if len(L) > mid + 2: # this loop will run when length of array is greater than 2 + a = merge_sort(L[0:mid]) # a is initialised with left side of the array taking reference as middle index + b = merge_sort(L[mid:len(L)]) # b is initialised with right side of the array taking reference as middle index - elif len(L) == 2: #this loop will when length of array is equal to 2 - a = [L[0]] #a is initiliased with the first element of array - b = [L[1]] #b is initiliased with the second element of array + elif len(L) == 2: # this loop will when length of array is equal to 2 + a = [L[0]] # a is initiliased with the first element of array + b = [L[1]] # b is initiliased with the second element of array else: return L - + i = 0 j = 0 new = [] - while (i!= len(a) or j != len(b)): #this loop will run until i is not equal to the lenth of array a or j is equal to length of array b + while (i != len(a) or j != len( + b)): # this loop will run until i is not equal to the lenth of array a or j is equal to length of array b - if i < len(a) and j < len(b): #checking if value of i and j is lesser than length of array a and b respectively + if i < len(a) and j < len( + b): # checking if value of i and j is lesser than length of array a and b respectively + + if a[i] < b[j]: # if the element on the left side is lesser than the element on the right side + new += [a[i]] # then it will be directly added to the array new + i += 1 # i is increased by 1 - if a[i] < b[j]: #if the element on the left side is lesser than the element on the right side - new += [a[i]] #then it will be directly added to the array new - i += 1 #i is increased by 1 - else: - new +=[b[j]] #if element on the right side is lesser than the element on the left side then right side element is added to the array new - j += 1 #j increased by 1 + new += [b[ + j]] # if element on the right side is lesser than the element on the left side then right side element is added to the array new + j += 1 # j increased by 1 - elif i == len(a) and j != len(b): #if i gets equal to the length of array a then all the elements of array b are directly added to the array new + elif i == len(a) and j != len( + b): # if i gets equal to the length of array a then all the elements of array b are directly added to the array new new += [b[j]] j += 1 - - elif j == len(b) and i != len(a):#if j gets equal to the length of array b then all the elements of array a are directly added to the array new + + elif j == len(b) and i != len( + a): # if j gets equal to the length of array b then all the elements of array a are directly added to the array new new += [a[i]] i += 1 @@ -50,4 +55,5 @@ def merge_sort(L): return new + print(merge_sort(l)) diff --git a/MobiusFunction.py b/MobiusFunction.py index c7476e4eed4..ae9e6b0a123 100644 --- a/MobiusFunction.py +++ b/MobiusFunction.py @@ -1,4 +1,3 @@ - def is_square_free(factors): ''' This functions takes a list of prime factors as input. @@ -8,7 +7,7 @@ def is_square_free(factors): if factors.count(i) > 1: return False return True - + def prime_factors(n): ''' @@ -26,15 +25,16 @@ def prime_factors(n): factors.append(n) return factors + def mobius_function(n): ''' Defines Mobius function ''' factors = prime_factors(n) if is_square_free(factors): - if len(factors)%2 == 0: + if len(factors) % 2 == 0: return 1 - elif len(factors)%2 != 0: + elif len(factors) % 2 != 0: return -1 else: return 0 diff --git a/MySQL_Databses.py b/MySQL_Databses.py index 0cf9dad5dd9..93ceb6fd709 100644 --- a/MySQL_Databses.py +++ b/MySQL_Databses.py @@ -1,22 +1,19 @@ import mysql.connector - # MySQl databses details mydb = mysql.connector.connect( - host="localhost", - user="root", - passwd="", - database="db_name" + host="localhost", + user="root", + passwd="", + database="db_name" ) mycursor = mydb.cursor() - - -#Execute SQL Query =>>>> mycursor.execute("SQL Query") +# Execute SQL Query =>>>> mycursor.execute("SQL Query") mycursor.execute("SELECT column FROM table") myresult = mycursor.fetchall() for x in myresult: - print(x) + print(x) diff --git a/Organise.py b/Organise.py index d63d24d0aca..00d3155a241 100644 --- a/Organise.py +++ b/Organise.py @@ -1,57 +1,65 @@ -from __future__ import print_function +from __future__ import print_function + import os -import sys import shutil +import sys -EXT_VIDEO_LIST = ['FLV', 'WMV', 'MOV', 'MP4', 'MPEG', '3GP', 'MKV','AVI'] +EXT_VIDEO_LIST = ['FLV', 'WMV', 'MOV', 'MP4', 'MPEG', '3GP', 'MKV', 'AVI'] EXT_IMAGE_LIST = ['JPG', 'JPEG', 'GIF', 'PNG', 'SVG'] -EXT_DOCUMENT_LIST = ['DOC', 'DOCX', 'PPT', 'PPTX', 'PAGES', 'PDF', 'ODT', 'ODP', 'XLSX', 'XLS', 'ODS', 'TXT', 'IN', 'OUT', 'MD'] +EXT_DOCUMENT_LIST = ['DOC', 'DOCX', 'PPT', 'PPTX', 'PAGES', 'PDF', 'ODT', 'ODP', 'XLSX', 'XLS', 'ODS', 'TXT', 'IN', + 'OUT', 'MD'] EXT_MUSIC_LIST = ['MP3', 'WAV', 'WMA', 'MKA', 'AAC', 'MID', 'RA', 'RAM', 'RM', 'OGG'] EXT_CODE_LIST = ['CPP', 'RB', 'PY', 'HTML', 'CSS', 'JS'] -EXT_EXECUTABLE_LIST = ['LNK','DEB', 'EXE', 'SH', 'BUNDLE'] +EXT_EXECUTABLE_LIST = ['LNK', 'DEB', 'EXE', 'SH', 'BUNDLE'] EXT_COMPRESSED_LIST = ['RAR', 'JAR', 'ZIP', 'TAR', 'MAR', 'ISO', 'LZ', '7ZIP', 'TGZ', 'GZ', 'BZ2'] # Taking the location of the Folder to Arrange try: - destLocation = str(sys.argv[1]) + destLocation = str(sys.argv[1]) except IndexError: - destLocation = str(input('Enter the Path of directory: ')) + destLocation = str(input('Enter the Path of directory: ')) + # When we make a folder that already exist then WindowsError happen # Changing directory may give WindowsError def ChangeDirectory(dir): - try: - os.chdir(dir) - except WindowsError: - print ('Error! Cannot change the Directory') - print ('Enter a valid directory!') - ChangeDirectory(str(input('Enter the Path of directory: '))) + try: + os.chdir(dir) + except WindowsError: + print('Error! Cannot change the Directory') + print('Enter a valid directory!') + ChangeDirectory(str(input('Enter the Path of directory: '))) + + ChangeDirectory(destLocation) + def Organize(dirs, name): - try: - os.mkdir(name) - print ('{} Folder Created'.format(name)) - except WindowsError: - print ('{} Folder Exist'.format(name)) - - src = '{}\\{}'.format(destLocation, dirs) - dest = '{}\{}'.format(destLocation, name) + try: + os.mkdir(name) + print('{} Folder Created'.format(name)) + except WindowsError: + print('{} Folder Exist'.format(name)) + + src = '{}\\{}'.format(destLocation, dirs) + dest = '{}\{}'.format(destLocation, name) - os.chdir(dest) - shutil.move(src, '{}\\{}'.format(dest, dirs)) + os.chdir(dest) + shutil.move(src, '{}\\{}'.format(dest, dirs)) + + print(os.getcwd()) + os.chdir(destLocation) - print(os.getcwd()) - os.chdir(destLocation) TYPES_LIST = ['Video', 'Images', 'Documents', 'Music', 'Codes', 'Executables', 'Compressed'] for dirs in os.listdir(os.getcwd()): - if 1: - for name, extensions_list in zip(TYPES_LIST, [EXT_VIDEO_LIST, EXT_IMAGE_LIST, EXT_DOCUMENT_LIST, EXT_MUSIC_LIST, EXT_CODE_LIST, EXT_EXECUTABLE_LIST, EXT_COMPRESSED_LIST]): - if dirs.split('.')[-1].upper() in extensions_list: - Organize(dirs, name) - else: - if dirs not in TYPES_LIST: - Organize(dirs, 'Folders') - -print ('Done Arranging Files and Folder in your specified directory') + if 1: + for name, extensions_list in zip(TYPES_LIST, [EXT_VIDEO_LIST, EXT_IMAGE_LIST, EXT_DOCUMENT_LIST, EXT_MUSIC_LIST, + EXT_CODE_LIST, EXT_EXECUTABLE_LIST, EXT_COMPRESSED_LIST]): + if dirs.split('.')[-1].upper() in extensions_list: + Organize(dirs, name) + else: + if dirs not in TYPES_LIST: + Organize(dirs, 'Folders') + +print('Done Arranging Files and Folder in your specified directory') diff --git a/PDF/basic.py b/PDF/basic.py index 40c21ba8aa3..55927fb12ed 100644 --- a/PDF/basic.py +++ b/PDF/basic.py @@ -12,25 +12,23 @@ pdf.set_title('Generating PDF with Python') pdf.add_page() - # Set Font family Courier with font size 28 -pdf.set_font("Courier",'',18) +pdf.set_font("Courier", '', 18) # Add Text at (0,50) -pdf.text(0,50,"Example to generate PDF in python.") +pdf.text(0, 50, "Example to generate PDF in python.") # Set Font Family Courier with italic and font size 28 -pdf.set_font("Courier",'i',28) -pdf.text(0,60,"This is an italic text") # Write text at 0,60 - +pdf.set_font("Courier", 'i', 28) +pdf.text(0, 60, "This is an italic text") # Write text at 0,60 # Draw a Rectangle at (10,100) with Width 60,30 -pdf.rect(10,100,60,30,'D') +pdf.rect(10, 100, 60, 30, 'D') # Set Fill color -pdf.set_fill_color(255,0,0) # Red = (255,0,0) +pdf.set_fill_color(255, 0, 0) # Red = (255,0,0) # Draw a Circle at (10,135) with diameter 50 -pdf.ellipse(10,135,50,50,'F') +pdf.ellipse(10, 135, 50, 50, 'F') # Save the Output at Local File -pdf.output('output.pdf', 'F') \ No newline at end of file +pdf.output('output.pdf', 'F') diff --git a/PDF/header_footer.py b/PDF/header_footer.py index e96b6cbdd5b..49f2bcf3611 100644 --- a/PDF/header_footer.py +++ b/PDF/header_footer.py @@ -1,24 +1,25 @@ from fpdf import FPDF + + # Author: @NavonilDas class MyPdf(FPDF): def header(self): # Uncomment the line below to add logo if needed # self.image('somelogo.png',12,10,25,25) # Draw Image ar (12,10) with height = 25 and width = 25 - self.set_font('Arial','B',18) - self.text(27,10,'Generating PDF With python') + self.set_font('Arial', 'B', 18) + self.text(27, 10, 'Generating PDF With python') self.ln(10) - + def footer(self): # Set Position at 1cm (10mm) From Bottom self.set_y(-10) # Arial italic 8 self.set_font('Arial', 'I', 8) # set Page number at the bottom - self.cell(0, 10,'Page No {}'.format(self.page_no()), 0, 0, 'C') + self.cell(0, 10, 'Page No {}'.format(self.page_no()), 0, 0, 'C') pass -from fpdf import FPDF pdf = MyPdf() # Set Author Name of the PDF @@ -29,15 +30,14 @@ def footer(self): pdf.set_title('Generating PDF with Python') pdf.add_page() - # Set Font family Courier with font size 28 -pdf.set_font("Courier",'',18) +pdf.set_font("Courier", '', 18) # Add Text at (0,50) -pdf.text(0,50,"Example to generate PDF in python.") +pdf.text(0, 50, "Example to generate PDF in python.") # Set Font Family Courier with italic and font size 28 -pdf.set_font("Courier",'i',28) -pdf.text(0,60,"This is an italic text") # Write text at 0,60 +pdf.set_font("Courier", 'i', 28) +pdf.text(0, 60, "This is an italic text") # Write text at 0,60 pdf.add_page() @@ -45,4 +45,4 @@ def footer(self): pdf.cell(0, 10, 'Hello There', 1, 1, 'C') # Save the Output at Local File -pdf.output('output.pdf', 'F') \ No newline at end of file +pdf.output('output.pdf', 'F') diff --git a/PDF/images.py b/PDF/images.py index b53553c7b0f..5566344df0d 100644 --- a/PDF/images.py +++ b/PDF/images.py @@ -1,6 +1,7 @@ -from fpdf import FPDF import os + from PIL import Image +from fpdf import FPDF # Author: @NavonilDas @@ -15,10 +16,10 @@ for filename in os.listdir('images'): try: # Read Image file so that we can cover the complete image properly and if invalid image file skip those file - img = Image.open("images\\"+filename) + img = Image.open("images\\" + filename) # Read Width and Height - width,height = img.size + width, height = img.size # Close opened Image img.close() @@ -30,15 +31,15 @@ orientation = 'P' if width < height else 'L' # Read the minimum of A4 Size and the image size - width = min(A4_SIZE[orientation]['w'],width) - height = min(A4_SIZE[orientation]['h'],height) + width = min(A4_SIZE[orientation]['w'], width) + height = min(A4_SIZE[orientation]['h'], height) # Add Page With an orientation pdf.add_page(orientation=orientation) # Add Image with their respective width and height in mm - pdf.image("images\\"+filename, 0, 0, width, height) + pdf.image("images\\" + filename, 0, 0, width, height) except OSError: - print("Skipped : "+filename) + print("Skipped : " + filename) -pdf.output('output.pdf','F') \ No newline at end of file +pdf.output('output.pdf', 'F') diff --git a/PONG_GAME.py b/PONG_GAME.py index 5993345296e..b43f79f5ee4 100644 --- a/PONG_GAME.py +++ b/PONG_GAME.py @@ -1,10 +1,11 @@ # Pong Game in Codeskulptor -import simplegui import random +import simplegui + WIDTH = 600 -HEIGHT = 400 +HEIGHT = 400 BALL_RADIUS = 20 PAD_WIDTH = 8 PAD_HEIGHT = 80 @@ -19,98 +20,108 @@ paddle1_vel = 0 paddle2_vel = 0 + def spawn_ball(direction): - global ball_pos, ball_vel # these are vectors stored as lists - ball_pos = [WIDTH/2 , HEIGHT/2] + global ball_pos, ball_vel # these are vectors stored as lists + ball_pos = [WIDTH / 2, HEIGHT / 2] if direction == RIGHT: - ball_vel = [ random.randrange(120, 240)/60, random.randrange(60, 180)/60] + ball_vel = [random.randrange(120, 240) / 60, random.randrange(60, 180) / 60] elif direction == LEFT: - ball_vel = [ -random.randrange(120, 240)/60, random.randrange(60, 180)/60] + ball_vel = [-random.randrange(120, 240) / 60, random.randrange(60, 180) / 60] + def reset(): global ball_pos, score1, score2 - ball_pos = [WIDTH/2 , HEIGHT/2] + ball_pos = [WIDTH / 2, HEIGHT / 2] score1 = 0 score2 = 0 - + + def new_game(): - global paddle1_pos, paddle2_pos, paddle1_vel, paddle2_vel - global score1, score2 + global paddle1_pos, paddle2_pos, paddle1_vel, paddle2_vel + global score1, score2 reset() spawn_ball(RIGHT) + def draw(canvas): - global paddle1_pos, paddle2_pos, ball_pos, ball_vel,paddle1_vel, paddle2_vel, BALL_RADIUS + global paddle1_pos, paddle2_pos, ball_pos, ball_vel, paddle1_vel, paddle2_vel, BALL_RADIUS global score1, score2 - - canvas.draw_line([WIDTH / 2, 0],[WIDTH / 2, HEIGHT], 1, "White") - canvas.draw_line([PAD_WIDTH, 0],[PAD_WIDTH, HEIGHT], 1, "White") - canvas.draw_line([WIDTH - PAD_WIDTH, 0],[WIDTH - PAD_WIDTH, HEIGHT], 1, "White") - + + canvas.draw_line([WIDTH / 2, 0], [WIDTH / 2, HEIGHT], 1, "White") + canvas.draw_line([PAD_WIDTH, 0], [PAD_WIDTH, HEIGHT], 1, "White") + canvas.draw_line([WIDTH - PAD_WIDTH, 0], [WIDTH - PAD_WIDTH, HEIGHT], 1, "White") + ball_pos[0] += ball_vel[0] ball_pos[1] += ball_vel[1] - + if ball_pos[0] <= BALL_RADIUS + PAD_WIDTH or ball_pos[0] >= WIDTH - BALL_RADIUS - PAD_WIDTH: ball_vel[0] = -ball_vel[0] elif ball_pos[1] <= BALL_RADIUS + PAD_WIDTH or ball_pos[1] >= HEIGHT - BALL_RADIUS - PAD_WIDTH: ball_vel[1] = -ball_vel[1] - - canvas.draw_circle( ball_pos ,BALL_RADIUS , 1, "White","White") - + + canvas.draw_circle(ball_pos, BALL_RADIUS, 1, "White", "White") + paddle1_pos += paddle1_vel paddle2_pos += paddle2_vel - - if paddle1_pos <= -HEIGHT/2 + PAD_HEIGHT/2 : - paddle1_pos = -HEIGHT/2 + PAD_HEIGHT/2 - elif paddle1_pos >= HEIGHT/2 -PAD_HEIGHT/2: - paddle1_pos = HEIGHT/2 - PAD_HEIGHT/2 - - if paddle2_pos <= -HEIGHT/2 + PAD_HEIGHT/2 : - paddle2_pos = -HEIGHT/2 + PAD_HEIGHT/2 - elif paddle2_pos >= HEIGHT/2 -PAD_HEIGHT/2: - paddle2_pos = HEIGHT/2 - PAD_HEIGHT/2 - - canvas.draw_line([PAD_WIDTH/2, paddle1_pos + HEIGHT/2 - PAD_HEIGHT/2] ,[ PAD_WIDTH/2, paddle1_pos + PAD_HEIGHT/2 + HEIGHT/2] , 10, "White") - canvas.draw_line([WIDTH - PAD_WIDTH/2, paddle2_pos + HEIGHT/2 - PAD_HEIGHT/2] ,[WIDTH - PAD_WIDTH/2, PAD_HEIGHT/2 + paddle2_pos + HEIGHT/2] , 10, "White") - - if (ball_pos[1] <= (paddle1_pos + HEIGHT/2 - PAD_HEIGHT/2) or ball_pos[1] >= (paddle1_pos + PAD_HEIGHT/2 + HEIGHT/2)) and ball_pos[0] == (PAD_WIDTH + BALL_RADIUS): + + if paddle1_pos <= -HEIGHT / 2 + PAD_HEIGHT / 2: + paddle1_pos = -HEIGHT / 2 + PAD_HEIGHT / 2 + elif paddle1_pos >= HEIGHT / 2 - PAD_HEIGHT / 2: + paddle1_pos = HEIGHT / 2 - PAD_HEIGHT / 2 + + if paddle2_pos <= -HEIGHT / 2 + PAD_HEIGHT / 2: + paddle2_pos = -HEIGHT / 2 + PAD_HEIGHT / 2 + elif paddle2_pos >= HEIGHT / 2 - PAD_HEIGHT / 2: + paddle2_pos = HEIGHT / 2 - PAD_HEIGHT / 2 + + canvas.draw_line([PAD_WIDTH / 2, paddle1_pos + HEIGHT / 2 - PAD_HEIGHT / 2], + [PAD_WIDTH / 2, paddle1_pos + PAD_HEIGHT / 2 + HEIGHT / 2], 10, "White") + canvas.draw_line([WIDTH - PAD_WIDTH / 2, paddle2_pos + HEIGHT / 2 - PAD_HEIGHT / 2], + [WIDTH - PAD_WIDTH / 2, PAD_HEIGHT / 2 + paddle2_pos + HEIGHT / 2], 10, "White") + + if (ball_pos[1] <= (paddle1_pos + HEIGHT / 2 - PAD_HEIGHT / 2) or ball_pos[1] >= ( + paddle1_pos + PAD_HEIGHT / 2 + HEIGHT / 2)) and ball_pos[0] == (PAD_WIDTH + BALL_RADIUS): score2 += 1 - else : + else: pass - - if (ball_pos[1] <= (paddle2_pos + HEIGHT/2 - PAD_HEIGHT/2) or ball_pos[1] >= (paddle2_pos + PAD_HEIGHT/2 + HEIGHT/2)) and ball_pos[0] == (WIDTH - PAD_WIDTH - BALL_RADIUS): + + if (ball_pos[1] <= (paddle2_pos + HEIGHT / 2 - PAD_HEIGHT / 2) or ball_pos[1] >= ( + paddle2_pos + PAD_HEIGHT / 2 + HEIGHT / 2)) and ball_pos[0] == (WIDTH - PAD_WIDTH - BALL_RADIUS): score1 += 1 else: pass - - canvas.draw_text( str(score1) , (250,30) , 40 , "White") - canvas.draw_text( str(score2) , (330,30) , 40 , "White") - - + + canvas.draw_text(str(score1), (250, 30), 40, "White") + canvas.draw_text(str(score2), (330, 30), 40, "White") + + def keydown(key): - global paddle1_vel, paddle2_vel + global paddle1_vel, paddle2_vel if key == simplegui.KEY_MAP["down"]: - paddle1_vel = 2 + paddle1_vel = 2 elif key == simplegui.KEY_MAP["up"]: paddle1_vel = -2 - - if key == simplegui.KEY_MAP["w"]: + + if key == simplegui.KEY_MAP["w"]: paddle2_vel = -2 elif key == simplegui.KEY_MAP["s"]: paddle2_vel = 2 - + + def keyup(key): global paddle1_vel, paddle2_vel if key == simplegui.KEY_MAP["down"] or key == simplegui.KEY_MAP["up"]: paddle1_vel = 0 if key == simplegui.KEY_MAP["w"] or key == simplegui.KEY_MAP["s"]: paddle2_vel = 0 - + + frame = simplegui.create_frame("Pong", WIDTH, HEIGHT) frame.set_draw_handler(draw) frame.set_keydown_handler(keydown) frame.set_keyup_handler(keyup) -frame.add_button("Restart",reset) +frame.add_button("Restart", reset) new_game() print() diff --git a/PORT SCANNER.PY b/PORT SCANNER.PY index 0c918e54dc1..481e0703922 100644 --- a/PORT SCANNER.PY +++ b/PORT SCANNER.PY @@ -68,7 +68,6 @@ Open up an text editor, copy & paste the code below. Save the file as: "portscanner.py" and exit the editor """ - import socket import subprocess import sys @@ -78,8 +77,8 @@ from datetime import datetime subprocess.call('clear', shell=True) # Ask for input -remoteServer = input("Enter a remote host to scan: ") -remoteServerIP = socket.gethostbyname(remoteServer) +remoteServer = input("Enter a remote host to scan: ") +remoteServerIP = socket.gethostbyname(remoteServer) # Print a nice banner with information on which host we are about to scan print("-" * 60) @@ -94,7 +93,7 @@ t1 = datetime.now() # We also put in some error handling for catching errors try: - for port in range(1,1025): + for port in range(1, 1025): sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) result = sock.connect_ex((remoteServerIP, port)) if result == 0: @@ -117,8 +116,7 @@ except socket.error: t2 = datetime.now() # Calculates the difference of time, to see how long it took to run the script -total = t2 - t1 +total = t2 - t1 # Printing the information to screen print('Scanning Completed in: ', total) - diff --git a/Palindrome_Checker.py b/Palindrome_Checker.py index e5eade76076..432842f224f 100644 --- a/Palindrome_Checker.py +++ b/Palindrome_Checker.py @@ -3,8 +3,8 @@ # PALINDROME: A word, phrase, or sequence that reads the same backward as forward samplePhrase = "A man, a plan, a cat, a ham, a yak, a yam, a hat, a canal-Panama!" -#givenPhrase = "" -#phrase = "" +# givenPhrase = "" +# phrase = "" givenPhrase = input("\nPlease input a phrase:(Press ENTER to use the sample phrase) ") @@ -16,17 +16,16 @@ phrase = phrase.lower() - length_ = len(phrase) bol_ = True # check using two pointers, one at beginning # other at the end. Use only half of the list. -for items in range(length_//2): +for items in range(length_ // 2): if phrase[items] != phrase[length_ - 1 - items]: print("\nSorry, The given phrase is not a Palindrome.") bol_ = False break -if bol_==True: +if bol_ == True: print("\nWow!, The phrase is a Palindrome!") diff --git a/Polyline.py b/Polyline.py index caa73cfa970..08d51eb5fcf 100644 --- a/Polyline.py +++ b/Polyline.py @@ -1,28 +1,30 @@ # Polyline drawing in codeskulptor import simplegui -import math polyline = [] + def click(pos): global polyline polyline.append(pos) - + + def clear(): global polyline polyline = [] + def draw(canvas): if len(polyline) == 1: - canvas.draw_point(polyline[0] , "White") - for i in range(1 ,len(polyline)): - canvas.draw_line(polyline[i-1] ,polyline[i] ,2 ,"White" ) - + canvas.draw_point(polyline[0], "White") + for i in range(1, len(polyline)): + canvas.draw_line(polyline[i - 1], polyline[i], 2, "White") + + frame = simplegui.create_frame("Echo click", 300, 200) frame.set_mouseclick_handler(click) frame.set_draw_handler(draw) frame.add_button("Clear", clear) frame.start() - diff --git a/Print_List_of_Even_Numbers.py b/Print_List_of_Even_Numbers.py index b1843c83248..a4a43b9f39d 100644 --- a/Print_List_of_Even_Numbers.py +++ b/Print_List_of_Even_Numbers.py @@ -1,19 +1,19 @@ # INPUT NUMBER OF EVEN NUMBERS -def print_error_messages(): #function to print error message if user enters a negative number - print("Invalid number, please enter a Non-negative number!") - exit() +def print_error_messages(): # function to print error message if user enters a negative number + print("Invalid number, please enter a Non-negative number!") + exit() try: - n=int(input('Amount: ')) #user input + n = int(input('Amount: ')) # user input except ValueError: - print_error_messages() + print_error_messages() -start=0 +start = 0 if n < 0: - print_error_messages() + print_error_messages() -for i in range(n): #loop till the number n entered by the user - print(start) #prints 0 first as it is an even number - start+=2 #increases the value of start by 2 to get to the next even number +for i in range(n): # loop till the number n entered by the user + print(start) # prints 0 first as it is an even number + start += 2 # increases the value of start by 2 to get to the next even number diff --git a/Print_List_of_Odd_Numbers.py b/Print_List_of_Odd_Numbers.py index 1fa99c8339b..e350761f8bf 100644 --- a/Print_List_of_Odd_Numbers.py +++ b/Print_List_of_Odd_Numbers.py @@ -1,22 +1,22 @@ # INPUT NUMBER OF ODD NUMBERS def print_error_messages(): - print("Invalid number, please enter a Non-negative number!") - exit() + print("Invalid number, please enter a Non-negative number!") + exit() try: - n=int(input('Amount: ')) + n = int(input('Amount: ')) except ValueError: - print_error_messages() + print_error_messages() -start=1 +start = 1 if n < 0: - print_error_messages() + print_error_messages() for i in range(n): - if(n==0): - start+=1 - print(start) - elif(n%2!=0): - print(start) + if (n == 0): + start += 1 + print(start) + elif (n % 2 != 0): + print(start) diff --git a/Program to print table of given number.py b/Program to print table of given number.py index a7c793bf0a5..f260dfa7581 100644 --- a/Program to print table of given number.py +++ b/Program to print table of given number.py @@ -1,3 +1,3 @@ -n=int(input("Enter the number to print the tables for:")) -for i in range(1,11): - print(n,"x",i,"=",n*i) +n = int(input("Enter the number to print the tables for:")) +for i in range(1, 11): + print(n, "x", i, "=", n * i) diff --git a/QuadraticCalc.py b/QuadraticCalc.py index 359254c783b..c75dceb1bd3 100644 --- a/QuadraticCalc.py +++ b/QuadraticCalc.py @@ -1,42 +1,42 @@ -#GGearing -#02/10/2017 -#Simple script to calculate the quadratic formula of a sequence of numbers and -#recognises when the sequence isn't quadratic +# GGearing +# 02/10/2017 +# Simple script to calculate the quadratic formula of a sequence of numbers and +# recognises when the sequence isn't quadratic -def findLinear(numbers): ##find a & b of linear sequence - output=[] - a=numbers[1]-numbers[0] - a1=numbers[2]-numbers[1] - if a1==a: - b=numbers[0]-a - return (a,b) +def findLinear(numbers): ##find a & b of linear sequence + output = [] + a = numbers[1] - numbers[0] + a1 = numbers[2] - numbers[1] + if a1 == a: + b = numbers[0] - a + return (a, b) else: print("Sequence is not linear") - -sequence=[] -first_difference=[] -second_difference=[] -for i in range(4): #input - term=str(i+1) - inp=int(input("Enter term "+term+": ")) + + +sequence = [] +first_difference = [] +second_difference = [] +for i in range(4): # input + term = str(i + 1) + inp = int(input("Enter term " + term + ": ")) sequence.append(inp) - + for i in range(3): - gradient=sequence[i+1]-sequence[i] + gradient = sequence[i + 1] - sequence[i] first_difference.append(gradient) for i in range(2): - gradient=first_difference[i+1]-first_difference[i] + gradient = first_difference[i + 1] - first_difference[i] second_difference.append(gradient) - -if second_difference[0]==second_difference[1]: #checks to see if consistent - a=second_difference[0]/2 - subs_diff=[] + +if second_difference[0] == second_difference[1]: # checks to see if consistent + a = second_difference[0] / 2 + subs_diff = [] for i in range(4): - n=i+1 - num=a*(n*n) - subs_diff.append((sequence[i])-num) - b,c=findLinear(subs_diff) - print("Nth term: "+str(a)+"n^2 + "+str(b)+"n + "+str(c)) #outputs nth term + n = i + 1 + num = a * (n * n) + subs_diff.append((sequence[i]) - num) + b, c = findLinear(subs_diff) + print("Nth term: " + str(a) + "n^2 + " + str(b) + "n + " + str(c)) # outputs nth term else: print("Sequence is not quadratic") - diff --git a/Quick_Sort.py b/Quick_Sort.py index 3b97dfcf6b4..285b0701f5f 100644 --- a/Quick_Sort.py +++ b/Quick_Sort.py @@ -5,22 +5,22 @@ # array, and places all smaller (smaller than pivot) # to left of pivot and all greater elements to right # of pivot -def partition(arr,low,high): - i = ( low-1 ) # index of smaller element - pivot = arr[high] # pivot +def partition(arr, low, high): + i = (low - 1) # index of smaller element + pivot = arr[high] # pivot - for j in range(low , high): + for j in range(low, high): - # If current element is smaller than or - # equal to pivot - if arr[j] <= pivot: - - # increment index of smaller element - i = i+1 - arr[i],arr[j] = arr[j],arr[i] + # If current element is smaller than or + # equal to pivot + if arr[j] <= pivot: + # increment index of smaller element + i = i + 1 + arr[i], arr[j] = arr[j], arr[i] + + arr[i + 1], arr[high] = arr[high], arr[i + 1] + return (i + 1) - arr[i+1],arr[high] = arr[high],arr[i+1] - return ( i+1 ) # The main function that implements QuickSort # arr[] --> Array to be sorted, @@ -28,24 +28,23 @@ def partition(arr,low,high): # high --> Ending index # Function to do Quick sort -def quickSort(arr,low,high): - if low < high: - - # pi is partitioning index, arr[p] is now - # at right place - pi = partition(arr,low,high) - - # Separately sort elements before - # partition and after partition - quickSort(arr, low, pi-1) - quickSort(arr, pi+1, high) - -# Driver code to test above -arr = [10, 7, 8, 9, 1, 5] -n = len(arr) -quickSort(arr,0,n-1) -print ("Sorted array is:") -for i in range(n): - print ("%d" %arr[i]), - - +def quickSort(arr, low, high): + if low < high: + # pi is partitioning index, arr[p] is now + # at right place + pi = partition(arr, low, high) + + # Separately sort elements before + # partition and after partition + quickSort(arr, low, pi - 1) + quickSort(arr, pi + 1, high) + + # Driver code to test above + + +arr = [10, 7, 8, 9, 1, 5] +n = len(arr) +quickSort(arr, 0, n - 1) +print("Sorted array is:") +for i in range(n): + print("%d" % arr[i]), diff --git a/RandomDice.py b/RandomDice.py index a76e944ff92..1b469769b36 100644 --- a/RandomDice.py +++ b/RandomDice.py @@ -1,13 +1,17 @@ -#GGearing 01/10/19 -#Random Dice Game using Tkinter +# GGearing 01/10/19 +# Random Dice Game using Tkinter -from tkinter import * from random import randint +from tkinter import * + + def roll(): - text.delete(0.0,END) - text.insert(END,str(randint(1,100))) -window=Tk() -text=Text(window,width=3,height=1) -buttonA=Button(window,text="Press to roll!", command=roll) + text.delete(0.0, END) + text.insert(END, str(randint(1, 100))) + + +window = Tk() +text = Text(window, width=3, height=1) +buttonA = Button(window, text="Press to roll!", command=roll) text.pack() buttonA.pack() diff --git a/ReadFromCSV.py b/ReadFromCSV.py index d8c19dc31eb..3888659afa5 100644 --- a/ReadFromCSV.py +++ b/ReadFromCSV.py @@ -1,6 +1,5 @@ __author__ = 'vamsi' -import pandas as pd -import numpy as np +import pandas as pd from matplotlib import pyplot as plt from matplotlib import style @@ -9,11 +8,11 @@ """reading data from SalesData.csv file and passing data to dataframe""" -df=pd.read_csv("C:\\Users\Test\Desktop\SalesData.csv") -x=df["SalesID"].as_matrix()#casting SalesID to list -y=df["ProductPrice"].as_matrix()#casting ProductPrice to list -plt.xlabel("SalesID")#assigning X-axis label -plt.ylabel("ProductPrice")#assigning Y-axis label -plt.title("Sales Analysis")#assigning Title to the graph -plt.plot(x,y)#Plot X and Y axis -plt.show()#Show the graph +df = pd.read_csv("C:\\Users\Test\Desktop\SalesData.csv") +x = df["SalesID"].as_matrix() # casting SalesID to list +y = df["ProductPrice"].as_matrix() # casting ProductPrice to list +plt.xlabel("SalesID") # assigning X-axis label +plt.ylabel("ProductPrice") # assigning Y-axis label +plt.title("Sales Analysis") # assigning Title to the graph +plt.plot(x, y) # Plot X and Y axis +plt.show() # Show the graph diff --git a/Shivaansh.py b/Shivaansh.py index 3542862b8aa..deec715f10f 100644 --- a/Shivaansh.py +++ b/Shivaansh.py @@ -1,5 +1,5 @@ -from __future__ import print_function +from __future__ import print_function + x = input("Enter a number: ") -for i in range (1,11,1): - print(x, "x", i, "=", (x * i)) - +for i in range(1, 11, 1): + print(x, "x", i, "=", (x * i)) diff --git a/SimpleCalculator.py b/SimpleCalculator.py index f76dcec16c6..05ae4b8d36c 100644 --- a/SimpleCalculator.py +++ b/SimpleCalculator.py @@ -1,14 +1,22 @@ -def add(a,b): - return a+b -def subtract(a,b): - return a-b -def multiply(a,b): - return a*b -def divide(a,b): +def add(a, b): + return a + b + + +def subtract(a, b): + return a - b + + +def multiply(a, b): + return a * b + + +def divide(a, b): try: - return a/b + return a / b except ZeroDivisionError: return "Zero Division Error" + + print("Select Operation") print("1.Add") print("2.Subtract") @@ -20,15 +28,15 @@ def divide(a,b): num2 = int(input("Enbter Second number:")) if choice == '1': - print(num1,"+",num2,"=", add(num1,num2)) + print(num1, "+", num2, "=", add(num1, num2)) elif choice == '2': - print(num1,"-",num2,"=", subtract(num1,num2)) + print(num1, "-", num2, "=", subtract(num1, num2)) elif choice == '3': - print(num1,"*",num2,"=", multiply(num1,num2)) + print(num1, "*", num2, "=", multiply(num1, num2)) elif choice == '4': - print(num1,"/",num2,"=", divide(num1,num2)) + print(num1, "/", num2, "=", divide(num1, num2)) else: - print("Invalid input") + print("Invalid input") diff --git a/SimpleStopWatch.py b/SimpleStopWatch.py index dd63d7767cd..1a1c38dfb42 100644 --- a/SimpleStopWatch.py +++ b/SimpleStopWatch.py @@ -1,12 +1,12 @@ -#Author: OMKAR PATHAK -#This script helps to build a simple stopwatch application using Python's time module. +# Author: OMKAR PATHAK +# This script helps to build a simple stopwatch application using Python's time module. import time print('Press ENTER to begin, Press Ctrl + C to stop') while True: try: - input() # For ENTER. Use raw_input() if you are running python 2.x instead of input() + input() # For ENTER. Use raw_input() if you are running python 2.x instead of input() starttime = time.time() print('Started') while True: @@ -15,5 +15,5 @@ except KeyboardInterrupt: print('Stopped') endtime = time.time() - print('Total Time:', round(endtime - starttime, 2),'secs') + print('Total Time:', round(endtime - starttime, 2), 'secs') break diff --git a/Streaming Tweets from Twitter to Database.py b/Streaming Tweets from Twitter to Database.py index 5fbf62c0807..d418fb42315 100644 --- a/Streaming Tweets from Twitter to Database.py +++ b/Streaming Tweets from Twitter to Database.py @@ -1,46 +1,46 @@ -from tweepy import Stream -from tweepy import OAuthHandler -from tweepy.streaming import StreamListener -import MySQLdb -import time import json +import time - +import MySQLdb +from tweepy import OAuthHandler +from tweepy import Stream +from tweepy.streaming import StreamListener # replace mysql.server with "localhost" if you are running via your own server! # server MySQL username MySQL pass Database name. -conn = MySQLdb.connect("mysql.server","beginneraccount","cookies","beginneraccount$tutorial") +conn = MySQLdb.connect("mysql.server", "beginneraccount", "cookies", "beginneraccount$tutorial") c = conn.cursor() +# consumer key, consumer secret, access token, access secret. +ckey = "asdfsafsafsaf" +csecret = "asdfasdfsadfsa" +atoken = "asdfsadfsafsaf-asdfsaf" +asecret = "asdfsadfsadfsadfsadfsad" -#consumer key, consumer secret, access token, access secret. -ckey="asdfsafsafsaf" -csecret="asdfasdfsadfsa" -atoken="asdfsadfsafsaf-asdfsaf" -asecret="asdfsadfsadfsadfsadfsad" class listener(StreamListener): def on_data(self, data): all_data = json.loads(data) - + tweet = all_data["text"] - + username = all_data["user"]["screen_name"] - + c.execute("INSERT INTO taula (time, username, tweet) VALUES (%s,%s,%s)", - (time.time(), username, tweet)) + (time.time(), username, tweet)) conn.commit() - print((username,tweet)) - + print((username, tweet)) + return True def on_error(self, status): print(status) + auth = OAuthHandler(ckey, csecret) auth.set_access_token(atoken, asecret) diff --git a/TTS.py b/TTS.py index 8ab4efa7611..391f21c1e93 100644 --- a/TTS.py +++ b/TTS.py @@ -1,29 +1,26 @@ -import win32com.client as wincl from tkinter import * +import win32com.client as wincl + def text2Speech(): - text = e.get() - speak = wincl.Dispatch("SAPI.SpVoice") - speak.Speak(text) + text = e.get() + speak = wincl.Dispatch("SAPI.SpVoice") + speak.Speak(text) -#window configs +# window configs tts = Tk() tts.wm_title("Text to Speech") tts.geometry("225x105") tts.config(background="#708090") - -f=Frame(tts,height=280,width=500,bg="#bebebe") -f.grid(row=0,column=0,padx=10,pady=5) -lbl=Label(f,text="Enter your Text here : ") -lbl.grid(row=1,column=0,padx=10,pady=2) -e=Entry(f,width=30) -e.grid(row=2,column=0,padx=10,pady=2) -btn=Button(f,text="Speak",command=text2Speech) -btn.grid(row=3,column=0,padx=20,pady=10) +f = Frame(tts, height=280, width=500, bg="#bebebe") +f.grid(row=0, column=0, padx=10, pady=5) +lbl = Label(f, text="Enter your Text here : ") +lbl.grid(row=1, column=0, padx=10, pady=2) +e = Entry(f, width=30) +e.grid(row=2, column=0, padx=10, pady=2) +btn = Button(f, text="Speak", command=text2Speech) +btn.grid(row=3, column=0, padx=20, pady=10) tts.mainloop() - - - diff --git a/TicTacToe.py b/TicTacToe.py index f4657863651..e424444120d 100644 --- a/TicTacToe.py +++ b/TicTacToe.py @@ -7,6 +7,7 @@ except NameError: pass + def drawBoard(board): # This function prints out the board that it was passed. @@ -17,6 +18,7 @@ def drawBoard(board): print('-----------') print(' ' + board[1] + ' | ' + board[2] + ' | ' + board[3]) + def inputPlayerLetter(): # Lets the player type which letter they want to be. # Returns a list with the player's letter as the first item, and the computer's letter as the second. @@ -25,35 +27,40 @@ def inputPlayerLetter(): letter = input('Do you want to be X or O? ').upper() # the first element in the tuple is the player's letter, the second is the computer's letter. - + return ['X', 'O'] if letter == 'X' else ['O', 'X'] + def whoGoesFirst(): # Randomly choose the player who goes first. return random.choice(('computer', 'player')) + def playAgain(): # This function returns True if the player wants to play again, otherwise it returns False. print('Do you want to play again? (yes or no)') return input().lower().startswith('y') + def makeMove(board, letter, move): - if isSpaceFree(board,move): + if isSpaceFree(board, move): board[move] = letter else: raise Exception("makeMove: the field is not empty!") + def isWinner(bo, le): # Given a board and a player's letter, this function returns True if that player has won. # We use bo instead of board and le instead of letter so we don't have to type as much. - return ((bo[7] == le and bo[8] == le and bo[9] == le) or # across the top - (bo[4] == le and bo[5] == le and bo[6] == le) or # across the middle - (bo[1] == le and bo[2] == le and bo[3] == le) or # across the bottom - (bo[7] == le and bo[4] == le and bo[1] == le) or # down the left side - (bo[8] == le and bo[5] == le and bo[2] == le) or # down the middle - (bo[9] == le and bo[6] == le and bo[3] == le) or # down the right side - (bo[7] == le and bo[5] == le and bo[3] == le) or # diagonal - (bo[9] == le and bo[5] == le and bo[1] == le)) # diagonal + return ((bo[7] == le and bo[8] == le and bo[9] == le) or # across the top + (bo[4] == le and bo[5] == le and bo[6] == le) or # across the middle + (bo[1] == le and bo[2] == le and bo[3] == le) or # across the bottom + (bo[7] == le and bo[4] == le and bo[1] == le) or # down the left side + (bo[8] == le and bo[5] == le and bo[2] == le) or # down the middle + (bo[9] == le and bo[6] == le and bo[3] == le) or # down the right side + (bo[7] == le and bo[5] == le and bo[3] == le) or # diagonal + (bo[9] == le and bo[5] == le and bo[1] == le)) # diagonal + def getBoardCopy(board): # Make a duplicate of the board list and return it the duplicate. @@ -64,10 +71,12 @@ def getBoardCopy(board): return dupeBoard + def isSpaceFree(board, move): # Return true if the passed move is free on the passed board. return board[move].isdigit() + def getPlayerMove(board): # Let the player type in his move. move = ' ' @@ -76,12 +85,14 @@ def getPlayerMove(board): move = input() return int(move) + def chooseRandomMoveFromList(board, movesList): # Returns a valid move from the passed list on the passed board. # Returns None if there is no valid move. possibleMoves = [i for i in movesList if isSpaceFree(board, i)] return random.choice(possibleMoves) if possibleMoves else None + def getComputerMove(board, computerLetter): # Given a board and the computer's letter, determine where to move and return that move. playerLetter = 'O' if computerLetter == 'X' else 'X' @@ -115,6 +126,7 @@ def getComputerMove(board, computerLetter): # Move on one of the sides. return chooseRandomMoveFromList(board, [2, 4, 6, 8]) + def isBoardFull(board): # Return True if every space on the board has been taken. Otherwise return False. for i in range(1, 10): @@ -122,26 +134,27 @@ def isBoardFull(board): return False return True + def main(): print('Welcome to Tic Tac Toe!') random.seed() while True: # Reset the board theBoard = [' '] * 10 - for i in range(9,0,-1): + for i in range(9, 0, -1): theBoard[i] = str(i) playerLetter, computerLetter = inputPlayerLetter() turn = whoGoesFirst() print('The ' + turn + ' will go first.') gameIsPlaying = True - + while gameIsPlaying: if turn == 'player': # Player's turn. drawBoard(theBoard) move = getPlayerMove(theBoard) makeMove(theBoard, playerLetter, move) - + if isWinner(theBoard, playerLetter): drawBoard(theBoard) print('Hooray! You have won the game!') @@ -153,12 +166,12 @@ def main(): break else: turn = 'computer' - + else: # Computer's turn. move = getComputerMove(theBoard, computerLetter) makeMove(theBoard, computerLetter, move) - + if isWinner(theBoard, computerLetter): drawBoard(theBoard) print('The computer has beaten you! You lose.') @@ -170,9 +183,10 @@ def main(): break else: turn = 'player' - + if not playAgain(): break - + + if __name__ == "__main__": main() diff --git a/Weather Scrapper/weather.py b/Weather Scrapper/weather.py index 153747aef42..f47e335a194 100644 --- a/Weather Scrapper/weather.py +++ b/Weather Scrapper/weather.py @@ -1,23 +1,23 @@ +import csv +from datetime import datetime + import requests from bs4 import BeautifulSoup -from datetime import datetime -import csv city = input('Enter City') url = 'https://www.wunderground.com/weather/in/' + city try: - response = requests.get(url) + response = requests.get(url) except requests.exceptions.RequestException as e: - print(e) - exit(1) + print(e) + exit(1) try: - response.raise_for_status() + response.raise_for_status() except Exception as e: - print(e) - exit(1) - + print(e) + exit(1) html = response.text soup = BeautifulSoup(html, 'lxml') @@ -26,21 +26,19 @@ out4 = soup.find(class_="data-module additional-conditions") Time = datetime.now().strftime("%H:%M") -Date = out2.find('span', attrs={'class':'date'}).get_text() -Temperature = out2.find('span', attrs={'class':'temp'}).get_text() +Date = out2.find('span', attrs={'class': 'date'}).get_text() +Temperature = out2.find('span', attrs={'class': 'temp'}).get_text() Temperature = " ".join(Temperature.split()) -Precipitation = 'Precipitate:' + out3.find('a', attrs={'class':'hook'}).get_text().split(' ', 1)[0] -other = out3.find('a', attrs={'class':'module-link'}).get_text().split('.') +Precipitation = 'Precipitate:' + out3.find('a', attrs={'class': 'hook'}).get_text().split(' ', 1)[0] +other = out3.find('a', attrs={'class': 'module-link'}).get_text().split('.') sky = other[0] Wind = other[2].strip() with open('weather.csv', 'a') as new_file: - csv_writer = csv.writer(new_file) - csv_writer.writerow([city, - Time, - Date, - Temperature, - Precipitation, - sky,Wind]) - - + csv_writer = csv.writer(new_file) + csv_writer.writerow([city, + Time, + Date, + Temperature, + Precipitation, + sky, Wind]) diff --git a/WikipediaModule.py b/WikipediaModule.py index 4f6000fd8ad..7a99a4b3376 100644 --- a/WikipediaModule.py +++ b/WikipediaModule.py @@ -4,84 +4,85 @@ @author: Albert """ from __future__ import print_function + import wikipedia as wk from bs4 import BeautifulSoup + def wiki(): ''' Search Anything in wikipedia ''' - word=input("Wikipedia Search : ") - results=wk.search(word) + word = input("Wikipedia Search : ") + results = wk.search(word) for i in enumerate(results): print(i) try: - key=int(input("Enter the number : ")) + key = int(input("Enter the number : ")) except AssertionError: - key=int(input("Please enter corresponding article number : ")) + key = int(input("Please enter corresponding article number : ")) - page=wk.page(results[key]) - url=page.url - #originalTitle=page.original_title - pageId=page.pageid - #references=page.references - title=page.title - #soup=BeautifulSoup(page.content,'lxml') - pageLength=input('''Wiki Page Type : 1.Full 2.Summary : ''') - if pageLength==1: - soup=fullPage(page) + page = wk.page(results[key]) + url = page.url + # originalTitle=page.original_title + pageId = page.pageid + # references=page.references + title = page.title + # soup=BeautifulSoup(page.content,'lxml') + pageLength = input('''Wiki Page Type : 1.Full 2.Summary : ''') + if pageLength == 1: + soup = fullPage(page) print(soup) else: print(title) - print("Page Id = ",pageId) + print("Page Id = ", pageId) print(page.summary) - print("Page Link = ",url) - #print "References : ",references - + print("Page Link = ", url) + # print "References : ",references pass + def fullPage(page): - soup=BeautifulSoup(page.content,'lxml') + soup = BeautifulSoup(page.content, 'lxml') return soup + def randomWiki(): ''' This function gives you a list of n number of random articles Choose any article. ''' - number=input("No: of Random Pages : ") - lst=wk.random(number) + number = input("No: of Random Pages : ") + lst = wk.random(number) for i in enumerate(lst): print(i) try: - key=input("Enter the number : ") - assert key>=0 and key= 0 and key < number except AssertionError: - key=input("Please enter corresponding article number : ") + key = input("Please enter corresponding article number : ") - page=wk.page(lst[key]) - url=page.url - #originalTitle=page.original_title - pageId=page.pageid - #references=page.references - title=page.title - #soup=BeautifulSoup(page.content,'lxml') - pageLength=input('''Wiki Page Type : 1.Full 2.Summary : ''') - if pageLength==1: - soup=fullPage(page) + page = wk.page(lst[key]) + url = page.url + # originalTitle=page.original_title + pageId = page.pageid + # references=page.references + title = page.title + # soup=BeautifulSoup(page.content,'lxml') + pageLength = input('''Wiki Page Type : 1.Full 2.Summary : ''') + if pageLength == 1: + soup = fullPage(page) print(soup) else: print(title) - print("Page Id = ",pageId) + print("Page Id = ", pageId) print(page.summary) - print("Page Link = ",url) - #print "References : ",references + print("Page Link = ", url) + # print "References : ",references pass - - -#if __name__=="__main__": -# wiki() +# if __name__=="__main__": +# wiki() diff --git a/Windows_Wallpaper_Script/wallpaper_extract.py b/Windows_Wallpaper_Script/wallpaper_extract.py index 93e0f4d5727..8a0a5778b02 100644 --- a/Windows_Wallpaper_Script/wallpaper_extract.py +++ b/Windows_Wallpaper_Script/wallpaper_extract.py @@ -1,6 +1,7 @@ import os import shutil import time + from PIL import Image @@ -75,6 +76,7 @@ def extract_wall(): os.remove(w.file_urls["wall_dst"] + filename) else: im.close() + # Arrange the wallpapers into the corresponding folders @staticmethod def arr_desk_wallpapers(): diff --git a/XORcipher/XOR_cipher.py b/XORcipher/XOR_cipher.py index 727fac3b070..1a9770af551 100644 --- a/XORcipher/XOR_cipher.py +++ b/XORcipher/XOR_cipher.py @@ -16,172 +16,166 @@ - encrypt_file : boolean - decrypt_file : boolean """ -class XORCipher(object): - - def __init__(self, key = 0): - """ - simple constructor that receives a key or uses - default key = 0 - """ - - #private field - self.__key = key - - def encrypt(self, content, key): - """ - input: 'content' of type string and 'key' of type int - output: encrypted string 'content' as a list of chars - if key not passed the method uses the key by the constructor. - otherwise key = 1 - """ - # precondition - assert (isinstance(key,int) and isinstance(content,str)) - key = key or self.__key or 1 - - # make sure key can be any size - while (key > 255): - key -= 255 - - # This will be returned - ans = [] +class XORCipher(object): - for ch in content: - ans.append(chr(ord(ch) ^ key)) + def __init__(self, key=0): + """ + simple constructor that receives a key or uses + default key = 0 + """ - return ans + # private field + self.__key = key - def decrypt(self,content,key): - """ - input: 'content' of type list and 'key' of type int - output: decrypted string 'content' as a list of chars - if key not passed the method uses the key by the constructor. - otherwise key = 1 - """ + def encrypt(self, content, key): + """ + input: 'content' of type string and 'key' of type int + output: encrypted string 'content' as a list of chars + if key not passed the method uses the key by the constructor. + otherwise key = 1 + """ - # precondition - assert (isinstance(key,int) and isinstance(content,list)) + # precondition + assert (isinstance(key, int) and isinstance(content, str)) - key = key or self.__key or 1 + key = key or self.__key or 1 - # make sure key can be any size - while (key > 255): - key -= 255 + # make sure key can be any size + while (key > 255): + key -= 255 - # This will be returned - ans = [] + # This will be returned + ans = [] - for ch in content: - ans.append(chr(ord(ch) ^ key)) + for ch in content: + ans.append(chr(ord(ch) ^ key)) - return ans + return ans + def decrypt(self, content, key): + """ + input: 'content' of type list and 'key' of type int + output: decrypted string 'content' as a list of chars + if key not passed the method uses the key by the constructor. + otherwise key = 1 + """ - def encrypt_string(self,content, key = 0): - """ - input: 'content' of type string and 'key' of type int - output: encrypted string 'content' - if key not passed the method uses the key by the constructor. - otherwise key = 1 - """ + # precondition + assert (isinstance(key, int) and isinstance(content, list)) - # precondition - assert (isinstance(key,int) and isinstance(content,str)) + key = key or self.__key or 1 - key = key or self.__key or 1 + # make sure key can be any size + while (key > 255): + key -= 255 - # make sure key can be any size - while (key > 255): - key -= 255 + # This will be returned + ans = [] - # This will be returned - ans = "" + for ch in content: + ans.append(chr(ord(ch) ^ key)) - for ch in content: - ans += chr(ord(ch) ^ key) + return ans - return ans + def encrypt_string(self, content, key=0): + """ + input: 'content' of type string and 'key' of type int + output: encrypted string 'content' + if key not passed the method uses the key by the constructor. + otherwise key = 1 + """ - def decrypt_string(self,content,key = 0): - """ - input: 'content' of type string and 'key' of type int - output: decrypted string 'content' - if key not passed the method uses the key by the constructor. - otherwise key = 1 - """ + # precondition + assert (isinstance(key, int) and isinstance(content, str)) - # precondition - assert (isinstance(key,int) and isinstance(content,str)) + key = key or self.__key or 1 - key = key or self.__key or 1 + # make sure key can be any size + while (key > 255): + key -= 255 - # make sure key can be any size - while (key > 255): - key -= 255 + # This will be returned + ans = "" - # This will be returned - ans = "" - - for ch in content: - ans += chr(ord(ch) ^ key) + for ch in content: + ans += chr(ord(ch) ^ key) - return ans + return ans + def decrypt_string(self, content, key=0): + """ + input: 'content' of type string and 'key' of type int + output: decrypted string 'content' + if key not passed the method uses the key by the constructor. + otherwise key = 1 + """ - def encrypt_file(self, file, key = 0): - """ - input: filename (str) and a key (int) - output: returns true if encrypt process was - successful otherwise false - if key not passed the method uses the key by the constructor. - otherwise key = 1 - """ + # precondition + assert (isinstance(key, int) and isinstance(content, str)) - #precondition - assert (isinstance(file,str) and isinstance(key,int)) + key = key or self.__key or 1 - try: - with open(file,"r") as fin: - with open("encrypt.out","w+") as fout: + # make sure key can be any size + while (key > 255): + key -= 255 - # actual encrypt-process - for line in fin: - fout.write(self.encrypt_string(line,key)) + # This will be returned + ans = "" - except: - return False + for ch in content: + ans += chr(ord(ch) ^ key) - return True + return ans + def encrypt_file(self, file, key=0): + """ + input: filename (str) and a key (int) + output: returns true if encrypt process was + successful otherwise false + if key not passed the method uses the key by the constructor. + otherwise key = 1 + """ - def decrypt_file(self,file, key): - """ - input: filename (str) and a key (int) - output: returns true if decrypt process was - successful otherwise false - if key not passed the method uses the key by the constructor. - otherwise key = 1 - """ + # precondition + assert (isinstance(file, str) and isinstance(key, int)) - #precondition - assert (isinstance(file,str) and isinstance(key,int)) + try: + with open(file, "r") as fin: + with open("encrypt.out", "w+") as fout: + # actual encrypt-process + for line in fin: + fout.write(self.encrypt_string(line, key)) - try: - with open(file,"r") as fin: - with open("decrypt.out","w+") as fout: + except: + return False - # actual encrypt-process - for line in fin: - fout.write(self.decrypt_string(line,key)) + return True - except: - return False + def decrypt_file(self, file, key): + """ + input: filename (str) and a key (int) + output: returns true if decrypt process was + successful otherwise false + if key not passed the method uses the key by the constructor. + otherwise key = 1 + """ - return True + # precondition + assert (isinstance(file, str) and isinstance(key, int)) + try: + with open(file, "r") as fin: + with open("decrypt.out", "w+") as fout: + # actual encrypt-process + for line in fin: + fout.write(self.decrypt_string(line, key)) + except: + return False + return True # Tests # crypt = XORCipher() @@ -206,4 +200,4 @@ def decrypt_file(self,file, key): # if (crypt.decrypt_file("encrypt.out",key)): # print "decrypt successful" # else: -# print "decrypt unsuccessful" \ No newline at end of file +# print "decrypt unsuccessful" diff --git a/XORcipher/test_XOR_cipher.py b/XORcipher/test_XOR_cipher.py index 4b978059c9c..4cf493c4b4e 100644 --- a/XORcipher/test_XOR_cipher.py +++ b/XORcipher/test_XOR_cipher.py @@ -14,6 +14,7 @@ import unittest from unittest import TestCase + import mock from XOR_cipher import XORCipher @@ -41,7 +42,7 @@ def test__init__(self, mock__init__): """ # self.XORCipher_1.__init__ = mock.MagicMock() - XORCipher.__init__ = mock.MagicMock() + XORCipher.__init__ = mock.MagicMock() # self.XORCipher_1.__init__(1) XORCipher.__init__() @@ -54,14 +55,14 @@ def test_encrypt(self, mock_encrypt): """ Test the encrypt method with mocked values. """ - + ans = mock.MagicMock() content = mock.MagicMock() key = mock.MagicMock() XORCipher.encrypt = mock.MagicMock(return_value=ans) XORCipher.encrypt(content, key) - XORCipher.encrypt.assert_called_with(content, key) + XORCipher.encrypt.assert_called_with(content, key) @mock.patch('XOR_cipher.XORCipher.decrypt') def test_decrypt(self, mock_decrypt): @@ -76,35 +77,35 @@ def test_decrypt(self, mock_decrypt): XORCipher.decrypt(content, key) XORCipher.decrypt.assert_called_with(content, key) - + @mock.patch('XOR_cipher.XORCipher.encrypt_string') def test_encrypt_string(self, mock_encrypt_string): """ Test the encrypt_string method with mocked values. """ - + ans = mock.MagicMock() content = mock.MagicMock() key = mock.MagicMock() XORCipher.encrypt_string = mock.MagicMock(return_value=ans) XORCipher.encrypt_string(content, key) - XORCipher.encrypt_string.assert_called_with(content, key) + XORCipher.encrypt_string.assert_called_with(content, key) @mock.patch('XOR_cipher.XORCipher.decrypt_string') def test_decrypt_string(self, mock_decrypt_string): """ Test the decrypt_string method with mocked values. """ - + ans = mock.MagicMock() content = mock.MagicMock() key = mock.MagicMock() XORCipher.decrypt_string = mock.MagicMock(return_value=ans) XORCipher.decrypt_string(content, key) - - XORCipher.decrypt_string.assert_called_with(content, key) - + + XORCipher.decrypt_string.assert_called_with(content, key) + @mock.patch('XOR_cipher.XORCipher.encrypt_file') def test_encrypt_file(self, mock_encrypt_file): """ @@ -128,10 +129,9 @@ def test_decrypt_file(self, mock_decrypt_file): key = mock.MagicMock() XORCipher.decrypt_string = mock.MagicMock(return_value=True) XORCipher.decrypt_string(file, key) - + XORCipher.decrypt_string.assert_called_with(file, key) if __name__ == '__main__': unittest.main() - diff --git a/alexa_news_headlines.py b/alexa_news_headlines.py index 2d7f9638f0e..b2c56c14e0b 100644 --- a/alexa_news_headlines.py +++ b/alexa_news_headlines.py @@ -1,18 +1,20 @@ -from flask import Flask -from flask_ask import Ask, question, statement, session -import unidecode import json -import requests import time +import requests +import unidecode +from flask import Flask +from flask_ask import Ask, question, statement + app = Flask(__name__) -ask = Ask(app,"/reddit_reader") +ask = Ask(app, "/reddit_reader") + def get_headlines(): - user_pass_dict = {'user':'USERNAME', 'passwd': "PASSWORD", 'api_type':'json'} + user_pass_dict = {'user': 'USERNAME', 'passwd': "PASSWORD", 'api_type': 'json'} sess = requests.Session() - sess.headers.update({'User-Agent':'I am testing Alexa: nobi'}) - sess.post("https://www.reddit.com/api/login/",data = user_pass_dict) + sess.headers.update({'User-Agent': 'I am testing Alexa: nobi'}) + sess.post("https://www.reddit.com/api/login/", data=user_pass_dict) time.sleep(1) url = "https://reddit.com/r/worldnews/.json?limit=10" html = sess.get(url) @@ -21,25 +23,30 @@ def get_headlines(): titles = '... '.join([i for i in titles]) return titles + @app.route("/") def homepage(): return "hi there!" + @ask.launch def start_skill(): welcome_message = "Hello there, would you like to hear the news?" return question(welcome_message) + @ask.intent("YesIntent") def share_headlines(): headlines = get_headlines() headline_msg = "The current world news headlines are {}".format(headlines) return statement(headline_msg) + @ask.intent("NooIntent") def no_intent(): bye_text = "I am not sure why you then turned me on. Anyways, bye for now!" return statement(bye_text) + if __name__ == "__main__": - app.run(port=8000,debug=True) + app.run(port=8000, debug=True) diff --git a/async_downloader/async_downloader.py b/async_downloader/async_downloader.py index 37afc9b9784..89b5241b9ad 100644 --- a/async_downloader/async_downloader.py +++ b/async_downloader/async_downloader.py @@ -9,13 +9,13 @@ """ import asyncio -import aiohttp -from os.path import basename import concurrent.futures as cofu +from os.path import basename +import aiohttp -def download(ways): +def download(ways): if not ways: print('Ways list is empty. Downloading is impossible') return @@ -48,7 +48,6 @@ def download(ways): async def async_downloader(ways, loop, success_files=set(), failure_files=set()): - async with aiohttp.ClientSession() as session: coroutines = [ download_file_by_url( @@ -78,7 +77,6 @@ async def async_downloader(ways, loop, success_files=set(), failure_files=set()) async def download_file_by_url(url, session=None): - fail = True file_name = basename(url) @@ -113,7 +111,6 @@ async def download_file_by_url(url, session=None): def test(): - ways = ['https://www.wikipedia.org', 'https://www.ya.ru', 'https://www.duckduckgo.com', diff --git a/bank_managment_system/backend.py b/bank_managment_system/backend.py index cee54e558d9..cd4e7c60ae4 100644 --- a/bank_managment_system/backend.py +++ b/bank_managment_system/backend.py @@ -1,6 +1,7 @@ import sqlite3 -#making connection with database + +# making connection with database def connect_database(): global conn global cur @@ -21,164 +22,208 @@ def connect_database(): acc_no = 1 else: acc_no = int(acc[-1][0]) + 1 -#check admin dtails in database -def check_admin(name,password): + +# check admin dtails in database +def check_admin(name, password): cur.execute("select * from admin") - data=cur.fetchall() + data = cur.fetchall() - if data[0][0]==name and data[0][1]==password: + if data[0][0] == name and data[0][1] == password: return True return -#create employee in database -def create_employee(name,password,salary,positon): + + +# create employee in database +def create_employee(name, password, salary, positon): print(password) - cur.execute("insert into staff values(?,?,?,?)",(name,password,salary,positon)) + cur.execute("insert into staff values(?,?,?,?)", (name, password, salary, positon)) conn.commit() -#check employee details in dabase for employee login -def check_employee(name,password): + + +# check employee details in dabase for employee login +def check_employee(name, password): print(password) print(name) cur.execute("select name,pass from staff") - data=cur.fetchall() + data = cur.fetchall() print(data) - if len(data)==0: + if len(data) == 0: return False for i in range(len(data)): - if data[i][0]==name and data[i][1]==password: + if data[i][0] == name and data[i][1] == password: return True return False -#create customer details in database -def create_customer(name,age,address,balance,acc_type,mobile_number): + + +# create customer details in database +def create_customer(name, age, address, balance, acc_type, mobile_number): global acc_no - cur.execute("insert into bank values(?,?,?,?,?,?,?)",(acc_no,name,age,address,balance,acc_type,mobile_number)) + cur.execute("insert into bank values(?,?,?,?,?,?,?)", + (acc_no, name, age, address, balance, acc_type, mobile_number)) conn.commit() - acc_no=acc_no+1 - return acc_no-1 -#check account in database + acc_no = acc_no + 1 + return acc_no - 1 + + +# check account in database def check_acc_no(acc_no): cur.execute("select acc_no from bank") - list_acc_no=cur.fetchall() + list_acc_no = cur.fetchall() for i in range(len(list_acc_no)): - if list_acc_no[i][0]==int(acc_no): + if list_acc_no[i][0] == int(acc_no): return True return False -#get all details of a particular customer from database + + +# get all details of a particular customer from database def get_details(acc_no): - cur.execute("select * from bank where acc_no=?",(acc_no)) + cur.execute("select * from bank where acc_no=?", (acc_no)) global detail detail = cur.fetchall() print(detail) - if len(detail)==0: + if len(detail) == 0: return False else: - return (detail[0][0],detail[0][1],detail[0][2],detail[0][3],detail[0][4],detail[0][5],detail[0][6]) -#add new balance of customer in bank database -def update_balance(new_money,acc_no): - cur.execute("select balance from bank where acc_no=?",(acc_no,)) - bal=cur.fetchall() - bal=bal[0][0] - new_bal=bal+int(new_money) - - cur.execute("update bank set balance=? where acc_no=?",(new_bal,acc_no)) + return (detail[0][0], detail[0][1], detail[0][2], detail[0][3], detail[0][4], detail[0][5], detail[0][6]) + + +# add new balance of customer in bank database +def update_balance(new_money, acc_no): + cur.execute("select balance from bank where acc_no=?", (acc_no,)) + bal = cur.fetchall() + bal = bal[0][0] + new_bal = bal + int(new_money) + + cur.execute("update bank set balance=? where acc_no=?", (new_bal, acc_no)) conn.commit() -#deduct balance from customer bank database -def deduct_balance(new_money,acc_no): - cur.execute("select balance from bank where acc_no=?",(acc_no,)) - bal=cur.fetchall() - bal=bal[0][0] - if bal 21: outcome = "you won!!" elif player_card.get_value() <= dealer_card.get_value(): @@ -113,32 +120,35 @@ def stand(): score1 = str(player_card.get_value()) score2 = str(dealer_card.get_value()) + def hit(): - global outcome, in_play, score1, score2,player_card, dealer_card, deck + global outcome, in_play, score1, score2, player_card, dealer_card, deck if in_play == True: - player_card.add_card(deck.deal_card()) - + player_card.add_card(deck.deal_card()) + if player_card.get_value() > 21: outcome = "you are busted" in_play = False - + score1 = str(player_card.get_value()) score2 = str(dealer_card.get_value()) - + + def draw(canvas): - canvas.draw_text(outcome , [250, 150],25 , 'White') - canvas.draw_text("BlackJack" , [250, 50], 40, 'Black') - canvas.draw_text(score1 , [100, 100] , 40, 'Red') - - player_card.draw(canvas , [20 ,300]) - dealer_card.draw(canvas , [300 ,300]) - canvas.draw_text(score2 , [400, 100] , 40, 'Red') + canvas.draw_text(outcome, [250, 150], 25, 'White') + canvas.draw_text("BlackJack", [250, 50], 40, 'Black') + canvas.draw_text(score1, [100, 100], 40, 'Red') + + player_card.draw(canvas, [20, 300]) + dealer_card.draw(canvas, [300, 300]) + canvas.draw_text(score2, [400, 100], 40, 'Red') + frame = simplegui.create_frame("Blackjack", 600, 600) frame.set_canvas_background("Green") frame.add_button("Deal", deal, 200) -frame.add_button("Hit", hit, 200) +frame.add_button("Hit", hit, 200) frame.add_button("Stand", stand, 200) frame.set_draw_handler(draw) diff --git a/blackjack.py b/blackjack.py index fdf9754d026..9fef7b2c6e0 100644 --- a/blackjack.py +++ b/blackjack.py @@ -2,92 +2,86 @@ import random -deck=[1,2,3,4,5,6,7,8,9,10,10,10,10,11]*4 +deck = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 10, 10, 10, 11] * 4 random.shuffle(deck) +print( + " ********************************************************** ") +print( + " Welcome to the game Casino - BLACK JACK ! ") +print( + " ********************************************************** ") -print(" ********************************************************** ") -print(" Welcome to the game Casino - BLACK JACK ! ") -print(" ********************************************************** ") - - -d_cards = [] #Initialising dealer's cards -p_cards = [] #Initialising player's cards +d_cards = [] # Initialising dealer's cards +p_cards = [] # Initialising player's cards while len(d_cards) != 2: - random.shuffle(deck) - d_cards.append(deck.pop()) - if len(d_cards) == 2: - print('The cards dealer has are X ',d_cards[1]) - - + random.shuffle(deck) + d_cards.append(deck.pop()) + if len(d_cards) == 2: + print('The cards dealer has are X ', d_cards[1]) # Displaying the Player's cards while len(p_cards) != 2: - random.shuffle(deck) - p_cards.append(deck.pop()) - if len(p_cards) == 2: - print("The total of player is ",sum(p_cards)) - print("The cards Player has are ",p_cards) - + random.shuffle(deck) + p_cards.append(deck.pop()) + if len(p_cards) == 2: + print("The total of player is ", sum(p_cards)) + print("The cards Player has are ", p_cards) if sum(p_cards) > 21: - print("You are BUSTED !\n **************Dealer Wins !!******************\n") - exit() + print("You are BUSTED !\n **************Dealer Wins !!******************\n") + exit() if sum(d_cards) > 21: - print("Dealer is BUSTED !\n ************** You are the Winner !!******************\n") - exit() + print("Dealer is BUSTED !\n ************** You are the Winner !!******************\n") + exit() if sum(d_cards) == 21: - print("***********************Dealer is the Winner !!******************") - exit() + print("***********************Dealer is the Winner !!******************") + exit() if sum(d_cards) == 21 and sum(p_cards) == 21: - print("*****************The match is tie !!*************************") - exit() + print("*****************The match is tie !!*************************") + exit() def dealer_choice(): - if sum(d_cards) < 17: - while sum(d_cards) < 17: - random.shuffle(deck) - d_cards.append(deck.pop()) - - - print("Dealer has total "+ str(sum(d_cards))+"with the cards ",d_cards) - - if sum(p_cards) == sum(d_cards): - print("***************The match is tie !!****************") - exit() - - - if sum(d_cards) == 21: - if sum(p_cards) < 21: - print("***********************Dealer is the Winner !!******************") - elif sum(p_cards) == 21: - print("********************There is tie !!**************************") - else: - print("***********************Dealer is the Winner !!******************") - - elif sum(d_cards) <21: - if sum(p_cards) < 21 and sum(p_cards) < sum(d_cards): - print("***********************Dealer is the Winner !!******************") - if sum(p_cards) == 21: - print("**********************Player is winner !!**********************") - if sum(p_cards) < 21 and sum(p_cards) > sum(d_cards): - print("**********************Player is winner !!**********************") - - else: - if sum(p_cards) < 21: - print("**********************Player is winner !!**********************") - elif sum(p_cards) == 21: - print("**********************Player is winner !!**********************") - else: - print("***********************Dealer is the Winner !!******************") - + if sum(d_cards) < 17: + while sum(d_cards) < 17: + random.shuffle(deck) + d_cards.append(deck.pop()) + + print("Dealer has total " + str(sum(d_cards)) + "with the cards ", d_cards) + + if sum(p_cards) == sum(d_cards): + print("***************The match is tie !!****************") + exit() + + if sum(d_cards) == 21: + if sum(p_cards) < 21: + print("***********************Dealer is the Winner !!******************") + elif sum(p_cards) == 21: + print("********************There is tie !!**************************") + else: + print("***********************Dealer is the Winner !!******************") + + elif sum(d_cards) < 21: + if sum(p_cards) < 21 and sum(p_cards) < sum(d_cards): + print("***********************Dealer is the Winner !!******************") + if sum(p_cards) == 21: + print("**********************Player is winner !!**********************") + if sum(p_cards) < 21 and sum(p_cards) > sum(d_cards): + print("**********************Player is winner !!**********************") + else: + if sum(p_cards) < 21: + print("**********************Player is winner !!**********************") + elif sum(p_cards) == 21: + print("**********************Player is winner !!**********************") + else: + print("***********************Dealer is the Winner !!******************") while sum(p_cards) < 21: @@ -96,17 +90,14 @@ def dealer_choice(): if k == 1: random.shuffle(deck) p_cards.append(deck.pop()) - print ('You have a total of ' + str(sum(p_cards)) - + ' with the cards ', p_cards) + print('You have a total of ' + str(sum(p_cards)) + + ' with the cards ', p_cards) if sum(p_cards) > 21: - print ('*************You are BUSTED !*************\n Dealer Wins !!') + print('*************You are BUSTED !*************\n Dealer Wins !!') if sum(p_cards) == 21: - print ('*******************You are the Winner !!*****************************') - - - else: - dealer_choice() - break - + print('*******************You are the Winner !!*****************************') + else: + dealer_choice() + break diff --git a/brickout-game/brickout-game.py b/brickout-game/brickout-game.py index 59cc2234a50..53b1a29ec36 100644 --- a/brickout-game/brickout-game.py +++ b/brickout-game/brickout-game.py @@ -14,11 +14,11 @@ That includes the classes Ball, Paddle, Brick, and BrickWall. """ - -import pygame + import random - +import pygame + # Define Four Colours BLACK = (0, 0, 0) WHITE = (255, 255, 255) @@ -35,8 +35,10 @@ This is a simple Ball class for respresenting a ball in the game. """ + + class Ball(object): - def __init__ (self, screen, radius,x,y): + def __init__(self, screen, radius, x, y): self.__screen = screen self._radius = radius self._xLoc = x @@ -46,15 +48,19 @@ def __init__ (self, screen, radius,x,y): w, h = pygame.display.get_surface().get_size() self.__width = w self.__height = h + def getXVel(self): return self.__xVel + def getYVel(self): return self.__yVel + def draw(self): """ draws the ball onto screen. """ - pygame.draw.circle(screen,(255, 0, 0) , (self._xLoc,self._yLoc), self._radius) + pygame.draw.circle(screen, (255, 0, 0), (self._xLoc, self._yLoc), self._radius) + def update(self, paddle, brickwall): """ moves the ball at the screen. @@ -62,16 +68,16 @@ def update(self, paddle, brickwall): """ self._xLoc += self.__xVel self._yLoc += self.__yVel - #left screen wall bounce + # left screen wall bounce if self._xLoc <= self._radius: self.__xVel *= -1 - #right screen wall bounce + # right screen wall bounce elif self._xLoc >= self.__width - self._radius: self.__xVel *= -1 - #top wall bounce + # top wall bounce if self._yLoc <= self._radius: self.__yVel *= -1 - #bottom drop out + # bottom drop out elif self._yLoc >= self.__width - self._radius: return True @@ -88,17 +94,19 @@ def update(self, paddle, brickwall): ballY = self._yLoc if ((ballX + self._radius) >= paddleX and ballX <= (paddleX + paddleW)) \ - and ((ballY + self._radius) >= paddleY and ballY <= (paddleY + paddleH)): + and ((ballY + self._radius) >= paddleY and ballY <= (paddleY + paddleH)): self.__yVel *= -1 return False - + """ Simple class for representing a paddle -""" -class Paddle (object): - def __init__ (self, screen, width, height,x,y): +""" + + +class Paddle(object): + def __init__(self, screen, width, height, x, y): self.__screen = screen self._width = width self._height = height @@ -107,25 +115,30 @@ def __init__ (self, screen, width, height,x,y): w, h = pygame.display.get_surface().get_size() self.__W = w self.__H = h + def draw(self): """ draws the paddle onto screen. """ - pygame.draw.rect(screen, (0,0,0), (self._xLoc,self._yLoc,self._width,self._height),0) + pygame.draw.rect(screen, (0, 0, 0), (self._xLoc, self._yLoc, self._width, self._height), 0) + def update(self): """ moves the paddle at the screen via mouse """ - x,y = pygame.mouse.get_pos() + x, y = pygame.mouse.get_pos() if x >= 0 and x <= (self.__W - self._width): self._xLoc = x - + + """ This class represents a simple Brick class. For representing bricks onto screen. """ -class Brick (pygame.sprite.Sprite): - def __init__(self, screen, width, height, x,y): + + +class Brick(pygame.sprite.Sprite): + def __init__(self, screen, width, height, x, y): self.__screen = screen self._width = width self._height = height @@ -135,24 +148,28 @@ def __init__(self, screen, width, height, x,y): self.__W = w self.__H = h self.__isInGroup = False + def draw(self): """ draws the brick onto screen. color: rgb(56, 177, 237) """ - pygame.draw.rect(screen, (56, 177, 237), (self._xLoc,self._yLoc,self._width,self._height),0) - def add (self, group): + pygame.draw.rect(screen, (56, 177, 237), (self._xLoc, self._yLoc, self._width, self._height), 0) + + def add(self, group): """ adds this brick to a given group. """ group.add(self) self.__isInGroup = True + def remove(self, group): """ removes this brick from the given group. """ group.remove(self) self.__isInGroup = False + def alive(self): """ returns true when this brick belongs to the brick wall. @@ -173,10 +190,9 @@ def collide(self, ball): ballXVel = ball.getXVel() ballYVel = ball.getYVel() - - if ((ballX + ball._radius) >= brickX and (ballX+ball._radius) <= (brickX + brickW)) \ - and ((ballY - ball._radius) >= brickY and (ballY - ball._radius)\ - <= (brickY + brickH)): + if ((ballX + ball._radius) >= brickX and (ballX + ball._radius) <= (brickX + brickW)) \ + and ((ballY - ball._radius) >= brickY and (ballY - ball._radius) \ + <= (brickY + brickH)): return True else: return False @@ -186,8 +202,10 @@ def collide(self, ball): This is a simple class for representing a brick wall. """ -class BrickWall (pygame.sprite.Group): - def __init__ (self,screen, x, y, width, height): + + +class BrickWall(pygame.sprite.Group): + def __init__(self, screen, x, y, width, height): self.__screen = screen self._x = x self._y = y @@ -199,21 +217,23 @@ def __init__ (self,screen, x, y, width, height): Y = y for i in range(3): for j in range(4): - self._bricks.append(Brick(screen,width,height,X,Y)) - X += width + (width/ 7.0) + self._bricks.append(Brick(screen, width, height, X, Y)) + X += width + (width / 7.0) Y += height + (height / 7.0) X = x - - def add(self,brick): + + def add(self, brick): """ adds a brick to this BrickWall (group) """ self._bricks.append(brick) - def remove(self,brick): + + def remove(self, brick): """ removes a brick from this BrickWall (group) """ self._bricks.remove(brick) + def draw(self): """ draws all bricks onto screen. @@ -221,6 +241,7 @@ def draw(self): for brick in self._bricks: if brick != None: brick.draw() + def update(self, ball): """ checks collision between ball and bricks. @@ -228,17 +249,19 @@ def update(self, ball): for i in range(len(self._bricks)): if ((self._bricks[i] != None) and self._bricks[i].collide(ball)): self._bricks[i] = None - + # removes the None-elements from the brick list. for brick in self._bricks: if brick == None: self._bricks.remove(brick) + def hasWin(self): """ Has player win the game? """ return len(self._bricks) == 0 - def collide (self, ball): + + def collide(self, ball): """ check collisions between the ball and any of the bricks. @@ -248,27 +271,28 @@ def collide (self, ball): return True return False + # The game objects ball, paddle and brick wall -ball = Ball(screen,25, random.randint(1,700),250) -paddle = Paddle(screen,100,20,250,450) -brickWall = BrickWall(screen,25,25,150,50) +ball = Ball(screen, 25, random.randint(1, 700), 250) +paddle = Paddle(screen, 100, 20, 250, 450) +brickWall = BrickWall(screen, 25, 25, 150, 50) -isGameOver = False # determines whether game is lose -gameStatus = True # game is still running +isGameOver = False # determines whether game is lose +gameStatus = True # game is still running + +score = 0 # score for the game. -score = 0 # score for the game. - pygame.display.set_caption("Brickout-game") - + # Loop until the user clicks the close button. done = False - + # Used to manage how fast the screen updates clock = pygame.time.Clock() # for displaying text in the game -pygame.font.init() # you have to call this at the start, - # if you want to use this module. +pygame.font.init() # you have to call this at the start, +# if you want to use this module. # message for game over mgGameOver = pygame.font.SysFont('Comic Sans MS', 40) @@ -280,30 +304,29 @@ def collide (self, ball): mgScore = pygame.font.SysFont('Comic Sans MS', 40) textsurfaceGameOver = mgGameOver.render('Game Over!', False, (0, 0, 0)) -textsurfaceWin = mgWin.render("You win!",False,(0,0,0)) -textsurfaceScore = mgScore.render("score: "+str(score),False,(0,0,0)) - - +textsurfaceWin = mgWin.render("You win!", False, (0, 0, 0)) +textsurfaceScore = mgScore.render("score: " + str(score), False, (0, 0, 0)) + # -------- Main Program Loop ----------- while not done: # --- Main event loop for event in pygame.event.get(): if event.type == pygame.QUIT: done = True - + # --- Game logic should go here - + # --- Screen-clearing code goes here - + # Here, we clear the screen to white. Don't put other drawing commands # above this, or they will be erased with this command. - + # If you want a background image, replace this clear with blit'ing the # background image. screen.fill(WHITE) - + # --- Drawing code should go here - + """ Because I use OOP in the game logic and the drawing code, are both in the same section. @@ -313,11 +336,11 @@ def collide (self, ball): # first draws ball for appropriate displaying the score. brickWall.draw() - # for counting and displaying the score + # for counting and displaying the score if brickWall.collide(ball): score += 10 - textsurfaceScore = mgScore.render("score: "+str(score),False,(0,0,0)) - screen.blit(textsurfaceScore,(300,0)) + textsurfaceScore = mgScore.render("score: " + str(score), False, (0, 0, 0)) + screen.blit(textsurfaceScore, (300, 0)) # after scoring. because hit bricks are removed in the update-method brickWall.update(ball) @@ -328,27 +351,27 @@ def collide (self, ball): if ball.update(paddle, brickWall): isGameOver = True gameStatus = False - + if brickWall.hasWin(): gameStatus = False ball.draw() - else: # game isn't running. - if isGameOver: # player lose - screen.blit(textsurfaceGameOver,(0,0)) - textsurfaceScore = mgScore.render("score: "+str(score),False,(0,0,0)) - screen.blit(textsurfaceScore,(300,0)) - elif brickWall.hasWin(): # player win - screen.blit(textsurfaceWin,(0,0)) - textsurfaceScore = mgScore.render("score: "+str(score),False,(0,0,0)) - screen.blit(textsurfaceScore,(300,0)) - + else: # game isn't running. + if isGameOver: # player lose + screen.blit(textsurfaceGameOver, (0, 0)) + textsurfaceScore = mgScore.render("score: " + str(score), False, (0, 0, 0)) + screen.blit(textsurfaceScore, (300, 0)) + elif brickWall.hasWin(): # player win + screen.blit(textsurfaceWin, (0, 0)) + textsurfaceScore = mgScore.render("score: " + str(score), False, (0, 0, 0)) + screen.blit(textsurfaceScore, (300, 0)) + # --- Go ahead and update the screen with what we've drawn. pygame.display.flip() - + # --- Limit to 60 frames per second clock.tick(60) - + # Close the window and quit. pygame.quit() diff --git a/changemac.py b/changemac.py index ba123866710..1cf7a875edc 100644 --- a/changemac.py +++ b/changemac.py @@ -3,13 +3,11 @@ # Simple python Script to change mac address of linux generate random or enter mac address +import random +from subprocess import PIPE, Popen - - -import random,os,base64 -from subprocess import PIPE, Popen -#function for returning terminal command +# function for returning terminal command def cret(command): process = Popen( args=command, @@ -18,75 +16,66 @@ def cret(command): ) return process.communicate()[0] -#function for genrate mac address random -def randmac(): - return [ 0x00, 0x16, 0x3e, - random.randint(0x00, 0x7f), - random.randint(0x00, 0xff), - random.randint(0x00, 0xff) ] - -def retrandmac(mac): - return ':'.join(map(lambda x: "%02x" % x, mac)) +# function for genrate mac address random +def randmac(): + return [0x00, 0x16, 0x3e, + random.randint(0x00, 0x7f), + random.randint(0x00, 0xff), + random.randint(0x00, 0xff)] +def retrandmac(mac): + return ':'.join(map(lambda x: "%02x" % x, mac)) print(" +-+-+-+ +-+-+-+-+-+-+-+") print(" |M|A|C| |c|h|a|n|g|e|r|") print(" +-+-+-+ +-+-+-+-+-+-+-+") -#finding wireless interface name that should start with wl e.g.-wlan0,wlp3s0 -infname=cret('ifconfig -a | egrep "^[wl-wl]+" | sed "s/: .*//" | grep -v "lo"') -#INTERFACE NAME 6 character so return 6 last character -infname=infname[:6] -infname=infname.decode('utf-8') -#GETTING MAC Address from /sys/class/net/wlan0/address directory -cmdgetmac=('cat /sys/class/net/'+infname+'/address') -crrntmac=cret("cat /sys/class/net/"+infname+"/address") -crrntmac=crrntmac.decode('utf-8') -print("Your Current mac address = "+crrntmac+"\nEnter Option to change Your MAC:\n1. Enter MAC address manually \n2. Automatic Random MAC address") -opt=int(input()) - - - -if opt==1: - print("Please Enter Your New MAC address: \nExmple: 46:d2:f4:0c:2a:50") - - newmac=input() - print("Please wait changing mac address..................") - - - #first turn off wifi - cret('nmcli radio wifi off') - - changemaccmd="sudo ip link set dev "+infname+" address "+newmac -#executing command with new mac address - cret(changemaccmd) -#turning on wifi - cret('nmcli radio wifi on') -#GETTING MAC Address from /sys/class/net/wlan0/address directory - cr=cret("cat /sys/class/net/"+infname+"/address") - cr=cr.decode('utf-8') - - - print("\nNow Your Current mac address = "+cr) - - -elif opt==2: - genmac=retrandmac(randmac()) - print("Please wait generating new mac address.....................") - cret('nmcli radio wifi off') - changemaccmd="sudo ip link set dev "+infname+" address "+genmac - cret(changemaccmd) - cret('nmcli radio wifi on') - cr=cret("cat /sys/class/net/"+infname+"/address") - cr=cr.decode('utf-8') - print("Now Your Current mac address = "+cr) +# finding wireless interface name that should start with wl e.g.-wlan0,wlp3s0 +infname = cret('ifconfig -a | egrep "^[wl-wl]+" | sed "s/: .*//" | grep -v "lo"') +# INTERFACE NAME 6 character so return 6 last character +infname = infname[:6] +infname = infname.decode('utf-8') +# GETTING MAC Address from /sys/class/net/wlan0/address directory +cmdgetmac = ('cat /sys/class/net/' + infname + '/address') +crrntmac = cret("cat /sys/class/net/" + infname + "/address") +crrntmac = crrntmac.decode('utf-8') +print( + "Your Current mac address = " + crrntmac + "\nEnter Option to change Your MAC:\n1. Enter MAC address manually \n2. Automatic Random MAC address") +opt = int(input()) + +if opt == 1: + print("Please Enter Your New MAC address: \nExmple: 46:d2:f4:0c:2a:50") + + newmac = input() + print("Please wait changing mac address..................") + + # first turn off wifi + cret('nmcli radio wifi off') + + changemaccmd = "sudo ip link set dev " + infname + " address " + newmac + # executing command with new mac address + cret(changemaccmd) + # turning on wifi + cret('nmcli radio wifi on') + # GETTING MAC Address from /sys/class/net/wlan0/address directory + cr = cret("cat /sys/class/net/" + infname + "/address") + cr = cr.decode('utf-8') + + print("\nNow Your Current mac address = " + cr) + + +elif opt == 2: + genmac = retrandmac(randmac()) + print("Please wait generating new mac address.....................") + cret('nmcli radio wifi off') + changemaccmd = "sudo ip link set dev " + infname + " address " + genmac + cret(changemaccmd) + cret('nmcli radio wifi on') + cr = cret("cat /sys/class/net/" + infname + "/address") + cr = cr.decode('utf-8') + print("Now Your Current mac address = " + cr) else: - print("You Have Selected wrong Option") - - - - - + print("You Have Selected wrong Option") diff --git a/check_file.py b/check_file.py index ba72215214a..655c6eb1dde 100644 --- a/check_file.py +++ b/check_file.py @@ -9,8 +9,9 @@ # Description : Check a file exists and that we can read the file from __future__ import print_function -import sys # Import the Modules + import os # Import the Modules +import sys # Import the Modules # Prints usage if not appropriate length of arguments are provided diff --git a/check_for_sqlite_files.py b/check_for_sqlite_files.py index 5aa472af11c..e5ab0f83b9a 100644 --- a/check_for_sqlite_files.py +++ b/check_for_sqlite_files.py @@ -9,6 +9,7 @@ # Description : Scans directories to check if there are any sqlite files in there from __future__ import print_function + import os diff --git a/check_internet_con.py b/check_internet_con.py index 98081f17568..d1e7ca79a78 100644 --- a/check_internet_con.py +++ b/check_internet_con.py @@ -8,6 +8,7 @@ # Fall back to Python 2's urllib2 from urllib2 import URLError, urlopen + def checkInternetConnectivity(): try: urlopen("http://google.com", timeout=2) diff --git a/classicIndianCardMatch.py b/classicIndianCardMatch.py index c3f169af39a..6550b8f7460 100644 --- a/classicIndianCardMatch.py +++ b/classicIndianCardMatch.py @@ -1,11 +1,13 @@ -import random,time +import random +import time SUITS = ('C', 'S', 'H', 'D') RANKS = ('A', '2', '3', '4', '5', '6', '7', '8', '9', 'T', 'J', 'Q', 'K') -VALUES = {'A':1, '2':2, '3':3, '4':4, '5':5, '6':6, '7':7, '8':8, '9':9, 'T':10, 'J':10, 'Q':10, 'K':10} +VALUES = {'A': 1, '2': 2, '3': 3, '4': 4, '5': 5, '6': 6, '7': 7, '8': 8, '9': 9, 'T': 10, 'J': 10, 'Q': 10, 'K': 10} + class card: - def __init__(self,suit,rank): + def __init__(self, suit, rank): if (suit in SUITS) and (rank in RANKS): self.suit = suit self.rank = rank @@ -13,23 +15,31 @@ def __init__(self,suit,rank): self.suit = None self.rank = None print("Invalid card: ", suit, rank) + def __str__(self): return self.suit + self.rank + def getRank(self): return self.rank + def getSuit(self): return self.suit + class deck: def __init__(self): - self.deck = [card(suit,rank) for suit in SUITS for rank in RANKS] + self.deck = [card(suit, rank) for suit in SUITS for rank in RANKS] + def shuffle(self): random.shuffle(self.deck) + def dealCard(self): return random.choice(self.deck) + def __str__(self): print(self.deck) + # Begin play # create two decks, one for each player. print("Gathering brand new two decks of cards............\n") @@ -39,7 +49,7 @@ def __str__(self): print('..........decks ready!!!\n') print('Combining and shuffling both the decks..') time.sleep(10) -#Shuffle the decks +# Shuffle the decks deck1.shuffle() deck2.shuffle() # combine both the shuffled decks @@ -63,7 +73,7 @@ def __str__(self): centerPile = [] currentPlayer2Card = None -while len(player1) != 0 and len(player2) != 0: #this needs a fix as it goes on an infinite loop on a success. +while len(player1) != 0 and len(player2) != 0: # this needs a fix as it goes on an infinite loop on a success. switchPlayer = True while switchPlayer == True: for card in range(len(player1)): @@ -91,9 +101,4 @@ def __str__(self): print("GAME OVER!!!\n") -print("Human has {} cards and computer has {}..".format(len(player1),len(player2))) - - - - - +print("Human has {} cards and computer has {}..".format(len(player1), len(player2))) diff --git a/communication/file.py b/communication/file.py index 2b1d1e29fca..df2c16fa9d2 100755 --- a/communication/file.py +++ b/communication/file.py @@ -1,18 +1,18 @@ #!/usr/bin/python # coding: utf-8 - + +import math import os import sys -import math - - + + def slice(mink, maxk): s = 0.0 for k in range(int(mink), int(maxk)): - s += 1.0/(2*k+1)/(2*k+1) + s += 1.0 / (2 * k + 1) / (2 * k + 1) return s - - + + def pi(n): pids = [] unit = n / 10 @@ -34,8 +34,8 @@ def pi(n): sums.append(float(f.read())) os.remove("%d" % pid) # 删除通信的文件 return math.sqrt(sum(sums) * 8) - -if __name__ == '__main__': + + +if __name__ == '__main__': print("start") print(pi(10000000)) - diff --git a/communication/pipe.py b/communication/pipe.py index fd2837baa62..4138c519570 100644 --- a/communication/pipe.py +++ b/communication/pipe.py @@ -1,18 +1,19 @@ # coding: utf-8 - + from __future__ import print_function + +import math import os import sys -import math - - + + def slice(mink, maxk): s = 0.0 for k in range(mink, maxk): - s += 1.0/(2*k+1)/(2*k+1) + s += 1.0 / (2 * k + 1) / (2 * k + 1) return s - - + + def pi(n): childs = {} unit = n / 10 @@ -37,7 +38,6 @@ def pi(n): os.close(r) # 读完了,关闭读描述符 os.waitpid(pid, 0) # 等待子进程结束 return math.sqrt(sum(sums) * 8) - - -print(pi(10000000)) + +print(pi(10000000)) diff --git a/communication/socket_conn.py b/communication/socket_conn.py index 8789d1da640..ffe1ed437fa 100644 --- a/communication/socket_conn.py +++ b/communication/socket_conn.py @@ -1,17 +1,20 @@ # coding: utf-8 - + from __future__ import print_function -import os -import sys + import math +import os import socket - +import sys + + def slice(mink, maxk): s = 0.0 for k in range(mink, maxk): - s += 1.0/(2*k+1)/(2*k+1) + s += 1.0 / (2 * k + 1) / (2 * k + 1) return s - + + def pi(n): childs = {} unit = n / 10 @@ -35,6 +38,6 @@ def pi(n): rsock.close() os.waitpid(pid, 0) # 等待子进程结束 return math.sqrt(sum(sums) * 8) - - + + print(pi(10000000)) diff --git a/cricket_live_score.py b/cricket_live_score.py index 9f29600ede2..41a07f726ba 100644 --- a/cricket_live_score.py +++ b/cricket_live_score.py @@ -1,7 +1,7 @@ -import bs4 -from bs4 import BeautifulSoup as soup from urllib.request import urlopen as uReq +from bs4 import BeautifulSoup as soup + my_url = "http://www.cricbuzz.com/" Client = uReq(my_url) diff --git a/daily_checks.py b/daily_checks.py index bcb85aa5ccb..13d2e2fac9f 100644 --- a/daily_checks.py +++ b/daily_checks.py @@ -12,11 +12,10 @@ Description : This simple script loads everything I need to carry out the daily checks for our systems. """ -import platform # Load Modules import os +import platform # Load Modules import subprocess import sys - from time import strftime # Load just the strftime Module from Time diff --git a/days_from_date.py b/days_from_date.py index 17640e5a446..daa1d1d5f58 100644 --- a/days_from_date.py +++ b/days_from_date.py @@ -1,29 +1,32 @@ -from datetime import date -import sys -import re import calendar +import re +import sys +from datetime import date + def cleanDate(date_): - date_.replace(' ','') - date_.replace(',','') - date_.replace('/','') - return date_ - -def getYearMonthDay(date_): - day , year = map(int,re.findall(r'\d+',date_)) - month = ''.join(re.findall(r'[a-zA-Z]',date_)).capitalize() + date_.replace(' ', '') + date_.replace(',', '') + date_.replace('/', '') + return date_ + + +def getYearMonthDay(date_): + day, year = map(int, re.findall(r'\d+', date_)) + month = ''.join(re.findall(r'[a-zA-Z]', date_)).capitalize() month_num = list(calendar.month_abbr).index(month[:3]) - - return year,month_num,day -def numOfDays(year,month_num,day): - days = date(year,month_num,day).timetuple()[-2] - + return year, month_num, day + + +def numOfDays(year, month_num, day): + days = date(year, month_num, day).timetuple()[-2] + return days date_ = sys.argv[1] date_ = cleanDate(date_) -year,month_num,day = getYearMonthDay(date_) -print(numOfDays(year,month_num,day) - 1) +year, month_num, day = getYearMonthDay(date_) +print(numOfDays(year, month_num, day) - 1) diff --git a/dir_test.py b/dir_test.py index 76b445bc972..0e75426b64c 100644 --- a/dir_test.py +++ b/dir_test.py @@ -7,6 +7,7 @@ # Description : Tests to see if the directory testdir exists, if not it will create the directory for you from __future__ import print_function + import os try: diff --git a/factor.py b/factor.py index a58fc519b1a..2e17bec367f 100644 --- a/factor.py +++ b/factor.py @@ -2,6 +2,8 @@ def factorial(n): if n == 0: return 1 else: - return n * factorial(n-1) -n=int(input("Input a number to compute the factiorial : ")) + return n * factorial(n - 1) + + +n = int(input("Input a number to compute the factiorial : ")) print(factorial(n)) diff --git a/factorial.py b/factorial.py index a58fc519b1a..2e17bec367f 100644 --- a/factorial.py +++ b/factorial.py @@ -2,6 +2,8 @@ def factorial(n): if n == 0: return 1 else: - return n * factorial(n-1) -n=int(input("Input a number to compute the factiorial : ")) + return n * factorial(n - 1) + + +n = int(input("Input a number to compute the factiorial : ")) print(factorial(n)) diff --git a/factors.py b/factors.py index 9ef43e58a9e..b14b0398baa 100644 --- a/factors.py +++ b/factors.py @@ -4,7 +4,7 @@ a = int(input('Type now // ')) b = 1 while b <= math.sqrt(a): - if a % b == 0: - print("A factor of the number is ", b) - print("A factor of the number is ", int(a/b)) - b += 1 + if a % b == 0: + print("A factor of the number is ", b) + print("A factor of the number is ", int(a / b)) + b += 1 diff --git a/fibonacci.py b/fibonacci.py index f4c4d759740..6e28a15214c 100644 --- a/fibonacci.py +++ b/fibonacci.py @@ -5,54 +5,54 @@ def getFibonacciIterative(n: int) -> int: - """ - Calculate the fibonacci number at position n iteratively - """ + """ + Calculate the fibonacci number at position n iteratively + """ - a = 0 - b = 1 + a = 0 + b = 1 - for i in range(n): - a, b = b, a + b + for i in range(n): + a, b = b, a + b - return a + return a def getFibonacciRecursive(n: int) -> int: - """ - Calculate the fibonacci number at position n recursively - """ + """ + Calculate the fibonacci number at position n recursively + """ - a = 0 - b = 1 + a = 0 + b = 1 - def step(n: int) -> int: - nonlocal a, b - if n <= 0: - return a - a, b = b, a + b - return step(n - 1) + def step(n: int) -> int: + nonlocal a, b + if n <= 0: + return a + a, b = b, a + b + return step(n - 1) - return step(n) + return step(n) def compareFibonacciCalculators(n: int) -> None: - """ - Interactively compare both fibonacci generators - """ - - startI = time.clock() - resultI = getFibonacciIterative(n) - endI = time.clock() - - startR = time.clock() - resultR = getFibonacciRecursive(n) - endR = time.clock() - - s = "{} calculting {} => {} in {} seconds" - print(s.format( - "Iteratively", n, resultI, endI - startI - )) - print(s.format( - "Recursively", n, resultR, endR - startR - )) + """ + Interactively compare both fibonacci generators + """ + + startI = time.clock() + resultI = getFibonacciIterative(n) + endI = time.clock() + + startR = time.clock() + resultR = getFibonacciRecursive(n) + endR = time.clock() + + s = "{} calculting {} => {} in {} seconds" + print(s.format( + "Iteratively", n, resultI, endI - startI + )) + print(s.format( + "Recursively", n, resultR, endR - startR + )) diff --git a/fileinfo.py b/fileinfo.py index 1c9711c086e..774b7f5e365 100644 --- a/fileinfo.py +++ b/fileinfo.py @@ -11,15 +11,16 @@ # get file information using os.stat() # tested with Python24 vegsaeat 25sep2006 from __future__ import print_function + import os +import stat # index constants for os.stat() import sys -import stat # index constants for os.stat() import time if sys.version_info >= (3, 0): raw_input = input -file_name = raw_input("Enter a file name: ") # pick a file you have +file_name = raw_input("Enter a file name: ") # pick a file you have count = 0 t_char = 0 try: @@ -39,34 +40,34 @@ file_info = { 'fname': file_name, 'fsize': file_stats[stat.ST_SIZE], - 'f_lm' : time.strftime("%d/%m/%Y %I:%M:%S %p", - time.localtime(file_stats[stat.ST_MTIME])), - 'f_la' : time.strftime("%d/%m/%Y %I:%M:%S %p", - time.localtime(file_stats[stat.ST_ATIME])), - 'f_ct' : time.strftime("%d/%m/%Y %I:%M:%S %p", - time.localtime(file_stats[stat.ST_CTIME])), - 'no_of_lines':count, - 't_char':t_char + 'f_lm': time.strftime("%d/%m/%Y %I:%M:%S %p", + time.localtime(file_stats[stat.ST_MTIME])), + 'f_la': time.strftime("%d/%m/%Y %I:%M:%S %p", + time.localtime(file_stats[stat.ST_ATIME])), + 'f_ct': time.strftime("%d/%m/%Y %I:%M:%S %p", + time.localtime(file_stats[stat.ST_CTIME])), + 'no_of_lines': count, + 't_char': t_char } -print ("\nfile name =", file_info['fname']) -print ("file size =", file_info['fsize'] , "bytes") -print ("last modified =", file_info['f_lm']) -print ("last accessed =", file_info['f_la']) -print ("creation time =", file_info['f_ct']) -print ("Total number of lines are =", file_info['no_of_lines']) -print ("Total number of characters are =", file_info['t_char']) +print("\nfile name =", file_info['fname']) +print("file size =", file_info['fsize'], "bytes") +print("last modified =", file_info['f_lm']) +print("last accessed =", file_info['f_la']) +print("creation time =", file_info['f_ct']) +print("Total number of lines are =", file_info['no_of_lines']) +print("Total number of characters are =", file_info['t_char']) if stat.S_ISDIR(file_stats[stat.ST_MODE]): - print ("This a directory") + print("This a directory") else: - print ("This is not a directory\n") - print ("A closer look at the os.stat(%s) tuple:" % file_name) - print (file_stats) - print ("\nThe above tuple has the following sequence: ") - print ("""st_mode (protection bits), st_ino (inode number), + print("This is not a directory\n") + print("A closer look at the os.stat(%s) tuple:" % file_name) + print(file_stats) + print("\nThe above tuple has the following sequence: ") + print("""st_mode (protection bits), st_ino (inode number), st_dev (device), st_nlink (number of hard links), st_uid (user ID of owner), st_gid (group ID of owner), st_size (file size, bytes), st_atime (last access time, seconds since epoch), st_mtime (last modification time), st_ctime (time of creation, Windows)""" -) + ) diff --git a/find_prime.py b/find_prime.py index 960b077aaaa..db834c5cb35 100644 --- a/find_prime.py +++ b/find_prime.py @@ -26,17 +26,21 @@ ''' import sys + def find_prime(num): res_list = [] - for i in range(2,num+1): - if res_list!=[] and any(i%l==0 for l in res_list): + for i in range(2, num + 1): + if res_list != [] and any(i % l == 0 for l in res_list): continue res_list.append(i) return res_list -if __name__=="__main__": - if len(sys.argv)!=2: raise Exception("usage - $python find_prime.py ") - try:num = int(sys.argv[1]) - except ValueError: raise Exception("Enter an integer as argument only.") + +if __name__ == "__main__": + if len(sys.argv) != 2: raise Exception("usage - $python find_prime.py ") + try: + num = int(sys.argv[1]) + except ValueError: + raise Exception("Enter an integer as argument only.") l = find_prime(num) print(l) diff --git a/folder_size.py b/folder_size.py index a4566800571..d469e4aabc6 100755 --- a/folder_size.py +++ b/folder_size.py @@ -9,25 +9,28 @@ # Description : This will scan the current directory and all subdirectories and display the size. import os -import sys # Load the library module and the sys module for the argument vector''' +import sys # Load the library module and the sys module for the argument vector''' + try: - directory = sys.argv[1] # Set the variable directory to be the argument supplied by user. + directory = sys.argv[1] # Set the variable directory to be the argument supplied by user. except IndexError: sys.exit("Must provide an argument.") -dir_size = 0 # Set the size to 0 +dir_size = 0 # Set the size to 0 fsizedicr = {'Bytes': 1, 'Kilobytes': float(1) / 1024, 'Megabytes': float(1) / (1024 * 1024), 'Gigabytes': float(1) / (1024 * 1024 * 1024)} -for (path, dirs, files) in os.walk(directory): # Walk through all the directories. For each iteration, os.walk returns the folders, subfolders and files in the dir. - for file in files: # Get all the files +for (path, dirs, files) in os.walk( + directory): # Walk through all the directories. For each iteration, os.walk returns the folders, subfolders and files in the dir. + for file in files: # Get all the files filename = os.path.join(path, file) - dir_size += os.path.getsize(filename) # Add the size of each file in the root dir to get the total size. + dir_size += os.path.getsize(filename) # Add the size of each file in the root dir to get the total size. -fsizeList = [str(round(fsizedicr[key] * dir_size, 2)) + " " + key for key in fsizedicr] # List of units +fsizeList = [str(round(fsizedicr[key] * dir_size, 2)) + " " + key for key in fsizedicr] # List of units -if dir_size == 0: print ("File Empty") # Sanity check to eliminate corner-case of empty file. +if dir_size == 0: + print("File Empty") # Sanity check to eliminate corner-case of empty file. else: - for units in sorted(fsizeList)[::-1]: # Reverse sort list of units so smallest magnitude units print first. - print ("Folder Size: " + units) + for units in sorted(fsizeList)[::-1]: # Reverse sort list of units so smallest magnitude units print first. + print("Folder Size: " + units) diff --git a/four_digit_num_combination.py b/four_digit_num_combination.py index 2cf1df7f632..4e0b9c7a2b6 100644 --- a/four_digit_num_combination.py +++ b/four_digit_num_combination.py @@ -1,5 +1,6 @@ """ small script to learn how to print out all 4-digit num""" + # ALL the combinations of 4 digit combo def four_digit_combinations(): """ print out all 4-digit numbers in old way""" @@ -9,6 +10,7 @@ def four_digit_combinations(): print(code) numbers.append(code) + # Same as above but more pythonic def one_line_combinations(): """ print out all 4-digit numbers """ diff --git a/ftp_send_receive.py b/ftp_send_receive.py index 1c9b9a02eb5..1577d412bdc 100644 --- a/ftp_send_receive.py +++ b/ftp_send_receive.py @@ -9,6 +9,7 @@ """ from ftplib import FTP + ftp = FTP('xxx.xxx.x.x') # Enter the ip address or the domain name here ftp.login(user='username', passwd='password') ftp.cwd('/Enter the directory here/') @@ -18,17 +19,20 @@ Enter the location of the file where the file is received """ + def receive_file(filename='example.txt'): - with open(filename, 'wb') as out_file: - ftp.retrbinary('RETR ' + filename, out_file.write, 1024) - ftp.quit() + with open(filename, 'wb') as out_file: + ftp.retrbinary('RETR ' + filename, out_file.write, 1024) + ftp.quit() + """ The file which will be sent via the FTP server The file send will be send to the current working directory """ + def send_file(filename='example.txt'): - with open(filename, 'rb') as in_file: - ftp.storbinary('STOR ' + filename, in_file) - ftp.quit() + with open(filename, 'rb') as in_file: + ftp.storbinary('STOR ' + filename, in_file) + ftp.quit() diff --git a/gambler.py b/gambler.py index 78abd99e115..e56d5dd65d1 100644 --- a/gambler.py +++ b/gambler.py @@ -1,22 +1,22 @@ -from sys import argv import random +from sys import argv stake = int(argv[1]) goals = int(argv[2]) trials = int(argv[3]) wins = 0 -bets = 0 +bets = 0 for i in range(trials): cash = stake while cash > 0 and cash < goals: bets += 1 - if random.randrange(0 , 2) == 0: + if random.randrange(0, 2) == 0: cash += 1 else: cash -= 1 if cash == goals: wins += 1 print("Your won: " + str(100 * wins // trials) + "$") -print("Your bets: " + str(bets // trials)) \ No newline at end of file +print("Your bets: " + str(bets // trials)) diff --git a/game_of_life/game_o_life.py b/game_of_life/game_o_life.py index 32ebe0fc130..cfaef5fc6c2 100644 --- a/game_of_life/game_o_life.py +++ b/game_of_life/game_o_life.py @@ -27,25 +27,29 @@ Any dead cell with exactly three live neighbours be- comes a live cell, as if by reproduction. ''' +import random +import sys + import numpy as np -import random, time, sys from matplotlib import pyplot as plt -import matplotlib.animation as animation from matplotlib.colors import ListedColormap -usage_doc='Usage of script: script_nama ' +usage_doc = 'Usage of script: script_nama ' -choice = [0]*100 + [1]*10 +choice = [0] * 100 + [1] * 10 random.shuffle(choice) + def create_canvas(size): - canvas = [ [False for i in range(size)] for j in range(size)] + canvas = [[False for i in range(size)] for j in range(size)] return canvas + def seed(canvas): - for i,row in enumerate(canvas): - for j,_ in enumerate(row): - canvas[i][j]=bool(random.getrandbits(1)) + for i, row in enumerate(canvas): + for j, _ in enumerate(row): + canvas[i][j] = bool(random.getrandbits(1)) + def run(canvas): ''' This function runs the rules of game through all points, and changes their status accordingly.(in the same canvas) @@ -62,57 +66,62 @@ def run(canvas): for r, row in enumerate(canvas): for c, pt in enumerate(row): # print(r-1,r+2,c-1,c+2) - next_gen_canvas[r][c] = __judge_point(pt,canvas[r-1:r+2,c-1:c+2]) - + next_gen_canvas[r][c] = __judge_point(pt, canvas[r - 1:r + 2, c - 1:c + 2]) + canvas = next_gen_canvas - del next_gen_canvas # cleaning memory as we move on. - return canvas.tolist() + del next_gen_canvas # cleaning memory as we move on. + return canvas.tolist() -def __judge_point(pt,neighbours): - dead = 0 + +def __judge_point(pt, neighbours): + dead = 0 alive = 0 # finding dead or alive neighbours count. for i in neighbours: for status in i: - if status: alive+=1 - else: dead+=1 + if status: + alive += 1 + else: + dead += 1 # handling duplicate entry for focus pt. - if pt : alive-=1 - else : dead-=1 - + if pt: + alive -= 1 + else: + dead -= 1 + # running the rules of game here. state = pt if pt: - if alive<2: - state=False - elif alive==2 or alive==3: - state=True - elif alive>3: - state=False + if alive < 2: + state = False + elif alive == 2 or alive == 3: + state = True + elif alive > 3: + state = False else: - if alive==3: - state=True + if alive == 3: + state = True return state -if __name__=='__main__': +if __name__ == '__main__': if len(sys.argv) != 2: raise Exception(usage_doc) - + canvas_size = int(sys.argv[1]) # main working structure of this module. - c=create_canvas(canvas_size) + c = create_canvas(canvas_size) seed(c) fig, ax = plt.subplots() - fig.show() - cmap = ListedColormap(['w','k']) + fig.show() + cmap = ListedColormap(['w', 'k']) try: while True: - c = run(c) - ax.matshow(c,cmap=cmap) + c = run(c) + ax.matshow(c, cmap=cmap) fig.canvas.draw() - ax.cla() + ax.cla() except KeyboardInterrupt: # do nothing. pass diff --git a/gcd.py b/gcd.py index 720b421bc12..9de766c3374 100644 --- a/gcd.py +++ b/gcd.py @@ -1,16 +1,18 @@ """ This function takes two variable and returns greatest common divisior """ -def find_gcd(x, y): - while(y): - x, y = y, x % y - - return x - - # Input from user - print("For computing gcd of two numbers") - a,b = map(int,input("Enter the number by comma separating :-",end = " ").split(",")) - - # Map typecast the input in 'int' type - - print("Gcd of {} & {} is {}",format(a,b,find_gcd(a,b))) + + +def find_gcd(x, y): + while (y): + x, y = y, x % y + + return x + + # Input from user + print("For computing gcd of two numbers") + a, b = map(int, input("Enter the number by comma separating :-", end=" ").split(",")) + + # Map typecast the input in 'int' type + + print("Gcd of {} & {} is {}", format(a, b, find_gcd(a, b))) diff --git a/get_crypto_price.py b/get_crypto_price.py index c00df655ef2..4e2880d509c 100644 --- a/get_crypto_price.py +++ b/get_crypto_price.py @@ -1,25 +1,28 @@ import ccxt -def getprice(symbol,exchange_id): - symbol = symbol.upper() #BTC/USDT, LTC/USDT, ETH/BTC, LTC/BTC - exchange_id = exchange_id.lower() #binance, #bitmex - symbol_1 = symbol.split("/") - exchange = getattr(ccxt, exchange_id)({ - # https://github.com/ccxt/ccxt/wiki/Manual#rate-limit - 'enableRateLimit': True - }) - try: - v_price = exchange.fetch_ticker (symbol) - r_price = v_price['info']['lastPrice'] - if(symbol_1[1] == "USD" or symbol_1[1] == "USDT"): - v_return = "{:.2f} {}".format(float(r_price),symbol_1[1]) - return v_return - else: - v_return = "{:.8f} {}".format(float(r_price),symbol_1[1]) - return v_return - except (ccxt.ExchangeError, ccxt.NetworkError) as error: - # add necessary handling or rethrow the exception - return 'Got an error', type(error).__name__, error.args - raise -print(getprice("btc/usdt","BINANCE")) -print(getprice("btc/usd","BITMEX")) \ No newline at end of file + +def getprice(symbol, exchange_id): + symbol = symbol.upper() # BTC/USDT, LTC/USDT, ETH/BTC, LTC/BTC + exchange_id = exchange_id.lower() # binance, #bitmex + symbol_1 = symbol.split("/") + exchange = getattr(ccxt, exchange_id)({ + # https://github.com/ccxt/ccxt/wiki/Manual#rate-limit + 'enableRateLimit': True + }) + try: + v_price = exchange.fetch_ticker(symbol) + r_price = v_price['info']['lastPrice'] + if (symbol_1[1] == "USD" or symbol_1[1] == "USDT"): + v_return = "{:.2f} {}".format(float(r_price), symbol_1[1]) + return v_return + else: + v_return = "{:.8f} {}".format(float(r_price), symbol_1[1]) + return v_return + except (ccxt.ExchangeError, ccxt.NetworkError) as error: + # add necessary handling or rethrow the exception + return 'Got an error', type(error).__name__, error.args + raise + + +print(getprice("btc/usdt", "BINANCE")) +print(getprice("btc/usd", "BITMEX")) diff --git a/get_likes_on_FB.py b/get_likes_on_FB.py index 3ed8a2b9a73..fa75486067e 100644 --- a/get_likes_on_FB.py +++ b/get_likes_on_FB.py @@ -1,36 +1,34 @@ from __future__ import print_function -import urllib + import json import sys -import os +import urllib accessToken = 'TOKENVALUE' # YOUR ACCESS TOKEN GETS INSERTED HERE -userId = sys.argv[1] #USERID -limit=100 +userId = sys.argv[1] # USERID +limit = 100 - -url='https://graph.facebook.com/'+userId+'/posts?access_token='+accessToken +'&limit='+str(limit) #FB Link +url = 'https://graph.facebook.com/' + userId + '/posts?access_token=' + accessToken + '&limit=' + str(limit) # FB Link data = json.load(urllib.urlopen(url)) -id=0 +id = 0 print(str(id)) for item in data['data']: - time=item['created_time'][11:19] - date=item['created_time'][5:10] - year=item['created_time'][0:4] - + time = item['created_time'][11:19] + date = item['created_time'][5:10] + year = item['created_time'][0:4] if 'shares' in item: - num_share=item['shares']['count'] + num_share = item['shares']['count'] else: - num_share=0 + num_share = 0 if 'likes' in item: - num_like=item['likes']['count'] + num_like = item['likes']['count'] else: - num_like=0 - + num_like = 0 -id+=1 +id += 1 -print(str(id)+'\t'+ time.encode('utf-8')+'\t'+date.encode('utf-8')+'\t'+year.encode('utf-8')+'\t'+ str(num_share)+'\t'+str(num_like)) +print(str(id) + '\t' + time.encode('utf-8') + '\t' + date.encode('utf-8') + '\t' + year.encode('utf-8') + '\t' + str( + num_share) + '\t' + str(num_like)) diff --git a/get_youtube_view.py b/get_youtube_view.py index 0cebdc3af01..a947cb12a09 100644 --- a/get_youtube_view.py +++ b/get_youtube_view.py @@ -6,29 +6,30 @@ # browser you're using. import time -#Changed the method of opening the browser. -#Selenium allows for the page to be refreshed. + +# Changed the method of opening the browser. +# Selenium allows for the page to be refreshed. from selenium import webdriver -#adding ability to change number of repeats +# adding ability to change number of repeats count = int(input("Number of times to be repeated: ")) -#Same as before +# Same as before url = input("Enter the URL : ") -print( "Length of video:") +print("Length of video:") minutes = int(input("Minutes ")) -seconds = int(input("Seconds ")) +seconds = int(input("Seconds ")) -#Calculating the refreshrate from the user input +# Calculating the refreshrate from the user input refreshrate = minutes * 60 + seconds -#Selecting Safari as the browser +# Selecting Safari as the browser driver = webdriver.Safari() if url.startswith("https://"): - driver.get(url) + driver.get(url) else: - driver.get("https://"+url) + driver.get("https://" + url) for i in range(count): - #Sets the page to refresh at the refreshrate. + # Sets the page to refresh at the refreshrate. time.sleep(refreshrate) driver.refresh() diff --git a/google.py b/google.py index 09ff33ac98f..bded088f653 100755 --- a/google.py +++ b/google.py @@ -7,28 +7,31 @@ Version: 1.0 """ -import webbrowser -import sys -import pyperclip -import requests +import sys +import webbrowser + import bs4 +import pyperclip +import requests + def main(): - if len(sys.argv) > 1: - keyword = ' '.join(sys.argv[1:]) - else: - # if no keyword is entered, the script would search for the keyword - # copied in the clipboard - keyword = pyperclip.paste() - - res=requests.get('http://google.com/search?q='+ keyword) - res.raise_for_status() - soup = bs4.BeautifulSoup(res.text) - linkElems = soup.select('.r a') - numOpen = min(5, len(linkElems)) - - for i in range(numOpen): - webbrowser.open('http://google.com' + linkElems[i].get('href')) + if len(sys.argv) > 1: + keyword = ' '.join(sys.argv[1:]) + else: + # if no keyword is entered, the script would search for the keyword + # copied in the clipboard + keyword = pyperclip.paste() + + res = requests.get('http://google.com/search?q=' + keyword) + res.raise_for_status() + soup = bs4.BeautifulSoup(res.text) + linkElems = soup.select('.r a') + numOpen = min(5, len(linkElems)) + + for i in range(numOpen): + webbrowser.open('http://google.com' + linkElems[i].get('href')) + if __name__ == '__main__': - main() + main() diff --git a/insta_monitering/insta_api.py b/insta_monitering/insta_api.py index e35a5aed748..3f3b2885537 100644 --- a/insta_monitering/insta_api.py +++ b/insta_monitering/insta_api.py @@ -1,9 +1,9 @@ +from concurrent.futures import ThreadPoolExecutor + +import tornado.ioloop import tornado.web from tornado.concurrent import run_on_executor -from concurrent.futures import ThreadPoolExecutor from tornado.gen import coroutine -import tornado.ioloop - # import file try: @@ -23,19 +23,19 @@ def background_task(self, user, tags, type, productId): try: instasubprocess(user=user, tags=tags, type=type, productId=productId) except: - print("error::background_task>>",sys.exc_info()[1]) + print("error::background_task>>", sys.exc_info()[1]) @coroutine def get(self): try: - q=self.get_argument("q") + q = self.get_argument("q") user = self.get_argument("userId") type = self.get_argument("type") productId = self.get_argument("productId") except: self.send_error(400) if " " in q: - q = q.replace(" ","") + q = q.replace(" ", "") self.background_task(user=user, tags=q, type=type, productId=productId) temp = {} temp["query"] = q @@ -49,7 +49,7 @@ def get(self): class StopHandlerinsta(tornado.web.RequestHandler): def get(self): try: - q=self.get_argument("q") + q = self.get_argument("q") user = self.get_argument("userId") # tags = self.get_argument("hashtags") productId = self.get_argument("productId") @@ -65,10 +65,11 @@ def get(self): print("{0}, {1}, {2}, {3}".format(temp["userId"], temp["productId"], temp["query"], temp["status"])) self.write(ujson.dumps(temp)) + class StatusHandlerinsta(tornado.web.RequestHandler): def get(self): try: - q=self.get_argument("q") + q = self.get_argument("q") user = self.get_argument("userId") productId = self.get_argument("productId") # tags = self.get_argument("hashtags") @@ -84,6 +85,7 @@ def get(self): print("{0}, {1}, {2}, {3}".format(temp["userId"], temp["productId"], temp["query"], temp["status"])) self.write(ujson.dumps(temp)) + # class SenderHandlerinsta(tornado.web.RequestHandler): # def get(self): # try: @@ -113,6 +115,7 @@ def get(self): # print("{0}, {1}, {2}, {3}".format(temp["userId"], temp["productId"], temp["query"], temp["status"])) self.write(data) + class SenderHandlerinstaGreater(tornado.web.RequestHandler): def get(self): try: @@ -135,7 +138,7 @@ def get(self): (r"/instagram/monitoring/stop", StopHandlerinsta), (r"/instagram/monitoring/status", StatusHandlerinsta), (r"/instagram/monitoring/less", SenderHandlerinstaLess), - (r"/instagram/monitoring/greater", SenderHandlerinstaGreater),]) + (r"/instagram/monitoring/greater", SenderHandlerinstaGreater), ]) application.listen(7074) print("server running") diff --git a/insta_monitering/insta_datafetcher.py b/insta_monitering/insta_datafetcher.py index e2d6a8fcede..d131d410ec4 100644 --- a/insta_monitering/insta_datafetcher.py +++ b/insta_monitering/insta_datafetcher.py @@ -1,20 +1,21 @@ # only god knows whats happening in the code # if I forget the code structure # please pray to god for help -import socket -import socks -import requests -import urllib3 +import asyncio +import multiprocessing +import os import random +import re +import socket import sys +import time + +import bs4 import pymongo +import requests +import socks import ujson -import bs4 -import re -import asyncio -import time -import multiprocessing -import os +import urllib3 try: import instagram_monitering.con_file as config @@ -25,7 +26,7 @@ class PorxyApplyingDecorator(object): def __init__(self): - filename = os.getcwd()+"/"+"ipList.txt" + filename = os.getcwd() + "/" + "ipList.txt" with open(filename, "r") as f: ipdata = f.read() self._IP = random.choice(ipdata.split(",")) @@ -35,14 +36,16 @@ def __call__(self, function_to_call_for_appling_proxy): # default_socket = socket.socket socks.set_default_proxy(socks.SOCKS5, SOCKS5_PROXY_HOST, - config.SOCKS5_PROXY_PORT , - True , - config.auth , + config.SOCKS5_PROXY_PORT, + True, + config.auth, config.passcode) socket.socket = socks.socksocket + def wrapper_function(url): # this is used for applyting socks5 proxy over the request return function_to_call_for_appling_proxy(url) + socks.set_default_proxy() return wrapper_function @@ -56,7 +59,7 @@ async def dataprocess(htmldata): if "window._sharedData =" in datatext: break datajson = re.findall("{(.*)}", datatext) - datajson = '{'+datajson[0]+'}' + datajson = '{' + datajson[0] + '}' datadict = ujson.loads(datajson) maindict = {} datadict = datadict["entry_data"]["PostPage"][0]["graphql"]["shortcode_media"] @@ -68,6 +71,7 @@ async def dataprocess(htmldata): pass return maindict + async def datapullpost(future, url): while True: @PorxyApplyingDecorator() @@ -82,6 +86,7 @@ async def request_pull(url): data = None finally: return data + data = await request_pull(url) if data != None: break @@ -89,18 +94,19 @@ async def request_pull(url): # here processing of data has to occur future.set_result(data) + class MoniteringClass(): def __init__(self, user, tags, type, productId): try: self.mon = pymongo.MongoClient(host=config.host, port=config.mongoPort) - db = self.mon[productId+":"+user+":insta"] + db = self.mon[productId + ":" + user + ":insta"] self._collection = db[tags] if type == "hashtags": - self._url = "https://www.instagram.com/explore/tags/"+tags+"/?__a=1" + self._url = "https://www.instagram.com/explore/tags/" + tags + "/?__a=1" if type == "profile": - self._url = "https://www.instagram.com/"+tags+"/?__a=1" + self._url = "https://www.instagram.com/" + tags + "/?__a=1" except: print("error::MointeringClass.__init__>>", sys.exc_info()[1]) @@ -117,7 +123,7 @@ def _dataProcessing(self, data): futures = [] for i in media_post: tempdict = {} - tempdict["url"] = "https://www.instagram.com/p/"+i["code"]+"/" + tempdict["url"] = "https://www.instagram.com/p/" + i["code"] + "/" tempdict["code"] = i["code"] userdata.append(tempdict) for i in top_post: @@ -141,17 +147,16 @@ def _dataProcessing(self, data): print("top post::", len(top_post)) return userdata, media_post, top_post - def _insertFunction(self, record): try: - records = self._collection.find({"id":record["id"]}) + records = self._collection.find({"id": record["id"]}) if records.count() == 0: # record["timestamp"] = time.time() self._collection.insert(record) except: print("error::Monitering.insertFunction>>", sys.exc_info()[1]) - def _lastProcess(self,userdata, media_post, top_post): + def _lastProcess(self, userdata, media_post, top_post): mainlist = [] try: for i in userdata: @@ -161,7 +166,7 @@ def _lastProcess(self,userdata, media_post, top_post): tofind = ["owner", "location"] for z in tofind: try: - tempdict[z+"data"] = i["data"][z] + tempdict[z + "data"] = i["data"][z] except: pass mainlist.append(tempdict) @@ -172,7 +177,7 @@ def _lastProcess(self,userdata, media_post, top_post): tofind = ["owner", "location"] for z in tofind: try: - tempdict[z+"data"] = i["data"][z] + tempdict[z + "data"] = i["data"][z] except: pass mainlist.append(tempdict) @@ -195,12 +200,13 @@ def reqest_pull(url): data = None finally: return data + data = reqest_pull(self._url) if data != None: break datadict = ujson.loads(data) userdata, media_post, top_post = self._dataProcessing(datadict) - finallydata = (self._lastProcess(userdata = userdata, media_post= media_post, top_post=top_post)) + finallydata = (self._lastProcess(userdata=userdata, media_post=media_post, top_post=top_post)) # print(ujson.dumps(finallydata)) except: print("error::Monitering.request_data_from_instagram>>", sys.exc_info()[1]) @@ -217,7 +223,6 @@ def hashtags(user, tags, type, productId): print("error::hashtags>>", sys.exc_info()[1]) - class theradPorcess(multiprocessing.Process): def __init__(self, user, tags, type, productId): @@ -232,13 +237,11 @@ def __init__(self, user, tags, type, productId): def run(self): try: - hashtags(user=self.user, tags=self.tags, type = self.type, productId=self.productId) + hashtags(user=self.user, tags=self.tags, type=self.type, productId=self.productId) except: print("error::run>>", sys.exc_info()[1]) - - class InstaPorcessClass(): def _dbProcessReader(self, user, tags, productId): @@ -301,7 +304,7 @@ def deletProcess(self, user, tags, productId): temp = {} temp["user"] = user temp["tags"] = tags - temp["productId"] =productId + temp["productId"] = productId collection.delete_one(temp) except: print("error::deletProcess:>>", sys.exc_info()[1]) @@ -309,6 +312,7 @@ def deletProcess(self, user, tags, productId): mon.close() print("deleted - task", temp) return True + def statusCheck(self, user, tags, productId): mon = pymongo.MongoClient(host=config.host, port=config.mongoPort) try: @@ -329,12 +333,13 @@ def statusCheck(self, user, tags, productId): mon.close() return result + class DBDataFetcher(): def __init__(self, user, tags, type, productId): try: self.mon = pymongo.MongoClient(host=config.host, port=config.mongoPort) - db = self.mon[productId+":"+user+":insta"] + db = self.mon[productId + ":" + user + ":insta"] self._collection = db[tags] except: print("error::DBDataFetcher.init>>", sys.exc_info()[1]) @@ -342,7 +347,7 @@ def __init__(self, user, tags, type, productId): def dbFetcher(self, limit=20): mainlist = [] try: - records = self._collection.find().sort("id",-1).limit(limit) + records = self._collection.find().sort("id", -1).limit(limit) for i in records: del i["_id"] mainlist.append(i) @@ -360,7 +365,7 @@ def DBFetcherGreater(self, limit, date): raise Exception limit = int(limit) date = int(date) - if date!=0: + if date != 0: doc = self._collection.find({"date": {"$gt": date}}).sort("date", pymongo.ASCENDING).limit(limit) else: doc = self._collection.find().sort("date", pymongo.ASCENDING).limit(limit) @@ -413,4 +418,4 @@ def main(): if __name__ == '__main__': - main() \ No newline at end of file + main() diff --git a/insta_monitering/subpinsta.py b/insta_monitering/subpinsta.py index 997851f18fc..d4e20529803 100644 --- a/insta_monitering/subpinsta.py +++ b/insta_monitering/subpinsta.py @@ -1,17 +1,19 @@ # trggering the process +import os import subprocess -import sys, os +import sys def instasubprocess(user, tags, type, productId): try: child_env = sys.executable - file_pocessing = os.getcwd()+"/insta_datafetcher.py "+user+" "+tags+" "+type+" "+productId - command = child_env+" "+file_pocessing - result = subprocess.Popen(command, shell=True) + file_pocessing = os.getcwd() + "/insta_datafetcher.py " + user + " " + tags + " " + type + " " + productId + command = child_env + " " + file_pocessing + result = subprocess.Popen(command, shell=True) result.wait() except: - print("error::instasubprocess>>",sys.exc_info()[1]) + print("error::instasubprocess>>", sys.exc_info()[1]) + if __name__ == '__main__': - instasubprocess(user="u2", tags="food", type="hashtags", productId="abc") \ No newline at end of file + instasubprocess(user="u2", tags="food", type="hashtags", productId="abc") diff --git a/internet_connection_py3.py b/internet_connection_py3.py index 90ca98f14b5..bad7f3d852e 100644 --- a/internet_connection_py3.py +++ b/internet_connection_py3.py @@ -1,26 +1,28 @@ from __future__ import print_function -import urllib.request + import os +import urllib.request + from selenium import webdriver -from selenium.webdriver.common.keys import Keys + print("Testing Internet Connection") print() try: - urllib.request.urlopen("http://google.com", timeout=2)#Tests if connection is up and running + urllib.request.urlopen("http://google.com", timeout=2) # Tests if connection is up and running print("Internet is working fine!") print() question = input("Do you want to open a website? (Y/N): ") if question == 'Y': - print() - search = input("Input website to open (http://website.com) : ") + print() + search = input("Input website to open (http://website.com) : ") else: - os._exit(0) + os._exit(0) except urllib.error.URLError: - print ("No internet connection!")#Output if no connection + print("No internet connection!") # Output if no connection browser = webdriver.Firefox() browser.get(search) -os.system('cls')#os.system('clear') if Linux -print("[+] Website "+search + " opened!") +os.system('cls') # os.system('clear') if Linux +print("[+] Website " + search + " opened!") browser.close() diff --git a/jee_result.py b/jee_result.py index 367c5613391..db29c4d0d01 100644 --- a/jee_result.py +++ b/jee_result.py @@ -1,7 +1,8 @@ -from bs4 import BeautifulSoup import datetime + import mechanize -import urllib2 +from bs4 import BeautifulSoup + # Create a Browser b = mechanize.Browser() @@ -20,30 +21,30 @@ # Fill it out b['regno'] = '37000304' -currentdate = datetime.date(1997,3,10) -enddate = datetime.date(1998,4,1) +currentdate = datetime.date(1997, 3, 10) +enddate = datetime.date(1998, 4, 1) while currentdate <= enddate: - ct=0 - #print currentdate - yyyymmdd = currentdate.strftime("%Y/%m/%d") - ddmmyyyy = yyyymmdd[8:] + "/" + yyyymmdd[5:7] + "/" +yyyymmdd[:4] - print(ddmmyyyy) - b.open('http://cbseresults.nic.in/jee/jee_2015.htm') - b.select_form(nr=0) - b['regno'] = '37000304' - b['dob'] = ddmmyyyy - - fd = b.submit() - #print(fd.read()) - soup = BeautifulSoup(fd.read(),'html.parser') - - for writ in soup.find_all('table'): - ct = ct + 1; - #print (ct) - if ct == 6: - print("---fail---") - else: - print("--true--") - break; - currentdate += datetime.timedelta(days=1) - #print fd.read() + ct = 0 + # print currentdate + yyyymmdd = currentdate.strftime("%Y/%m/%d") + ddmmyyyy = yyyymmdd[8:] + "/" + yyyymmdd[5:7] + "/" + yyyymmdd[:4] + print(ddmmyyyy) + b.open('http://cbseresults.nic.in/jee/jee_2015.htm') + b.select_form(nr=0) + b['regno'] = '37000304' + b['dob'] = ddmmyyyy + + fd = b.submit() + # print(fd.read()) + soup = BeautifulSoup(fd.read(), 'html.parser') + + for writ in soup.find_all('table'): + ct = ct + 1; + # print (ct) + if ct == 6: + print("---fail---") + else: + print("--true--") + break; + currentdate += datetime.timedelta(days=1) + # print fd.read() diff --git a/kmp_str_search.py b/kmp_str_search.py index 5327770e897..e32536ec40b 100644 --- a/kmp_str_search.py +++ b/kmp_str_search.py @@ -7,6 +7,8 @@ 2) Step through the text one character at a time and compare it to a charac$ updating our location within the pattern if necessary """ + + def kmp(pattern, text, len_p=None, len_t=None): # 1) Construct the failure array failure = [0] @@ -37,7 +39,6 @@ def kmp(pattern, text, len_p=None, len_t=None): if __name__ == '__main__': - # Test 1) pattern = "abc1abc12" text1 = "alskfjaldsabc1abc1abc12k23adsfabcabc" diff --git a/linear-algebra-python/src/lib.py b/linear-algebra-python/src/lib.py index 94bb16d57d6..5edbff23a87 100644 --- a/linear-algebra-python/src/lib.py +++ b/linear-algebra-python/src/lib.py @@ -20,7 +20,6 @@ - function randomMatrix(W,H,a,b) """ - import math import random @@ -45,13 +44,15 @@ class Vector(object): changeComponent(pos,value) : changes the specified component. TODO: compare-operator """ - def __init__(self,components): + + def __init__(self, components): """ input: components or nothing simple constructor for init the vector """ self.__components = components - def set(self,components): + + def set(self, components): """ input: new components changes the components of the vector. @@ -61,6 +62,7 @@ def set(self,components): self.__components = components else: raise Exception("please give any vector") + def __str__(self): """ returns a string representation of the vector @@ -68,14 +70,15 @@ def __str__(self): ans = "(" length = len(self.__components) for i in range(length): - if i != length-1: + if i != length - 1: ans += str(self.__components[i]) + "," else: ans += str(self.__components[i]) + ")" if len(ans) == 1: ans += ")" return ans - def component(self,i): + + def component(self, i): """ input: index (start at 0) output: the i-th component of the vector. @@ -84,20 +87,23 @@ def component(self,i): return self.__components[i] else: raise Exception("index out of range") + def size(self): """ returns the size of the vector """ return len(self.__components) + def eulidLength(self): """ returns the eulidean length of the vector """ summe = 0 for c in self.__components: - summe += c**2 + summe += c ** 2 return math.sqrt(summe) - def __add__(self,other): + + def __add__(self, other): """ input: other vector assumes: other vector has the same size @@ -111,7 +117,8 @@ def __add__(self,other): else: raise Exception("must have the same size") return Vector(result) - def __sub__(self,other): + + def __sub__(self, other): """ input: other vector assumes: other vector has the same size @@ -122,42 +129,46 @@ def __sub__(self,other): if size == other.size(): for i in range(size): result.append(self.__components[i] - other.component(i)) - else: # error case + else: # error case raise Exception("must have the same size") return Vector(result) - def __mul__(self,other): + + def __mul__(self, other): """ mul implements the scalar multiplication and the dot-product """ ans = [] - if isinstance(other,float) or isinstance(other,int): + if isinstance(other, float) or isinstance(other, int): for c in self.__components: - ans.append(c*other) - elif (isinstance(other,Vector) and (self.size() == other.size())): + ans.append(c * other) + elif (isinstance(other, Vector) and (self.size() == other.size())): size = self.size() summe = 0 for i in range(size): summe += self.__components[i] * other.component(i) return summe - else: # error case + else: # error case raise Exception("invalide operand!") return Vector(ans) + def copy(self): """ copies this vector and returns it. """ components = [x for x in self.__components] return Vector(components) - def changeComponent(self,pos,value): + + def changeComponent(self, pos, value): """ input: an index (pos) and a value changes the specified component (pos) with the 'value' """ - #precondition + # precondition assert (pos >= 0 and pos < len(self.__components)) self.__components[pos] = value + def norm(self): """ normalizes this vector and returns it. @@ -167,10 +178,11 @@ def norm(self): for i in range(len(self.__components)): self.__components[i] = self.__components[i] * quotient return self - def __eq__(self,other): + + def __eq__(self, other): """ returns true if the vectors are equal otherwise false. - """ + """ ans = True SIZE = self.size() if (SIZE == other.size()): @@ -181,26 +193,27 @@ def __eq__(self,other): else: ans = False return ans - + + def zeroVector(dimension): """ returns a zero-vector of size 'dimension' - """ - #precondition - assert(isinstance(dimension,int)) + """ + # precondition + assert (isinstance(dimension, int)) ans = [] for i in range(dimension): ans.append(0) return Vector(ans) -def unitBasisVector(dimension,pos): +def unitBasisVector(dimension, pos): """ returns a unit basis vector with a One at index 'pos' (indexing at 0) """ - #precondition - assert(isinstance(dimension,int) and (isinstance(pos,int))) + # precondition + assert (isinstance(dimension, int) and (isinstance(pos, int))) ans = [] for i in range(dimension): if i != pos: @@ -208,21 +221,21 @@ def unitBasisVector(dimension,pos): else: ans.append(1) return Vector(ans) - -def axpy(scalar,x,y): + +def axpy(scalar, x, y): """ input: a 'scalar' and two vectors 'x' and 'y' output: a vector computes the axpy operation """ # precondition - assert(isinstance(x,Vector) and (isinstance(y,Vector)) \ - and (isinstance(scalar,int) or isinstance(scalar,float))) - return (x*scalar + y) - + assert (isinstance(x, Vector) and (isinstance(y, Vector)) \ + and (isinstance(scalar, int) or isinstance(scalar, float))) + return (x * scalar + y) -def randomVector(N,a,b): + +def randomVector(N, a, b): """ input: size (N) of the vector. random range (a,b) @@ -232,7 +245,7 @@ def randomVector(N,a,b): ans = zeroVector(N) random.seed(None) for i in range(N): - ans.changeComponent(i,random.randint(a,b)) + ans.changeComponent(i, random.randint(a, b)) return ans @@ -253,7 +266,8 @@ class Matrix(object): operator + : implements the matrix-addition. operator - _ implements the matrix-subtraction """ - def __init__(self,matrix,w,h): + + def __init__(self, matrix, w, h): """ simple constructor for initialzes the matrix with components. @@ -261,6 +275,7 @@ def __init__(self,matrix,w,h): self.__matrix = matrix self.__width = w self.__height = h + def __str__(self): """ returns a string representation of this @@ -270,64 +285,70 @@ def __str__(self): for i in range(self.__height): ans += "|" for j in range(self.__width): - if j < self.__width -1: + if j < self.__width - 1: ans += str(self.__matrix[i][j]) + "," else: ans += str(self.__matrix[i][j]) + "|\n" return ans - def changeComponent(self,x,y, value): + + def changeComponent(self, x, y, value): """ changes the x-y component of this matrix """ if x >= 0 and x < self.__height and y >= 0 and y < self.__width: self.__matrix[x][y] = value else: - raise Exception ("changeComponent: indices out of bounds") - def component(self,x,y): + raise Exception("changeComponent: indices out of bounds") + + def component(self, x, y): """ returns the specified (x,y) component """ if x >= 0 and x < self.__height and y >= 0 and y < self.__width: return self.__matrix[x][y] else: - raise Exception ("changeComponent: indices out of bounds") + raise Exception("changeComponent: indices out of bounds") + def width(self): """ getter for the width """ return self.__width + def height(self): """ getter for the height """ return self.__height - def __mul__(self,other): + + def __mul__(self, other): """ implements the matrix-vector multiplication. implements the matrix-scalar multiplication """ - if isinstance(other, Vector): # vector-matrix + if isinstance(other, Vector): # vector-matrix if (other.size() == self.__width): ans = zeroVector(self.__height) for i in range(self.__height): summe = 0 for j in range(self.__width): summe += other.component(j) * self.__matrix[i][j] - ans.changeComponent(i,summe) + ans.changeComponent(i, summe) summe = 0 return ans else: raise Exception("vector must have the same size as the " - + "number of columns of the matrix!") - elif isinstance(other,int) or isinstance(other,float): # matrix-scalar + + "number of columns of the matrix!") + elif isinstance(other, int) or isinstance(other, float): # matrix-scalar matrix = [] for i in range(self.__height): row = [] for j in range(self.__width): row.append(self.__matrix[i][j] * other) matrix.append(row) - return Matrix(matrix,self.__width,self.__height) - def __add__(self,other): + return Matrix(matrix, self.__width, self.__height) + + def __add__(self, other): """ implements the matrix-addition. """ @@ -336,12 +357,13 @@ def __add__(self,other): for i in range(self.__height): row = [] for j in range(self.__width): - row.append(self.__matrix[i][j] + other.component(i,j)) + row.append(self.__matrix[i][j] + other.component(i, j)) matrix.append(row) - return Matrix(matrix,self.__width,self.__height) + return Matrix(matrix, self.__width, self.__height) else: raise Exception("matrix must have the same dimension!") - def __sub__(self,other): + + def __sub__(self, other): """ implements the matrix-subtraction. """ @@ -350,12 +372,13 @@ def __sub__(self,other): for i in range(self.__height): row = [] for j in range(self.__width): - row.append(self.__matrix[i][j] - other.component(i,j)) + row.append(self.__matrix[i][j] - other.component(i, j)) matrix.append(row) - return Matrix(matrix,self.__width,self.__height) + return Matrix(matrix, self.__width, self.__height) else: raise Exception("matrix must have the same dimension!") - def __eq__(self,other): + + def __eq__(self, other): """ returns true if the matrices are equal otherwise false. """ @@ -363,14 +386,13 @@ def __eq__(self,other): if self.__width == other.width() and self.__height == other.height(): for i in range(self.__height): for j in range(self.__width): - if self.__matrix[i][j] != other.component(i,j): + if self.__matrix[i][j] != other.component(i, j): ans = False break else: ans = False return ans - - + def squareZeroMatrix(N): """ @@ -382,10 +404,10 @@ def squareZeroMatrix(N): for j in range(N): row.append(0) ans.append(row) - return Matrix(ans,N,N) - - -def randomMatrix(W,H,a,b): + return Matrix(ans, N, N) + + +def randomMatrix(W, H, a, b): """ returns a random matrix WxH with integer components between 'a' and 'b' @@ -395,8 +417,6 @@ def randomMatrix(W,H,a,b): for i in range(H): row = [] for j in range(W): - row.append(random.randint(a,b)) + row.append(random.randint(a, b)) matrix.append(row) - return Matrix(matrix,W,H) - - \ No newline at end of file + return Matrix(matrix, W, H) diff --git a/linear-algebra-python/src/tests.py b/linear-algebra-python/src/tests.py index b26ce7f9cdd..07fc9cc7fa0 100644 --- a/linear-algebra-python/src/tests.py +++ b/linear-algebra-python/src/tests.py @@ -8,141 +8,164 @@ This file contains the test-suite for the linear algebra library. """ -import unittest import math +import unittest + from lib import * + class Test(unittest.TestCase): def test_component(self): """ test for method component """ - x = Vector([1,2,3]) - self.assertEqual(x.component(0),1) - self.assertEqual(x.component(2),3) + x = Vector([1, 2, 3]) + self.assertEqual(x.component(0), 1) + self.assertEqual(x.component(2), 3) try: y = Vector() self.assertTrue(False) except: self.assertTrue(True) + def test_str(self): """ test for toString() method """ - x = Vector([0,0,0,0,0,1]) - self.assertEqual(x.__str__(),"(0,0,0,0,0,1)") + x = Vector([0, 0, 0, 0, 0, 1]) + self.assertEqual(x.__str__(), "(0,0,0,0,0,1)") + def test_size(self): """ test for size()-method """ - x = Vector([1,2,3,4]) - self.assertEqual(x.size(),4) + x = Vector([1, 2, 3, 4]) + self.assertEqual(x.size(), 4) + def test_euclidLength(self): """ test for the eulidean length """ - x = Vector([1,2]) - self.assertAlmostEqual(x.eulidLength(),2.236,3) + x = Vector([1, 2]) + self.assertAlmostEqual(x.eulidLength(), 2.236, 3) + def test_add(self): """ test for + operator """ - x = Vector([1,2,3]) - y = Vector([1,1,1]) - self.assertEqual((x+y).component(0),2) - self.assertEqual((x+y).component(1),3) - self.assertEqual((x+y).component(2),4) + x = Vector([1, 2, 3]) + y = Vector([1, 1, 1]) + self.assertEqual((x + y).component(0), 2) + self.assertEqual((x + y).component(1), 3) + self.assertEqual((x + y).component(2), 4) + def test_sub(self): """ test for - operator """ - x = Vector([1,2,3]) - y = Vector([1,1,1]) - self.assertEqual((x-y).component(0),0) - self.assertEqual((x-y).component(1),1) - self.assertEqual((x-y).component(2),2) + x = Vector([1, 2, 3]) + y = Vector([1, 1, 1]) + self.assertEqual((x - y).component(0), 0) + self.assertEqual((x - y).component(1), 1) + self.assertEqual((x - y).component(2), 2) + def test_mul(self): """ test for * operator """ - x = Vector([1,2,3]) - a = Vector([2,-1,4]) # for test of dot-product - b = Vector([1,-2,-1]) - self.assertEqual((x*3.0).__str__(),"(3.0,6.0,9.0)") - self.assertEqual((a*b),0) + x = Vector([1, 2, 3]) + a = Vector([2, -1, 4]) # for test of dot-product + b = Vector([1, -2, -1]) + self.assertEqual((x * 3.0).__str__(), "(3.0,6.0,9.0)") + self.assertEqual((a * b), 0) + def test_zeroVector(self): """ test for the global function zeroVector(...) """ self.assertTrue(zeroVector(10).__str__().count("0") == 10) + def test_unitBasisVector(self): """ test for the global function unitBasisVector(...) """ - self.assertEqual(unitBasisVector(3,1).__str__(),"(0,1,0)") + self.assertEqual(unitBasisVector(3, 1).__str__(), "(0,1,0)") + def test_axpy(self): """ test for the global function axpy(...) (operation) """ - x = Vector([1,2,3]) - y = Vector([1,0,1]) - self.assertEqual(axpy(2,x,y).__str__(),"(3,4,7)") + x = Vector([1, 2, 3]) + y = Vector([1, 0, 1]) + self.assertEqual(axpy(2, x, y).__str__(), "(3,4,7)") + def test_copy(self): """ test for the copy()-method """ - x = Vector([1,0,0,0,0,0]) + x = Vector([1, 0, 0, 0, 0, 0]) y = x.copy() - self.assertEqual(x.__str__(),y.__str__()) + self.assertEqual(x.__str__(), y.__str__()) + def test_changeComponent(self): """ test for the changeComponent(...)-method """ - x = Vector([1,0,0]) - x.changeComponent(0,0) - x.changeComponent(1,1) - self.assertEqual(x.__str__(),"(0,1,0)") + x = Vector([1, 0, 0]) + x.changeComponent(0, 0) + x.changeComponent(1, 1) + self.assertEqual(x.__str__(), "(0,1,0)") + def test_str_matrix(self): - A = Matrix([[1,2,3],[2,4,5],[6,7,8]],3,3) - self.assertEqual("|1,2,3|\n|2,4,5|\n|6,7,8|\n",A.__str__()) + A = Matrix([[1, 2, 3], [2, 4, 5], [6, 7, 8]], 3, 3) + self.assertEqual("|1,2,3|\n|2,4,5|\n|6,7,8|\n", A.__str__()) + def test__mul__matrix(self): - A = Matrix([[1,2,3],[4,5,6],[7,8,9]],3,3) - x = Vector([1,2,3]) - self.assertEqual("(14,32,50)",(A*x).__str__()) - self.assertEqual("|2,4,6|\n|8,10,12|\n|14,16,18|\n",(A*2).__str__()) + A = Matrix([[1, 2, 3], [4, 5, 6], [7, 8, 9]], 3, 3) + x = Vector([1, 2, 3]) + self.assertEqual("(14,32,50)", (A * x).__str__()) + self.assertEqual("|2,4,6|\n|8,10,12|\n|14,16,18|\n", (A * 2).__str__()) + def test_changeComponent_matrix(self): - A = Matrix([[1,2,3],[2,4,5],[6,7,8]],3,3) - A.changeComponent(0,2,5) - self.assertEqual("|1,2,5|\n|2,4,5|\n|6,7,8|\n",A.__str__()) + A = Matrix([[1, 2, 3], [2, 4, 5], [6, 7, 8]], 3, 3) + A.changeComponent(0, 2, 5) + self.assertEqual("|1,2,5|\n|2,4,5|\n|6,7,8|\n", A.__str__()) + def test_component_matrix(self): - A = Matrix([[1,2,3],[2,4,5],[6,7,8]],3,3) - self.assertEqual(7,A.component(2,1),0.01) + A = Matrix([[1, 2, 3], [2, 4, 5], [6, 7, 8]], 3, 3) + self.assertEqual(7, A.component(2, 1), 0.01) + def test__add__matrix(self): - A = Matrix([[1,2,3],[2,4,5],[6,7,8]],3,3) - B = Matrix([[1,2,7],[2,4,5],[6,7,10]],3,3) - self.assertEqual("|2,4,10|\n|4,8,10|\n|12,14,18|\n",(A+B).__str__()) + A = Matrix([[1, 2, 3], [2, 4, 5], [6, 7, 8]], 3, 3) + B = Matrix([[1, 2, 7], [2, 4, 5], [6, 7, 10]], 3, 3) + self.assertEqual("|2,4,10|\n|4,8,10|\n|12,14,18|\n", (A + B).__str__()) + def test__sub__matrix(self): - A = Matrix([[1,2,3],[2,4,5],[6,7,8]],3,3) - B = Matrix([[1,2,7],[2,4,5],[6,7,10]],3,3) - self.assertEqual("|0,0,-4|\n|0,0,0|\n|0,0,-2|\n",(A-B).__str__()) + A = Matrix([[1, 2, 3], [2, 4, 5], [6, 7, 8]], 3, 3) + B = Matrix([[1, 2, 7], [2, 4, 5], [6, 7, 10]], 3, 3) + self.assertEqual("|0,0,-4|\n|0,0,0|\n|0,0,-2|\n", (A - B).__str__()) + def test_squareZeroMatrix(self): - self.assertEqual('|0,0,0,0,0|\n|0,0,0,0,0|\n|0,0,0,0,0|\n|0,0,0,0,0|' - +'\n|0,0,0,0,0|\n',squareZeroMatrix(5).__str__()) + self.assertEqual('|0,0,0,0,0|\n|0,0,0,0,0|\n|0,0,0,0,0|\n|0,0,0,0,0|' + + '\n|0,0,0,0,0|\n', squareZeroMatrix(5).__str__()) + def test_norm_vector(self): - x = Vector([1,2,3]) - self.assertAlmostEqual(x.norm().component(0),(1/math.sqrt(14)),0.001) - self.assertAlmostEqual(x.norm().component(1),math.sqrt((2.0/7)),0.001) + x = Vector([1, 2, 3]) + self.assertAlmostEqual(x.norm().component(0), (1 / math.sqrt(14)), 0.001) + self.assertAlmostEqual(x.norm().component(1), math.sqrt((2.0 / 7)), 0.001) + def test__eq__vector(self): - x = Vector([1,2,3]) - y = Vector([1,0,1]) + x = Vector([1, 2, 3]) + y = Vector([1, 0, 1]) self.assertTrue(x == x) self.assertFalse(x == y) + def test__eq__matrix(self): - A = Matrix([[1,2,3],[2,4,5],[6,7,8]],3,3) - B = Matrix([[1,2,7],[2,4,5],[6,7,10]],3,3) + A = Matrix([[1, 2, 3], [2, 4, 5], [6, 7, 8]], 3, 3) + B = Matrix([[1, 2, 7], [2, 4, 5], [6, 7, 10]], 3, 3) self.assertTrue(A == A) self.assertFalse(A == B) - - + + if __name__ == "__main__": - unittest.main() \ No newline at end of file + unittest.main() diff --git a/live_sketch.py b/live_sketch.py index 24e446046e5..663971d154c 100644 --- a/live_sketch.py +++ b/live_sketch.py @@ -1,14 +1,14 @@ import cv2 -import numpy as np -def sketch(image): +def sketch(image): img_gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY) - img_gray_blur = cv2.GaussianBlur(img_gray, (5,5), 0) + img_gray_blur = cv2.GaussianBlur(img_gray, (5, 5), 0) canny_edges = cv2.Canny(img_gray_blur, 10, 70) ret, mask = cv2.threshold(canny_edges, 70, 255, cv2.THRESH_BINARY_INV) return mask + cap = cv2.VideoCapture(0) while True: diff --git a/logs.py b/logs.py index 2fdf209e9c8..e770185bbc5 100644 --- a/logs.py +++ b/logs.py @@ -9,15 +9,16 @@ # # Description : This script will search for all *.log files in the given directory, zip them using the program you specify and then date stamp them -import os # Load the Library Module -from time import strftime # Load just the strftime Module from Time +import os # Load the Library Module +from time import strftime # Load just the strftime Module from Time -logsdir = "c:\puttylogs" # Set the Variable logsdir -zip_program = "zip.exe" # Set the Variable zip_program - 1.1 +logsdir = "c:\puttylogs" # Set the Variable logsdir +zip_program = "zip.exe" # Set the Variable zip_program - 1.1 -for files in os.listdir(logsdir): # Find all the files in the directory - if files.endswith(".log"): # Check to ensure the files in the directory end in .log - files1 = files + "." + strftime("%Y-%m-%d") + ".zip" # Create the Variable files1, this is the files in the directory, then we add a suffix with the date and the zip extension - os.chdir(logsdir) # Change directory to the logsdir - os.system(zip_program + " " + files1 +" "+ files) # Zip the logs into dated zip files for each server. - 1.1 - os.remove(files) # Remove the original log files +for files in os.listdir(logsdir): # Find all the files in the directory + if files.endswith(".log"): # Check to ensure the files in the directory end in .log + files1 = files + "." + strftime( + "%Y-%m-%d") + ".zip" # Create the Variable files1, this is the files in the directory, then we add a suffix with the date and the zip extension + os.chdir(logsdir) # Change directory to the logsdir + os.system(zip_program + " " + files1 + " " + files) # Zip the logs into dated zip files for each server. - 1.1 + os.remove(files) # Remove the original log files diff --git a/magic8ball.py b/magic8ball.py index d38b6fc0850..11e6757cd26 100644 --- a/magic8ball.py +++ b/magic8ball.py @@ -12,8 +12,9 @@ Ask a question, and know the future. ''' -from time import sleep from random import randint +from time import sleep + from colorama import Fore, Style # response list.. @@ -39,18 +40,23 @@ "Outlook not so good", "Very doubtful"] + # core game... def game(): ques = str(input("What is your question? \n").lower()) - print ("thinking...") + print("thinking...") sleep(1) - idx = randint(0,20) - if idx <10: color = Fore.GREEN - elif idx>=10 and idx<15: color = Fore.YELLOW - else: color = Fore.RED - print (color+response[idx]+Style.RESET_ALL+'\n\n') + idx = randint(0, 20) + if idx < 10: + color = Fore.GREEN + elif idx >= 10 and idx < 15: + color = Fore.YELLOW + else: + color = Fore.RED + print(color + response[idx] + Style.RESET_ALL + '\n\n') playloop() + # looping func... def playloop(): ques_again = str(input("Would you like to ask another question? (y/n)\n").lower()) @@ -61,8 +67,9 @@ def playloop(): print("Auf Wiedersehen!") else: - print ("What was that?/n") + print("What was that?/n") playloop() -if __name__=='__main__': + +if __name__ == '__main__': game() diff --git a/meme_maker.py b/meme_maker.py index c3cedd8eecd..f7a622847dd 100644 --- a/meme_maker.py +++ b/meme_maker.py @@ -22,20 +22,20 @@ def main(): print(image_file.size) text, size, color_value = input_par() - - #Font path is given as -->( " Path to your desired font " ) + + # Font path is given as -->( " Path to your desired font " ) font = ImageFont.truetype("C:\\Windows\\Fonts\\Arial.ttf", size=size) - #If the color of the text is not equal to white,then change the background to be white - if((color_value[0] and color_value[1] and color_value[2])!=255): + # If the color of the text is not equal to white,then change the background to be white + if ((color_value[0] and color_value[1] and color_value[2]) != 255): for y in range(100): for x in range(100): pixdata[x, y] = (255, 255, 255, 255) - #If the text color is white then the background is said to be black + # If the text color is white then the background is said to be black else: for y in range(100): for x in range(100): - pixdata[x, y] = (0,0, 0, 255) + pixdata[x, y] = (0, 0, 0, 255) image_file.show() # Drawing text on the picture diff --git a/merge.py b/merge.py index 753deb512b2..a2557b0a80e 100644 --- a/merge.py +++ b/merge.py @@ -1,14 +1,15 @@ from __future__ import print_function -# author:zhangshuyx@gmail.com - -#!/usr/bin/env python -# -*- coding=utf-8 -*- import os +# author:zhangshuyx@gmail.com +# !/usr/bin/env python +# -*- coding=utf-8 -*- + # define the result filename resultfile = 'result.csv' + # the merge func def merge(): """merge csv files to one file""" @@ -17,19 +18,20 @@ def merge(): global resultfile # use list save the csv files - csvfiles = [f for f in os.listdir('.') if f != resultfile \ - and (len(f.split('.')) >= 2) and f.split('.')[1]=='csv'] + csvfiles = [f for f in os.listdir('.') if f != resultfile \ + and (len(f.split('.')) >= 2) and f.split('.')[1] == 'csv'] # open file to write - with open(resultfile,'w') as writefile: + with open(resultfile, 'w') as writefile: for csvfile in csvfiles: with open(csvfile) as readfile: print('File {} readed.'.format(csvfile)) - + # do the read and write - writefile.write(readfile.read()+'\n') + writefile.write(readfile.read() + '\n') print('\nFile {} wrote.'.format(resultfile)) + # the main program def main(): @@ -37,5 +39,6 @@ def main(): print("This program merges csv-files to one file\n") merge() + if __name__ == '__main__': main() diff --git a/move_files_over_x_days.py b/move_files_over_x_days.py index e7881040b2f..9cbb6b0567e 100644 --- a/move_files_over_x_days.py +++ b/move_files_over_x_days.py @@ -6,34 +6,35 @@ # Modifications : Added possibility to use command line arguments to specify source, destination, and days. # Description : This will move all the files from the src directory that are over 240 days old to the destination directory. +import argparse +import os import shutil -import sys import time -import os -import argparse usage = 'python move_files_over_x_days.py -src [SRC] -dst [DST] -days [DAYS]' description = 'Move files from src to dst if they are older than a certain number of days. Default is 240 days' args_parser = argparse.ArgumentParser(usage=usage, description=description) -args_parser.add_argument('-src', '--src', type=str, nargs='?', default='.', help='(OPTIONAL) Directory where files will be moved from. Defaults to current directory') -args_parser.add_argument('-dst', '--dst', type=str, nargs='?', required=True, help='(REQUIRED) Directory where files will be moved to.') -args_parser.add_argument('-days', '--days', type=int, nargs='?', default=240, help='(OPTIONAL) Days value specifies the minimum age of files to be moved. Default is 240.') +args_parser.add_argument('-src', '--src', type=str, nargs='?', default='.', + help='(OPTIONAL) Directory where files will be moved from. Defaults to current directory') +args_parser.add_argument('-dst', '--dst', type=str, nargs='?', required=True, + help='(REQUIRED) Directory where files will be moved to.') +args_parser.add_argument('-days', '--days', type=int, nargs='?', default=240, + help='(OPTIONAL) Days value specifies the minimum age of files to be moved. Default is 240.') args = args_parser.parse_args() if args.days < 0: - args.days = 0 + args.days = 0 src = args.src # Set the source directory dst = args.dst # Set the destination directory -days = args.days #Set the number of days +days = args.days # Set the number of days now = time.time() # Get the current time if not os.path.exists(dst): - os.mkdir(dst) + os.mkdir(dst) for f in os.listdir(src): # Loop through all the files in the source directory if os.stat(f).st_mtime < now - days * 86400: # Work out how old they are, if they are older than 240 days old if os.path.isfile(f): # Check it's a file shutil.move(f, dst) # Move the files - diff --git a/movie_details.py b/movie_details.py index 400ec2cdfe6..b88daf458d6 100644 --- a/movie_details.py +++ b/movie_details.py @@ -1,5 +1,6 @@ -import mechanize import urllib.request + +import mechanize from bs4 import BeautifulSoup # Create a Browser @@ -9,12 +10,12 @@ browser.set_handle_robots(False) browser.addheaders = [('User-agent', - 'Mozilla/4.0 (compatible; MSIE 5.0; Windows 98;)')] + 'Mozilla/4.0 (compatible; MSIE 5.0; Windows 98;)')] movie_title = input("Enter movie title: ") movie_types = ('feature', 'tv_movie', 'tv_series', 'tv_episode', 'tv_special', - 'tv_miniseries', 'documentary', 'video_game', 'short', 'video', 'tv_short') + 'tv_miniseries', 'documentary', 'video_game', 'short', 'video', 'tv_short') # Navigate browser.open('http://www.imdb.com/search/title') @@ -26,20 +27,19 @@ # Check all the boxes of movie types for m_type in movie_types: - browser.find_control(type='checkbox',nr=0).get(m_type).selected = True + browser.find_control(type='checkbox', nr=0).get(m_type).selected = True # Submit -fd = browser.submit() -soup = BeautifulSoup(fd.read(),'html5lib') - +fd = browser.submit() +soup = BeautifulSoup(fd.read(), 'html5lib') # Updated from td tag to h3 tag for div in soup.findAll('h3', {'class': 'lister-item-header'}, limit=1): a = div.findAll('a')[0] hht = 'http://www.imdb.com' + a.attrs['href'] print(hht) - page = urllib.request.urlopen(hht) - soup2 = BeautifulSoup(page.read(),'html.parser') + page = urllib.request.urlopen(hht) + soup2 = BeautifulSoup(page.read(), 'html.parser') find = soup2.find print("Title: " + find(itemprop='name').get_text().strip()) diff --git a/multiplication_table.py b/multiplication_table.py index 593f184c3c4..0f4ed16373c 100644 --- a/multiplication_table.py +++ b/multiplication_table.py @@ -1,18 +1,20 @@ -from sys import argv # import argment variable +from sys import argv # import argment variable -script, rows, columns = argv # define rows and columns for the table and assign them to the argument variable +script, rows, columns = argv # define rows and columns for the table and assign them to the argument variable def table(rows, columns): - for i in range(1, int(rows) + 1 ): # it's safe to assume that the user would mean 12 rows when they provide 12 as an argument, b'coz 12 will produce 11 rows - print ("\t", i,) + for i in range(1, int( + rows) + 1): # it's safe to assume that the user would mean 12 rows when they provide 12 as an argument, b'coz 12 will produce 11 rows + print("\t", i, ) + + print("\n\n") # add 3 lines + + for i in range(1, int(columns) + 1): + print(i), + for j in range(1, int(rows) + 1): + print("\t", i * j, ) + print("\n\n") # add 3 lines - print ("\n\n") # add 3 lines - for i in range(1, int(columns) + 1 ): - print (i), - for j in range(1, int(rows) + 1 ): - print ("\t",i*j,) - print ("\n\n") # add 3 lines - table(rows, columns) diff --git a/nDigitNumberCombinations.py b/nDigitNumberCombinations.py index 866dfcf3ebb..e34752f1bb3 100644 --- a/nDigitNumberCombinations.py +++ b/nDigitNumberCombinations.py @@ -1,15 +1,15 @@ # ALL the combinations of n digit combo def nDigitCombinations(n): - try: - npow = 10**n - numbers=[] - for code in range(npow): - code=str(code).zfill(n) - numbers.append(code) - except: - # handle all other exceptions - pass - return(numbers) + try: + npow = 10 ** n + numbers = [] + for code in range(npow): + code = str(code).zfill(n) + numbers.append(code) + except: + # handle all other exceptions + pass + return (numbers) # An alternate solution: # from itertools import product diff --git a/new_script.py b/new_script.py index a2d46d3a6f8..3541a8cea97 100644 --- a/new_script.py +++ b/new_script.py @@ -1,18 +1,17 @@ -from __future__ import print_function +from __future__ import print_function + +import datetime # Load the library module +import os # Load the library module +import sys # Load the library module + # Script Name : new_script.py # Author : Craig Richards # Created : 20th November 2012 # Last Modified : # Version : 1.0 - # Modifications : - # Description : This will create a new basic template for a new script -import os # Load the library module -import sys # Load the library module -import datetime # Load the library module - text = '''You need to pass an argument for the new script you want to create, followed by the script name. You can use -python : Python Script -bash : Bash Script @@ -20,41 +19,41 @@ -sql : SQL Script''' if len(sys.argv) < 3: - print(text) - sys.exit() + print(text) + sys.exit() if '-h' in sys.argv or '--h' in sys.argv or '-help' in sys.argv or '--help' in sys.argv: - print(text) - sys.exit() -else: - if '-python' in sys.argv[1]: - config_file = "python.cfg" - extension = ".py" - elif '-bash' in sys.argv[1]: - config_file = "bash.cfg" - extension = ".bash" - elif '-ksh' in sys.argv[1]: - config_file = "ksh.cfg" - extension = ".ksh" - elif '-sql' in sys.argv[1]: - config_file = "sql.cfg" - extension = ".sql" - else: - print('Unknown option - ' + text) + print(text) sys.exit() +else: + if '-python' in sys.argv[1]: + config_file = "python.cfg" + extension = ".py" + elif '-bash' in sys.argv[1]: + config_file = "bash.cfg" + extension = ".bash" + elif '-ksh' in sys.argv[1]: + config_file = "ksh.cfg" + extension = ".ksh" + elif '-sql' in sys.argv[1]: + config_file = "sql.cfg" + extension = ".sql" + else: + print('Unknown option - ' + text) + sys.exit() confdir = os.getenv("my_config") scripts = os.getenv("scripts") dev_dir = "Development" newfile = sys.argv[2] output_file = (newfile + extension) -outputdir = os.path.join(scripts,dev_dir) +outputdir = os.path.join(scripts, dev_dir) script = os.path.join(outputdir, output_file) -input_file = os.path.join(confdir,config_file) +input_file = os.path.join(confdir, config_file) old_text = " Script Name : " new_text = (" Script Name : " + output_file) -if not(os.path.exists(outputdir)): - os.mkdir(outputdir) +if not (os.path.exists(outputdir)): + os.mkdir(outputdir) newscript = open(script, 'w') input = open(input_file, 'r') today = datetime.date.today() @@ -62,6 +61,6 @@ new_date = (" Created : " + today.strftime("%d %B %Y")) for line in input: - line = line.replace(old_text, new_text) - line = line.replace(old_date, new_date) - newscript.write(line) + line = line.replace(old_text, new_text) + line = line.replace(old_date, new_date) + newscript.write(line) diff --git a/news_intent_schema.json b/news_intent_schema.json index 527c707bb7a..19ca075c7d3 100644 --- a/news_intent_schema.json +++ b/news_intent_schema.json @@ -1,51 +1,51 @@ { - "interactionModel": { - "languageModel": { - "invocationName": "reddit news", - "intents": [ - { - "name": "AMAZON.CancelIntent", - "samples": [] - }, - { - "name": "AMAZON.HelpIntent", - "samples": [] - }, - { - "name": "AMAZON.StopIntent", - "samples": [] - }, - { - "name": "AMAZON.NavigateHomeIntent", - "samples": [] - }, - { - "name": "YesIntent", - "slots": [], - "samples": [ - "start", - "sure", - "yes" - ] - }, - { - "name": "NooIntent", - "slots": [], - "samples": [ - "go away", - "no" - ] - }, - { - "name": "AMAZON.FallbackIntent", - "samples": [] - }, - { - "name": "AMAZON.NoIntent", - "samples": [] - } - ], - "types": [] + "interactionModel": { + "languageModel": { + "invocationName": "reddit news", + "intents": [ + { + "name": "AMAZON.CancelIntent", + "samples": [] + }, + { + "name": "AMAZON.HelpIntent", + "samples": [] + }, + { + "name": "AMAZON.StopIntent", + "samples": [] + }, + { + "name": "AMAZON.NavigateHomeIntent", + "samples": [] + }, + { + "name": "YesIntent", + "slots": [], + "samples": [ + "start", + "sure", + "yes" + ] + }, + { + "name": "NooIntent", + "slots": [], + "samples": [ + "go away", + "no" + ] + }, + { + "name": "AMAZON.FallbackIntent", + "samples": [] + }, + { + "name": "AMAZON.NoIntent", + "samples": [] } + ], + "types": [] } + } } diff --git a/nmap_scan.py b/nmap_scan.py index f39d4a4ced9..d7f6214d8f9 100644 --- a/nmap_scan.py +++ b/nmap_scan.py @@ -1,40 +1,41 @@ -from __future__ import print_function +from __future__ import print_function + +import optparse # Import the module + +import nmap # Import the module + + # Script Name : nmap_scan.py # Author : Craig Richards # Created : 24th May 2013 # Last Modified : # Version : 1.0 - # Modifications : - # Description : This scans my scripts directory and gives a count of the different types of scripts, you need nmap installed to run this -import nmap # Import the module -import optparse # Import the module - -def nmapScan(tgtHost, tgtPort): # Create the function, this fucntion does the scanning - nmScan = nmap.PortScanner() - nmScan.scan(tgtHost, tgtPort) - state = nmScan[tgtHost]['tcp'][int(tgtPort)]['state'] - print("[*] " + tgtHost + " tcp/" + tgtPort + " " + state) +def nmapScan(tgtHost, tgtPort): # Create the function, this fucntion does the scanning + nmScan = nmap.PortScanner() + nmScan.scan(tgtHost, tgtPort) + state = nmScan[tgtHost]['tcp'][int(tgtPort)]['state'] + print("[*] " + tgtHost + " tcp/" + tgtPort + " " + state) -def main(): # Main Program - parser = optparse.OptionParser('usage%prog ' + '-H -p ') # Display options/help if required - parser.add_option('-H', dest='tgtHost', type='string', help='specify host') - parser.add_option('-p', dest='tgtPort', type='string', help='port') - (options, args) = parser.parse_args() - tgtHost = options.tgtHost - tgtPorts = str(options.tgtPort).split(',') +def main(): # Main Program + parser = optparse.OptionParser('usage%prog ' + '-H -p ') # Display options/help if required + parser.add_option('-H', dest='tgtHost', type='string', help='specify host') + parser.add_option('-p', dest='tgtPort', type='string', help='port') + (options, args) = parser.parse_args() + tgtHost = options.tgtHost + tgtPorts = str(options.tgtPort).split(',') - if (tgtHost == None) | (tgtPorts[0] == None): - print(parser.usage) - exit(0) + if (tgtHost == None) | (tgtPorts[0] == None): + print(parser.usage) + exit(0) - for tgtPort in tgtPorts: # Scan the hosts with the ports etc - nmapScan(tgtHost, tgtPort) + for tgtPort in tgtPorts: # Scan the hosts with the ports etc + nmapScan(tgtHost, tgtPort) if __name__ == '__main__': - main() + main() diff --git a/nodepad/notepad.py b/nodepad/notepad.py index 76b47d3a20a..a7e410dd79c 100644 --- a/nodepad/notepad.py +++ b/nodepad/notepad.py @@ -3,7 +3,6 @@ # GUI module generated by PAGE version 4.10 # In conjunction with Tcl version 8.6 # Jan 30, 2018 02:49:06 PM -import sys try: from Tkinter import * @@ -12,32 +11,39 @@ try: import ttk + py3 = 0 except ImportError: import tkinter.ttk as ttk + py3 = 1 import notepad_support + def vp_start_gui(): '''Starting point when module is the main routine.''' global val, w, root root = Tk() - root.resizable(False,False) - top = Notepads_managment (root) + root.resizable(False, False) + top = Notepads_managment(root) notepad_support.init(root, top) root.mainloop() + w = None + + def create_Notepads_managment(root, *args, **kwargs): '''Starting point when module is imported by another program.''' global w, w_win, rt rt = root - w = Toplevel (root) - top = Notepads_managment (w) + w = Toplevel(root) + top = Notepads_managment(w) notepad_support.init(w, top, *args, **kwargs) return (w, top) + def destroy_Notepads_managment(): global w w.destroy() @@ -50,46 +56,44 @@ def __init__(self, top=None): top is the toplevel containing window.''' _bgcolor = '#d9d9d9' # X11 color: 'gray85' _fgcolor = '#000000' # X11 color: 'black' - _compcolor = '#d9d9d9' # X11 color: 'gray85' - _ana1color = '#d9d9d9' # X11 color: 'gray85' - _ana2color = '#d9d9d9' # X11 color: 'gray85' + _compcolor = '#d9d9d9' # X11 color: 'gray85' + _ana1color = '#d9d9d9' # X11 color: 'gray85' + _ana2color = '#d9d9d9' # X11 color: 'gray85' self.style = ttk.Style() if sys.platform == "win32": self.style.theme_use('winnative') - self.style.configure('.',background=_bgcolor) - self.style.configure('.',foreground=_fgcolor) - self.style.configure('.',font="TkDefaultFont") - self.style.map('.',background= - [('selected', _compcolor), ('active',_ana2color)]) + self.style.configure('.', background=_bgcolor) + self.style.configure('.', foreground=_fgcolor) + self.style.configure('.', font="TkDefaultFont") + self.style.map('.', background= + [('selected', _compcolor), ('active', _ana2color)]) top.geometry("600x450") top.title("Notepads managment") top.configure(highlightcolor="black") - - self.style.configure('TNotebook.Tab', background=_bgcolor) self.style.configure('TNotebook.Tab', foreground=_fgcolor) self.style.map('TNotebook.Tab', background= - [('selected', _compcolor), ('active',_ana2color)]) + [('selected', _compcolor), ('active', _ana2color)]) self.TNotebook1 = ttk.Notebook(top) self.TNotebook1.place(relx=0.02, rely=0.02, relheight=0.85 - , relwidth=0.97) + , relwidth=0.97) self.TNotebook1.configure(width=582) self.TNotebook1.configure(takefocus="") self.TNotebook1_t0 = Frame(self.TNotebook1) self.TNotebook1.add(self.TNotebook1_t0, padding=3) - self.TNotebook1.tab(0, text="Add",compound="none",underline="-1",) + self.TNotebook1.tab(0, text="Add", compound="none", underline="-1", ) self.TNotebook1_t1 = Frame(self.TNotebook1) self.TNotebook1.add(self.TNotebook1_t1, padding=3) - self.TNotebook1.tab(1, text="Display",compound="none",underline="-1",) + self.TNotebook1.tab(1, text="Display", compound="none", underline="-1", ) self.TNotebook1_t2 = Frame(self.TNotebook1) self.TNotebook1.add(self.TNotebook1_t2, padding=3) - self.TNotebook1.tab(2, text="Create",compound="none",underline="-1",) + self.TNotebook1.tab(2, text="Create", compound="none", underline="-1", ) self.inputNotice = Text(self.TNotebook1_t0) self.inputNotice.place(relx=0.02, rely=0.28, relheight=0.64 - , relwidth=0.68) + , relwidth=0.68) self.inputNotice.configure(background="white") self.inputNotice.configure(font="TkTextFont") self.inputNotice.configure(selectbackground="#c4c4c4") @@ -97,7 +101,7 @@ def __init__(self, top=None): self.inputNotice.configure(wrap=WORD) self.inputTitle = Entry(self.TNotebook1_t0) - self.inputTitle.place(relx=0.09, rely=0.08,height=20, relwidth=0.6) + self.inputTitle.place(relx=0.09, rely=0.08, height=20, relwidth=0.6) self.inputTitle.configure(background="white") self.inputTitle.configure(font="TkFixedFont") self.inputTitle.configure(selectbackground="#c4c4c4") @@ -116,17 +120,17 @@ def __init__(self, top=None): self.Button2.place(relx=0.74, rely=0.28, height=26, width=50) self.Button2.configure(activebackground="#d9d9d9") self.Button2.configure(text='''Add''') - self.Button2.bind('',lambda e:notepad_support.add_button(e)) + self.Button2.bind('', lambda e: notepad_support.add_button(e)) self.Button3 = Button(self.TNotebook1_t0) self.Button3.place(relx=0.74, rely=0.39, height=26, width=56) self.Button3.configure(activebackground="#d9d9d9") self.Button3.configure(text='''Clear''') - self.Button3.bind('',lambda e:notepad_support.clear_button(e)) + self.Button3.bind('', lambda e: notepad_support.clear_button(e)) self.outputNotice = Text(self.TNotebook1_t1) self.outputNotice.place(relx=0.02, rely=0.19, relheight=0.76 - , relwidth=0.6) + , relwidth=0.6) self.outputNotice.configure(background="white") self.outputNotice.configure(font="TkTextFont") self.outputNotice.configure(selectbackground="#c4c4c4") @@ -135,7 +139,7 @@ def __init__(self, top=None): self.inputSearchTitle = Entry(self.TNotebook1_t1) self.inputSearchTitle.place(relx=0.09, rely=0.08, height=20 - , relwidth=0.51) + , relwidth=0.51) self.inputSearchTitle.configure(background="white") self.inputSearchTitle.configure(font="TkFixedFont") self.inputSearchTitle.configure(selectbackground="#c4c4c4") @@ -149,25 +153,25 @@ def __init__(self, top=None): self.Button4.place(relx=0.69, rely=0.33, height=26, width=54) self.Button4.configure(activebackground="#d9d9d9") self.Button4.configure(text='''Next''') - self.Button4.bind('',lambda e:notepad_support.next_button(e)) + self.Button4.bind('', lambda e: notepad_support.next_button(e)) self.Button5 = Button(self.TNotebook1_t1) self.Button5.place(relx=0.69, rely=0.44, height=26, width=55) self.Button5.configure(activebackground="#d9d9d9") self.Button5.configure(text='''Back''') - self.Button5.bind('',lambda e:notepad_support.back_button(e)) + self.Button5.bind('', lambda e: notepad_support.back_button(e)) self.Button7 = Button(self.TNotebook1_t1) self.Button7.place(relx=0.69, rely=0.22, height=26, width=68) self.Button7.configure(activebackground="#d9d9d9") self.Button7.configure(text='''Search''') - self.Button7.bind('',lambda e:notepad_support.search_button(e)) + self.Button7.bind('', lambda e: notepad_support.search_button(e)) self.Button8 = Button(self.TNotebook1_t1) self.Button8.place(relx=0.69, rely=0.56, height=26, width=64) self.Button8.configure(activebackground="#d9d9d9") self.Button8.configure(text='''Delete''') - self.Button8.bind('',lambda e:notepad_support.delete_button(e)) + self.Button8.bind('', lambda e: notepad_support.delete_button(e)) self.Label4 = Label(self.TNotebook1_t2) self.Label4.place(relx=0.09, rely=0.14, height=18, width=259) @@ -178,25 +182,18 @@ def __init__(self, top=None): self.Button6.place(relx=0.22, rely=0.25, height=26, width=69) self.Button6.configure(activebackground="#d9d9d9") self.Button6.configure(text='''Create''') - self.Button6.bind('',lambda e:notepad_support.create_button(e)) + self.Button6.bind('', lambda e: notepad_support.create_button(e)) self.Button1 = Button(top) self.Button1.place(relx=0.4, rely=0.91, height=26, width=117) self.Button1.configure(activebackground="#d9d9d9") self.Button1.configure(text='''Exit''') - self.Button1.bind('',lambda e:notepad_support.exit_button(e)) + self.Button1.bind('', lambda e: notepad_support.exit_button(e)) self.errorOutput = Label(top) self.errorOutput.place(relx=0.03, rely=0.91, height=18, width=206) self.errorOutput.configure(activebackground="#f9f9f9") - - - - if __name__ == '__main__': vp_start_gui() - - - diff --git a/nodepad/notepad_support.py b/nodepad/notepad_support.py index 4983ed3a97c..93f48a43568 100644 --- a/nodepad/notepad_support.py +++ b/nodepad/notepad_support.py @@ -5,7 +5,6 @@ # Jan 29, 2018 03:25:00 PM -import sys import sqlite3 try: @@ -15,9 +14,11 @@ try: import ttk + py3 = 0 except ImportError: import tkinter.ttk as ttk + py3 = 1 # connect with database 'data.db' @@ -32,6 +33,7 @@ index = 0 + def delete_button(p1): global index global results @@ -66,33 +68,34 @@ def create_button(p1): except: w.errorOutput.configure(text="The database already exists") + def add_button(p1): # for manipulating the data base global cursor global connection - if (len(w.inputTitle.get()) > 0 and len(w.inputNotice.get(1.0,END)) > 0): + if (len(w.inputTitle.get()) > 0 and len(w.inputNotice.get(1.0, END)) > 0): w.errorOutput.configure(text="") title = w.inputTitle.get() - note = w.inputNotice.get(1.0,END) + note = w.inputNotice.get(1.0, END) sql_command = """INSERT INTO notes (title,note) VALUES ("{0}","{1}"); """ - sql_command = sql_command.format(title,note) + sql_command = sql_command.format(title, note) cursor.execute(sql_command) connection.commit() else: w.errorOutput.configure(text="Please fill the fields. ") + def back_button(p1): global search global results global index - + w.errorOutput.configure(text="") index -= 1 if (index >= 0 and index < len(results)): - w.outputNotice.delete(1.0,END) - w.outputNotice.insert(1.0,results[index][2]) - - + w.outputNotice.delete(1.0, END) + w.outputNotice.insert(1.0, results[index][2]) + def clear_button(p1): """ @@ -101,6 +104,7 @@ def clear_button(p1): """ w.inputNotice.delete(1.0, END) + def exit_button(p1): """ function for the exit button. @@ -108,6 +112,7 @@ def exit_button(p1): """ sys.exit(0) + def search_button(p1): global cursor global results @@ -121,11 +126,10 @@ def search_button(p1): w.errorOutput.configure(text=str(len(results)) + " results") index = 0 if (index >= 0 and index < len(results)): - w.outputNotice.delete(1.0,END) - w.outputNotice.insert(1.0,results[index][2]) + w.outputNotice.delete(1.0, END) + w.outputNotice.insert(1.0, results[index][2]) except: - w.errorOutput.configure(text ="Please create at first a database.") - + w.errorOutput.configure(text="Please create at first a database.") def next_button(p1): @@ -134,26 +138,28 @@ def next_button(p1): index += 1 if (len(w.inputSearchTitle.get()) > 0): if (index >= 0 and index < len(results)): - w.outputNotice.delete(1.0,END) - w.outputNotice.insert(1.0,results[index][2]) - + w.outputNotice.delete(1.0, END) + w.outputNotice.insert(1.0, results[index][2]) + else: w.errorOutput.configure(text="Please fill the search field. ") + def init(top, gui, *args, **kwargs): global w, top_level, root w = gui top_level = top root = top + def destroy_window(): # Function which closes the window. global top_level top_level.destroy() top_level = None + if __name__ == '__main__': import notepad - notepad.vp_start_gui() - + notepad.vp_start_gui() diff --git a/nslookup_check.py b/nslookup_check.py index a7c39cb4e75..685c784d841 100644 --- a/nslookup_check.py +++ b/nslookup_check.py @@ -8,7 +8,7 @@ # Description : This very simple script opens the file server_list.txt and the does an nslookup for each one to check the DNS entry -import subprocess # Import the subprocess module +import subprocess # Import the subprocess module -for server in open('server_list.txt'): # Open the file and read each line - subprocess.Popen(('nslookup ' + server)) # Run the nslookup command for each server in the list +for server in open('server_list.txt'): # Open the file and read each line + subprocess.Popen(('nslookup ' + server)) # Run the nslookup command for each server in the list diff --git a/osinfo.py b/osinfo.py index 44633e7bccd..06af8a049c1 100644 --- a/osinfo.py +++ b/osinfo.py @@ -14,21 +14,21 @@ import platform as pl profile = [ - 'architecture', - 'linux_distribution', - 'mac_ver', - 'machine', - 'node', - 'platform', - 'processor', - 'python_build', - 'python_compiler', - 'python_version', - 'release', - 'system', - 'uname', - 'version', - ] + 'architecture', + 'linux_distribution', + 'mac_ver', + 'machine', + 'node', + 'platform', + 'processor', + 'python_build', + 'python_compiler', + 'python_version', + 'release', + 'system', + 'uname', + 'version', +] class bcolors: @@ -45,4 +45,3 @@ class bcolors: for key in profile: if hasattr(pl, key): print(key + bcolors.BOLD + ": " + str(getattr(pl, key)()) + bcolors.ENDC) - diff --git a/other_pepole/get_ip_gui b/other_pepole/get_ip_gui index 0866479de6a..5728697ac5b 100755 --- a/other_pepole/get_ip_gui +++ b/other_pepole/get_ip_gui @@ -1,68 +1,73 @@ #!/usr/bin/env python3 # -*- coding: utf-8 -*- -#**************** Modules Require *****************# -from tkinter import * import socket +# **************** Modules Require *****************# +from tkinter import * from urllib.request import urlopen -#**************** Get IP commands *****************# -#control buttons + +# **************** Get IP commands *****************# +# control buttons def get_wan_ip(): - try : - #get ip from http://ipecho.net/plain as text - wan_ip=urlopen('http://ipecho.net/plain').read().decode('utf-8') - res.configure(text='Wan IP is : '+wan_ip,fg='#600') - except : - res.configure(text='Problem in source : http://ipecho.net/plain',fg='red') -#get local ip + try: + # get ip from http://ipecho.net/plain as text + wan_ip = urlopen('http://ipecho.net/plain').read().decode('utf-8') + res.configure(text='Wan IP is : ' + wan_ip, fg='#600') + except: + res.configure(text='Problem in source : http://ipecho.net/plain', fg='red') + + +# get local ip def get_local_ip(): try: - lan_ip=(socket.gethostbyname(socket.gethostname())) - res.configure(text='Local IP is : '+lan_ip,fg='#600') + lan_ip = (socket.gethostbyname(socket.gethostname())) + res.configure(text='Local IP is : ' + lan_ip, fg='#600') except: - res.configure(text='Unkown Error',fg='#red') -#**************** about control button *****************# -#show about info and change the button command and place + res.configure(text='Unkown Error', fg='#red') + # **************** about control button *****************# + + +# show about info and change the button command and place def about(): - global close_app,frame,info + global close_app, frame, info about_app.destroy() - frame=Frame(root,width=350,height=2,bg='blue') - frame.grid(row=2,column=0,columnspan=4) - info=Label(root,text=""" + frame = Frame(root, width=350, height=2, bg='blue') + frame.grid(row=2, column=0, columnspan=4) + info = Label(root, text=""" Practice Python Take idea from here : https://github.com/geekcomputers/Python/blob/master/myip.py - """,fg='#02F') - info.grid(row=3,column=0,columnspan=4,padx=5) - close_app=Button(root,text='Close',command=close_about,bg='#55F') - close_app.grid(row=4,column=0,columnspan=4,pady=5) -#remove about info and remove close button then return about button in orignal place + """, fg='#02F') + info.grid(row=3, column=0, columnspan=4, padx=5) + close_app = Button(root, text='Close', command=close_about, bg='#55F') + close_app.grid(row=4, column=0, columnspan=4, pady=5) + + +# remove about info and remove close button then return about button in orignal place def close_about(): - global frame,about_app,info + global frame, about_app, info info.destroy() frame.destroy() close_app.destroy() - about_app=Button(root,text='about',command=about) - about_app.grid(row=1,column=2,padx=5,pady=5,sticky=W) + about_app = Button(root, text='about', command=about) + about_app.grid(row=1, column=2, padx=5, pady=5, sticky=W) -#**************** Tkinter GUI *****************# -root=Tk() -root.title ('Khaled programing practice') -#all buttons -res=Label(root,text='00.00.00.00',font=25) -res_wan_ip=Button(root,text='Get Wan IP',command=get_wan_ip) -res_local_ip=Button(root,text='Get Local IP',command=get_local_ip) -about_app=Button(root,text='about',command=about) -quit_app=Button(root,text='quit',command=quit,bg='#f40') -#method grid to install the button in window -res.grid(row=0,column=0,columnspan=4,sticky=N,padx=10,pady=5) -res_wan_ip.grid(row=1,column=0,padx=5,pady=5,sticky=W) -res_local_ip.grid(row=1,column=1,padx=5,pady=5,sticky=W) -about_app.grid(row=1,column=2,padx=5,pady=5,sticky=W) -quit_app.grid(row=1,column=3,padx=5,pady=5,sticky=E) -#run GUI/app -root.mainloop() - - +# **************** Tkinter GUI *****************# +root = Tk() +root.title('Khaled programing practice') +# all buttons +res = Label(root, text='00.00.00.00', font=25) +res_wan_ip = Button(root, text='Get Wan IP', command=get_wan_ip) +res_local_ip = Button(root, text='Get Local IP', command=get_local_ip) +about_app = Button(root, text='about', command=about) +quit_app = Button(root, text='quit', command=quit, bg='#f40') +# method grid to install the button in window +res.grid(row=0, column=0, columnspan=4, sticky=N, padx=10, pady=5) +res_wan_ip.grid(row=1, column=0, padx=5, pady=5, sticky=W) +res_local_ip.grid(row=1, column=1, padx=5, pady=5, sticky=W) +about_app.grid(row=1, column=2, padx=5, pady=5, sticky=W) +quit_app.grid(row=1, column=3, padx=5, pady=5, sticky=E) +# run GUI/app +root.mainloop() diff --git a/pan.py b/pan.py index 08ba69a2373..8bc494b9c17 100644 --- a/pan.py +++ b/pan.py @@ -1,193 +1,185 @@ -import pandas as pd import numpy as np +import pandas as pd from matplotlib import * -#.........................Series.......................# +# .........................Series.......................# -x1=np.array([1,2,3,4]) -s=pd.Series(x1,index=[1,2,3,4]) +x1 = np.array([1, 2, 3, 4]) +s = pd.Series(x1, index=[1, 2, 3, 4]) print(s) -#.......................DataFrame......................# +# .......................DataFrame......................# -x2=np.array([1,2,3,4,5,6]) -s=pd.DataFrame(x2) +x2 = np.array([1, 2, 3, 4, 5, 6]) +s = pd.DataFrame(x2) print(s) -x3=np.array([['Alex',10],['Nishit',21],['Aman',22]]) -s=pd.DataFrame(x3,columns=['Name','Age']) +x3 = np.array([['Alex', 10], ['Nishit', 21], ['Aman', 22]]) +s = pd.DataFrame(x3, columns=['Name', 'Age']) print(s) -data = {'Name':['Tom', 'Jack', 'Steve', 'Ricky'],'Age':[28,34,29,42]} -df = pd.DataFrame(data, index=['rank1','rank2','rank3','rank4']) -print (df) - -data=[{'a':1,'b':2},{'a':3,'b':4,'c':5}] -df=pd.DataFrame(data) +data = {'Name': ['Tom', 'Jack', 'Steve', 'Ricky'], 'Age': [28, 34, 29, 42]} +df = pd.DataFrame(data, index=['rank1', 'rank2', 'rank3', 'rank4']) print(df) +data = [{'a': 1, 'b': 2}, {'a': 3, 'b': 4, 'c': 5}] +df = pd.DataFrame(data) +print(df) -d = {'one' : pd.Series([1, 2, 3], index=['a', 'b', 'c']), - 'two' : pd.Series([1, 2, 3, 4], index=['a', 'b', 'c', 'd'])} +d = {'one': pd.Series([1, 2, 3], index=['a', 'b', 'c']), + 'two': pd.Series([1, 2, 3, 4], index=['a', 'b', 'c', 'd'])} df = pd.DataFrame(d) -print (df) +print(df) -#....Adding New column......# +# ....Adding New column......# -data={'one':pd.Series([1,2,3,4],index=[1,2,3,4]), - 'two':pd.Series([1,2,3],index=[1,2,3])} -df=pd.DataFrame(data) +data = {'one': pd.Series([1, 2, 3, 4], index=[1, 2, 3, 4]), + 'two': pd.Series([1, 2, 3], index=[1, 2, 3])} +df = pd.DataFrame(data) print(df) -df['three']=pd.Series([1,2],index=[1,2]) +df['three'] = pd.Series([1, 2], index=[1, 2]) print(df) -#......Deleting a column......# +# ......Deleting a column......# -data={'one':pd.Series([1,2,3,4],index=[1,2,3,4]), - 'two':pd.Series([1,2,3],index=[1,2,3]), - 'three':pd.Series([1,1],index=[1,2]) - } -df=pd.DataFrame(data) +data = {'one': pd.Series([1, 2, 3, 4], index=[1, 2, 3, 4]), + 'two': pd.Series([1, 2, 3], index=[1, 2, 3]), + 'three': pd.Series([1, 1], index=[1, 2]) + } +df = pd.DataFrame(data) print(df) del df['one'] print(df) df.pop('two') -print(df) +print(df) -#......Selecting a particular Row............# +# ......Selecting a particular Row............# -data={'one':pd.Series([1,2,3,4],index=[1,2,3,4]), - 'two':pd.Series([1,2,3],index=[1,2,3]), - 'three':pd.Series([1,1],index=[1,2]) - } -df=pd.DataFrame(data) +data = {'one': pd.Series([1, 2, 3, 4], index=[1, 2, 3, 4]), + 'two': pd.Series([1, 2, 3], index=[1, 2, 3]), + 'three': pd.Series([1, 1], index=[1, 2]) + } +df = pd.DataFrame(data) print(df.loc[2]) -print(df[1:4]) +print(df[1:4]) -#.........Addition of Row.................# +# .........Addition of Row.................# -df = pd.DataFrame([[1, 2], [3, 4]], columns = ['a','b']) -df2 = pd.DataFrame([[5, 6], [7, 8]], columns = ['a','b']) +df = pd.DataFrame([[1, 2], [3, 4]], columns=['a', 'b']) +df2 = pd.DataFrame([[5, 6], [7, 8]], columns=['a', 'b']) df = df.append(df2) -print (df.head()) - +print(df.head()) -#........Deleting a Row..................# +# ........Deleting a Row..................# -df = pd.DataFrame([[1, 2], [3, 4]], columns = ['a','b']) -df2 = pd.DataFrame([[5, 6], [7, 8]], columns = ['a','b']) +df = pd.DataFrame([[1, 2], [3, 4]], columns=['a', 'b']) +df2 = pd.DataFrame([[5, 6], [7, 8]], columns=['a', 'b']) df = df.append(df2) # Drop rows with label 0 df = df.drop(0) -print (df) - -#..........................Functions.....................................# +print(df) +# ..........................Functions.....................................# -d = {'Name':pd.Series(['Tom','James','Ricky','Vin','Steve','Smith','Jack']), - 'Age':pd.Series([25,26,25,23,30,29,23]), - 'Rating':pd.Series([4.23,3.24,3.98,2.56,3.20,4.6,3.8])} +d = {'Name': pd.Series(['Tom', 'James', 'Ricky', 'Vin', 'Steve', 'Smith', 'Jack']), + 'Age': pd.Series([25, 26, 25, 23, 30, 29, 23]), + 'Rating': pd.Series([4.23, 3.24, 3.98, 2.56, 3.20, 4.6, 3.8])} df = pd.DataFrame(d) -print ("The transpose of the data series is:") -print (df.T) +print("The transpose of the data series is:") +print(df.T) print(df.shape) print(df.size) print(df.values) -#.........................Statistics.......................................# +# .........................Statistics.......................................# -d = {'Name':pd.Series(['Tom','James','Ricky','Vin','Steve','Smith','Jack', - 'Lee','David','Gasper','Betina','Andres']), - 'Age':pd.Series([25,26,25,23,30,29,23,34,40,30,51,46]), - 'Rating':pd.Series([4.23,3.24,3.98,2.56,3.20,4.6,3.8,3.78,2.98,4.80,4.10,3.65]) -} +d = {'Name': pd.Series(['Tom', 'James', 'Ricky', 'Vin', 'Steve', 'Smith', 'Jack', + 'Lee', 'David', 'Gasper', 'Betina', 'Andres']), + 'Age': pd.Series([25, 26, 25, 23, 30, 29, 23, 34, 40, 30, 51, 46]), + 'Rating': pd.Series([4.23, 3.24, 3.98, 2.56, 3.20, 4.6, 3.8, 3.78, 2.98, 4.80, 4.10, 3.65]) + } df = pd.DataFrame(d) -print (df.sum()) - +print(df.sum()) -d = {'Name':pd.Series(['Tom','James','Ricky','Vin','Steve','Smith','Jack', - 'Lee','David','Gasper','Betina','Andres']), - 'Age':pd.Series([25,26,25,23,30,29,23,34,40,30,51,46]), - 'Rating':pd.Series([4.23,3.24,3.98,2.56,3.20,4.6,3.8,3.78,2.98,4.80,4.10,3.65]) -} +d = {'Name': pd.Series(['Tom', 'James', 'Ricky', 'Vin', 'Steve', 'Smith', 'Jack', + 'Lee', 'David', 'Gasper', 'Betina', 'Andres']), + 'Age': pd.Series([25, 26, 25, 23, 30, 29, 23, 34, 40, 30, 51, 46]), + 'Rating': pd.Series([4.23, 3.24, 3.98, 2.56, 3.20, 4.6, 3.8, 3.78, 2.98, 4.80, 4.10, 3.65]) + } df = pd.DataFrame(d) -print (df.describe(include='all')) +print(df.describe(include='all')) +# .......................Sorting..........................................# -#.......................Sorting..........................................# - -#Using the sort_index() method, by passing the axis arguments and the order of sorting, +# Using the sort_index() method, by passing the axis arguments and the order of sorting, # DataFrame can be sorted. By default, sorting is done on row labels in ascending order. -unsorted_df = pd.DataFrame(np.random.randn(10,2),index=[1,4,6,2,3,5,9,8,0,7],columns = ['col2','col1']) +unsorted_df = pd.DataFrame(np.random.randn(10, 2), index=[1, 4, 6, 2, 3, 5, 9, 8, 0, 7], columns=['col2', 'col1']) -sorted_df=unsorted_df.sort_index() -print (sorted_df) +sorted_df = unsorted_df.sort_index() +print(sorted_df) sorted_df = unsorted_df.sort_index(ascending=False) -print (sorted_df) +print(sorted_df) -#By passing the axis argument with a value 0 or 1, -#the sorting can be done on the column labels. By default, axis=0, sort by row. -#Let us consider the following example to understand the same. +# By passing the axis argument with a value 0 or 1, +# the sorting can be done on the column labels. By default, axis=0, sort by row. +# Let us consider the following example to understand the same. -unsorted_df = pd.DataFrame(np.random.randn(10,2),index=[1,4,6,2,3,5,9,8,0,7],columns = ['col2','col1']) -sorted_df=unsorted_df.sort_index(axis=1) +unsorted_df = pd.DataFrame(np.random.randn(10, 2), index=[1, 4, 6, 2, 3, 5, 9, 8, 0, 7], columns=['col2', 'col1']) +sorted_df = unsorted_df.sort_index(axis=1) print(sorted_df) -unsorted_df = pd.DataFrame({'col1':[2,1,1,1],'col2':[1,3,2,4]}) -sorted_df = unsorted_df.sort_values(by='col1',kind='mergesort') +unsorted_df = pd.DataFrame({'col1': [2, 1, 1, 1], 'col2': [1, 3, 2, 4]}) +sorted_df = unsorted_df.sort_values(by='col1', kind='mergesort') # print (sorted_df) -#...........................SLICING...............................# +# ...........................SLICING...............................# df = pd.DataFrame(np.random.randn(8, 4), -index = ['a','b','c','d','e','f','g','h'], columns = ['A', 'B', 'C', 'D']) + index=['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h'], columns=['A', 'B', 'C', 'D']) # Select all rows for multiple columns, say list[] -print (df.loc[:,['A','C']]) -print (df.loc[['a','b','f','h'],['A','C']]) - +print(df.loc[:, ['A', 'C']]) +print(df.loc[['a', 'b', 'f', 'h'], ['A', 'C']]) -df = pd.DataFrame(np.random.randn(8, 4), columns = ['A', 'B', 'C', 'D']) +df = pd.DataFrame(np.random.randn(8, 4), columns=['A', 'B', 'C', 'D']) # Index slicing -print(df.ix[:,'A']) +print(df.ix[:, 'A']) -#............................statistics......................# +# ............................statistics......................# -s = pd.Series([1,2,3,4,5,4]) +s = pd.Series([1, 2, 3, 4, 5, 4]) print(s.pct_change()) df = pd.DataFrame(np.random.randn(5, 2)) -print (df.pct_change()) +print(df.pct_change()) df = pd.DataFrame(np.random.randn(10, 4), - index = pd.date_range('1/1/2000', periods=10), - columns = ['A', 'B', 'C', 'D']) + index=pd.date_range('1/1/2000', periods=10), + columns=['A', 'B', 'C', 'D']) print(df.rolling(window=3).mean()) -print (df.expanding(min_periods=3).mean()) +print(df.expanding(min_periods=3).mean()) +# ........................MISSING DATA............................................# -#........................MISSING DATA............................................# - -df = pd.DataFrame(np.random.randn(3, 3), index=['a', 'c', 'e'],columns=['one', -'two', 'three']) +df = pd.DataFrame(np.random.randn(3, 3), index=['a', 'c', 'e'], columns=['one', + 'two', 'three']) df = df.reindex(['a', 'b', 'c']) print(df) -print ("NaN replaced with '0':") +print("NaN replaced with '0':") print(df.fillna(0)) - df = pd.DataFrame(np.random.randn(5, 3), index=['a', 'c', 'e', 'f', -'h'],columns=['one', 'two', 'three']) + 'h'], columns=['one', 'two', 'three']) df = df.reindex(['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h']) @@ -197,44 +189,26 @@ print(df.dropna()) print(df.dropna(axis=1)) - -#.........................Grouping...............................................# +# .........................Grouping...............................................# ipl_data = {'Team': ['Riders', 'Riders', 'Devils', 'Devils', 'Kings', - 'kings', 'Kings', 'Kings', 'Riders', 'Royals', 'Royals', 'Riders'], - 'Rank': [1, 2, 2, 3, 3,4 ,1 ,1,2 , 4,1,2], - 'Year': [2014,2015,2014,2015,2014,2015,2016,2017,2016,2014,2015,2017], - 'Points':[876,789,863,673,741,812,756,788,694,701,804,690]} + 'kings', 'Kings', 'Kings', 'Riders', 'Royals', 'Royals', 'Riders'], + 'Rank': [1, 2, 2, 3, 3, 4, 1, 1, 2, 4, 1, 2], + 'Year': [2014, 2015, 2014, 2015, 2014, 2015, 2016, 2017, 2016, 2014, 2015, 2017], + 'Points': [876, 789, 863, 673, 741, 812, 756, 788, 694, 701, 804, 690]} df = pd.DataFrame(ipl_data) grouped = df.groupby('Year') -for name,group in grouped: - print (name) - print (group) +for name, group in grouped: + print(name) + print(group) -print (grouped.get_group(2014)) +print(grouped.get_group(2014)) grouped = df.groupby('Team') -print (grouped['Points'].agg([np.sum, np.mean, np.std])) - +print(grouped['Points'].agg([np.sum, np.mean, np.std])) +# ...............................Reading a Csv File............................# -#...............................Reading a Csv File............................# - -data=pd.read_csv("dat.csv") +data = pd.read_csv("dat.csv") print(data) - - - - - - - - - - - - - - - diff --git a/passwordGen.py b/passwordGen.py index 20a4adecdf2..1c744185614 100644 --- a/passwordGen.py +++ b/passwordGen.py @@ -1,29 +1,29 @@ import random + lChars = 'abcdefghijklmnopqrstuvwxyz' uChars = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ' digits = '1234567890' specialChars = '!@#$%^&*-_+=' -passLen = 10 #actual generated password length will be this length + 1 +passLen = 10 # actual generated password length will be this length + 1 myPass = '' for i in range(passLen): - while(len(myPass)) <=2: + while (len(myPass)) <= 2: index = random.randrange(len(lChars)) - myPass = myPass+lChars[index] + myPass = myPass + lChars[index] myPassLen = len(myPass) - while(len(myPass)) <=5: + while (len(myPass)) <= 5: index = random.randrange(len(digits)) - myPass = myPass+digits[index] + myPass = myPass + digits[index] myPassLen = len(myPass) - while(len(myPass)) <=7: + while (len(myPass)) <= 7: index = random.randrange(len(specialChars)) - myPass = myPass+specialChars[index] + myPass = myPass + specialChars[index] myPassLen = len(myPass) - while(len(myPass)) <=10: + while (len(myPass)) <= 10: index = random.randrange(len(uChars)) - myPass = myPass+uChars[index] + myPass = myPass + uChars[index] myPassLen = len(myPass) - -print(myPass) +print(myPass) diff --git a/passwordGenerator.py b/passwordGenerator.py index 9bcaa037d9d..27f23346cba 100644 --- a/passwordGenerator.py +++ b/passwordGenerator.py @@ -1,17 +1,23 @@ -#PasswordGenerator GGearing314 01/10/19 +# PasswordGenerator GGearing314 01/10/19 from random import * -case=randint(1,2) -number=randint(1,99) -animals=("ant","alligator","baboon","badger","barb","bat","beagle","bear","beaver","bird","bison","bombay","bongo","booby","butterfly","bee","camel","cat","caterpillar","catfish","cheetah","chicken","chipmunk","cow","crab","deer","dingo","dodo","dog","dolphin","donkey","duck","eagle","earwig","elephant","emu","falcon","ferret","fish","flamingo","fly","fox","frog","gecko","gibbon","giraffe","goat","goose","gorilla") -colour=("red","orange","yellow","green","blue","indigo","violet","purple","magenta","cyan","pink","brown","white","grey","black") -chosenanimal= animals[randint(0,len(animals))] -chosencolour=colour[randint(0,len(colour))] -if case==1: - chosenanimal=chosenanimal.upper() - print(chosencolour,number,chosenanimal) + +case = randint(1, 2) +number = randint(1, 99) +animals = ( +"ant", "alligator", "baboon", "badger", "barb", "bat", "beagle", "bear", "beaver", "bird", "bison", "bombay", "bongo", +"booby", "butterfly", "bee", "camel", "cat", "caterpillar", "catfish", "cheetah", "chicken", "chipmunk", "cow", "crab", +"deer", "dingo", "dodo", "dog", "dolphin", "donkey", "duck", "eagle", "earwig", "elephant", "emu", "falcon", "ferret", +"fish", "flamingo", "fly", "fox", "frog", "gecko", "gibbon", "giraffe", "goat", "goose", "gorilla") +colour = ( +"red", "orange", "yellow", "green", "blue", "indigo", "violet", "purple", "magenta", "cyan", "pink", "brown", "white", +"grey", "black") +chosenanimal = animals[randint(0, len(animals))] +chosencolour = colour[randint(0, len(colour))] +if case == 1: + chosenanimal = chosenanimal.upper() + print(chosencolour, number, chosenanimal) else: - chosencolour=chosencolour.upper() - print(chosenanimal,number,chosencolour) -#print("This program has exatly ",(len(animals)*len(colour)*99*2),"different combinations") #I'm not sure this is right + chosencolour = chosencolour.upper() + print(chosenanimal, number, chosencolour) +# print("This program has exatly ",(len(animals)*len(colour)*99*2),"different combinations") #I'm not sure this is right input("Press enter to close...") - diff --git a/password_cracker.py b/password_cracker.py index 0e07b249463..0421353aaa9 100644 --- a/password_cracker.py +++ b/password_cracker.py @@ -1,48 +1,48 @@ from __future__ import print_function + +from sys import platform as _platform + # Script Name : password_cracker.py # Author : Craig Richards # Created : 20 May 2013 # Last Modified : # Version : 1.0 - # Modifications : - # Description : Old school password cracker using python -from sys import platform as _platform - # Check the current operating system to import the correct version of crypt -if _platform in ["linux", "linux2", "darwin"]: # darwin is _platform name for Mac OS X - import crypt # Import the module +if _platform in ["linux", "linux2", "darwin"]: # darwin is _platform name for Mac OS X + import crypt # Import the module elif _platform == "win32": # Windows try: - import fcrypt # Try importing the fcrypt module + import fcrypt # Try importing the fcrypt module except ImportError: - print('Please install fcrypt if you are on Windows') + print('Please install fcrypt if you are on Windows') -def testPass(cryptPass): # Start the function - salt = cryptPass[0:2] - dictFile = open('dictionary.txt','r') # Open the dictionary file - for word in dictFile.readlines(): # Scan through the file - word = word.strip('\n') - cryptWord = crypt.crypt(word, salt) # Check for password in the file - if (cryptWord == cryptPass): - print("[+] Found Password: "+word+"\n") - return - print("[-] Password Not Found.\n") - return +def testPass(cryptPass): # Start the function + salt = cryptPass[0:2] + dictFile = open('dictionary.txt', 'r') # Open the dictionary file + for word in dictFile.readlines(): # Scan through the file + word = word.strip('\n') + cryptWord = crypt.crypt(word, salt) # Check for password in the file + if (cryptWord == cryptPass): + print("[+] Found Password: " + word + "\n") + return + print("[-] Password Not Found.\n") + return def main(): - passFile = open('passwords.txt') # Open the password file - for line in passFile.readlines(): # Read through the file - if ":" in line: - user = line.split(':')[0] - cryptPass = line.split(':')[1].strip(' ') # Prepare the user name etc - print("[*] Cracking Password For: " + user) - testPass(cryptPass) # Call it to crack the users password + passFile = open('passwords.txt') # Open the password file + for line in passFile.readlines(): # Read through the file + if ":" in line: + user = line.split(':')[0] + cryptPass = line.split(':')[1].strip(' ') # Prepare the user name etc + print("[*] Cracking Password For: " + user) + testPass(cryptPass) # Call it to crack the users password + if __name__ == "__main__": - main() + main() diff --git a/ph_email.py b/ph_email.py index 50ed36f9d63..5f16050a5c6 100755 --- a/ph_email.py +++ b/ph_email.py @@ -1,18 +1,19 @@ #!/usr/bin/python3 # find phone numbers and email addresses -#./ph_email.py searches for phone numbers and emails in the latest clipboard -#entry and writes the matches into matches.txt +# ./ph_email.py searches for phone numbers and emails in the latest clipboard +# entry and writes the matches into matches.txt -import pyperclip import re -#Phone regex overview per line - #word boundary - #area code +91, 91, 0 - #optional space - #ten numbers - #word boundary +import pyperclip + +# Phone regex overview per line +# word boundary +# area code +91, 91, 0 +# optional space +# ten numbers +# word boundary find_phone = re.compile(r'''\b (\+?91|0)? @@ -21,8 +22,7 @@ \b ''', re.X) - -#email regex source : http://www.regexlib.com/REDetails.aspx?regexp_id=26 +# email regex source : http://www.regexlib.com/REDetails.aspx?regexp_id=26 find_email = re.compile(r'''( ([a-zA-Z0-9_\-\.]+) @ @@ -34,26 +34,26 @@ ) ''', re.X) -text = pyperclip.paste() #retrieve text from clipboard +text = pyperclip.paste() # retrieve text from clipboard -matches = [] #list to store numbers and emails +matches = [] # list to store numbers and emails - #ph[1] means second item of the group-wise tuple - #which is returned by findall function - #same applies to email +# ph[1] means second item of the group-wise tuple +# which is returned by findall function +# same applies to email for ph in find_phone.findall(text): - matches.append(ph[1]) + matches.append(ph[1]) for em in find_email.findall(text): - matches.append(em[0]) + matches.append(em[0]) -#display number of matches +# display number of matches print(f"{len(matches)} matches found") -#if matches are found add then to file +# if matches are found add then to file if len(matches): - with open('matches.txt', 'a') as file: - for match in matches: - file.write(match) - file.write('\n') \ No newline at end of file + with open('matches.txt', 'a') as file: + for match in matches: + file.write(match) + file.write('\n') diff --git a/ping_servers.py b/ping_servers.py index f1485c28fcf..d8e27fe40f4 100644 --- a/ping_servers.py +++ b/ping_servers.py @@ -1,20 +1,19 @@ from __future__ import print_function + +import os # Load the Library Module +import subprocess # Load the Library Module +import sys # Load the Library Module + # Script Name : ping_servers.py # Author : Craig Richards # Created : 9th May 2012 # Last Modified : 14th May 2012 # Version : 1.1 - # Modifications : 1.1 - 14th May 2012 - CR Changed it to use the config directory to store the server files - # Description : This script will, depending on the arguments supplied will ping the servers associated with that application group. -import os # Load the Library Module -import subprocess # Load the Library Module -import sys # Load the Library Module - -filename = sys.argv[0] # Sets a variable for the script name -if '-h' in sys.argv or '--h' in sys.argv or '-help' in sys.argv or '--help' in sys.argv: # Help Menu if called +filename = sys.argv[0] # Sets a variable for the script name +if '-h' in sys.argv or '--h' in sys.argv or '-help' in sys.argv or '--help' in sys.argv: # Help Menu if called print(''' You need to supply the application group for the servers you want to ping, i.e. dms @@ -26,40 +25,43 @@ sys.exit(0) else: - if (len(sys.argv) < 3): # If no arguments are passed,display the help/instructions on how to run the script - sys.exit ('\nYou need to supply the app group. Usage : ' + filename + ' followed by the application group i.e. \n \t dms or \n \t swaps \n then the site i.e. \n \t 155 or \n \t bromley') + if (len(sys.argv) < 3): # If no arguments are passed,display the help/instructions on how to run the script + sys.exit( + '\nYou need to supply the app group. Usage : ' + filename + ' followed by the application group i.e. \n \t dms or \n \t swaps \n then the site i.e. \n \t 155 or \n \t bromley') - appgroup = sys.argv[1] # Set the variable appgroup as the first argument you supply - site = sys.argv[2] # Set the variable site as the second argument you supply + appgroup = sys.argv[1] # Set the variable appgroup as the first argument you supply + site = sys.argv[2] # Set the variable site as the second argument you supply - if os.name == "posix": # Check the os, if it's linux then - myping = "ping -c 2 " # This is the ping command - elif os.name in ("nt", "dos", "ce"): # Check the os, if it's windows then - myping = "ping -n 2 " # This is the ping command + if os.name == "posix": # Check the os, if it's linux then + myping = "ping -c 2 " # This is the ping command + elif os.name in ("nt", "dos", "ce"): # Check the os, if it's windows then + myping = "ping -n 2 " # This is the ping command - if 'dms' in sys.argv: # If the argument passed is dms then - appgroup = 'dms' # Set the variable appgroup to dms - elif 'swaps' in sys.argv: # Else if the argment passed is swaps then - appgroup = 'swaps' # Set the variable appgroup to swaps + if 'dms' in sys.argv: # If the argument passed is dms then + appgroup = 'dms' # Set the variable appgroup to dms + elif 'swaps' in sys.argv: # Else if the argment passed is swaps then + appgroup = 'swaps' # Set the variable appgroup to swaps - if '155' in sys.argv: # If the argument passed is 155 then - site = '155' # Set the variable site to 155 - elif 'bromley' in sys.argv: # Else if the argument passed is bromley - site = 'bromley' # Set the variable site to bromley + if '155' in sys.argv: # If the argument passed is 155 then + site = '155' # Set the variable site to 155 + elif 'bromley' in sys.argv: # Else if the argument passed is bromley + site = 'bromley' # Set the variable site to bromley -logdir = os.getenv("logs") # Set the variable logdir by getting the OS environment logs -logfile = 'ping_' + appgroup + '_' + site + '.log' # Set the variable logfile, using the arguments passed to create the logfile -logfilename = os.path.join(logdir, logfile) # Set the variable logfilename by joining logdir and logfile together -confdir = os.getenv("my_config") # Set the variable confdir from the OS environment variable - 1.2 -conffile = (appgroup + '_servers_' + site + '.txt') # Set the variable conffile - 1.2 -conffilename = os.path.join(confdir, conffile) # Set the variable conffilename by joining confdir and conffile together - 1.2 +logdir = os.getenv("logs") # Set the variable logdir by getting the OS environment logs +logfile = 'ping_' + appgroup + '_' + site + '.log' # Set the variable logfile, using the arguments passed to create the logfile +logfilename = os.path.join(logdir, logfile) # Set the variable logfilename by joining logdir and logfile together +confdir = os.getenv("my_config") # Set the variable confdir from the OS environment variable - 1.2 +conffile = (appgroup + '_servers_' + site + '.txt') # Set the variable conffile - 1.2 +conffilename = os.path.join(confdir, + conffile) # Set the variable conffilename by joining confdir and conffile together - 1.2 -f = open(logfilename, "w") # Open a logfile to write out the output -for server in open(conffilename): # Open the config file and read each line - 1.2 - ret = subprocess.call(myping + server, shell=True, stdout=f, stderr=subprocess.STDOUT) # Run the ping command for each server in the list. - if ret == 0: # Depending on the response - f.write (server.strip() + " is alive" + "\n") # Write out that you can receive a reponse +f = open(logfilename, "w") # Open a logfile to write out the output +for server in open(conffilename): # Open the config file and read each line - 1.2 + ret = subprocess.call(myping + server, shell=True, stdout=f, + stderr=subprocess.STDOUT) # Run the ping command for each server in the list. + if ret == 0: # Depending on the response + f.write(server.strip() + " is alive" + "\n") # Write out that you can receive a reponse else: - f.write (server.strip() + " did not respond" + "\n") # Write out you can't reach the box + f.write(server.strip() + " did not respond" + "\n") # Write out you can't reach the box -print ("\n\tYou can see the results in the logfile : " + logfilename); # Show the location of the logfile +print("\n\tYou can see the results in the logfile : " + logfilename); # Show the location of the logfile diff --git a/ping_subnet.py b/ping_subnet.py index df7b9141c0c..78c35324b84 100644 --- a/ping_subnet.py +++ b/ping_subnet.py @@ -1,41 +1,41 @@ from __future__ import print_function + +import os # Load the Library Module +import subprocess # Load the Library Module +import sys # Load the Library Module + # Script Name : ping_subnet.py # Author : Craig Richards # Created : 12th January 2012 # Last Modified : # Version : 1.0 - # Modifications : - # Description : After supplying the first 3 octets it will scan the final range for available addresses -import os # Load the Library Module -import subprocess # Load the Library Module -import sys # Load the Library Module - -filename = sys.argv[0] # Sets a variable for the script name +filename = sys.argv[0] # Sets a variable for the script name -if '-h' in sys.argv or '--h' in sys.argv or '-help' in sys.argv or '--help' in sys.argv: # Help Menu if called +if '-h' in sys.argv or '--h' in sys.argv or '-help' in sys.argv or '--help' in sys.argv: # Help Menu if called print(''' You need to supply the first octets of the address Usage : ''' + filename + ''' 111.111.111 ''') sys.exit(0) else: - if (len(sys.argv) < 2): # If no arguments are passed then display the help and instructions on how to run the script - sys.exit (' You need to supply the first octets of the address Usage : ' + filename + ' 111.111.111') + if (len( + sys.argv) < 2): # If no arguments are passed then display the help and instructions on how to run the script + sys.exit(' You need to supply the first octets of the address Usage : ' + filename + ' 111.111.111') - subnet = sys.argv[1] # Set the variable subnet as the three octets you pass it + subnet = sys.argv[1] # Set the variable subnet as the three octets you pass it - if os.name == "posix": # Check the os, if it's linux then - myping = "ping -c 2 " # This is the ping command - elif os.name in ("nt", "dos", "ce"): # Check the os, if it's windows then - myping = "ping -n 2 " # This is the ping command + if os.name == "posix": # Check the os, if it's linux then + myping = "ping -c 2 " # This is the ping command + elif os.name in ("nt", "dos", "ce"): # Check the os, if it's windows then + myping = "ping -n 2 " # This is the ping command - f = open('ping_' + subnet + '.log', 'w') # Open a logfile - for ip in range(2,255): # Set the ip variable for the range of numbers - ret = subprocess.call(myping + str(subnet) + "." + str(ip) , - shell=True, stdout=f, stderr=subprocess.STDOUT) # Run the command pinging the servers - if ret == 0: # Depending on the response - f.write (subnet + "." + str(ip) + " is alive" + "\n") # Write out that you can receive a reponse + f = open('ping_' + subnet + '.log', 'w') # Open a logfile + for ip in range(2, 255): # Set the ip variable for the range of numbers + ret = subprocess.call(myping + str(subnet) + "." + str(ip), + shell=True, stdout=f, stderr=subprocess.STDOUT) # Run the command pinging the servers + if ret == 0: # Depending on the response + f.write(subnet + "." + str(ip) + " is alive" + "\n") # Write out that you can receive a reponse else: - f.write (subnet + "." + str(ip) + " did not respond" + "\n") # Write out you can't reach the box + f.write(subnet + "." + str(ip) + " did not respond" + "\n") # Write out you can't reach the box diff --git a/polygon.py b/polygon.py index 8ab7d11aa02..ba300f8a317 100644 --- a/polygon.py +++ b/polygon.py @@ -1,4 +1,5 @@ -import pygame, sys, time +import pygame +import sys from pygame.locals import * pygame.init() @@ -6,7 +7,7 @@ pygame.display.set_caption("Shape") WHITE = (255, 255, 255) -GREEN = ( 0, 255, 0) +GREEN = (0, 255, 0) window.fill(WHITE) pygame.draw.polygon(window, GREEN, ((146, 0), (236, 277), (56, 277))) diff --git a/portscanner.py b/portscanner.py index 5a78c478185..f90c063cea8 100644 --- a/portscanner.py +++ b/portscanner.py @@ -1,62 +1,66 @@ from __future__ import print_function + +import optparse # Import the module +from socket import * # Import the module +from threading import * # Import the module + # Script Name : portscanner.py # Author : Craig Richards -# Created : 20 May 2013 -# Last Modified : +# Created : 20 May 2013 +# Last Modified : # Version : 1.0 +# Modifications : +# Description : Port Scanner, you just pass the host and the ports -# Modifications : +screenLock = Semaphore(value=1) # Prevent other threads from preceeding -# Description : Port Scanner, you just pass the host and the ports -import optparse # Import the module -from socket import * # Import the module -from threading import * # Import the module - -screenLock = Semaphore(value=1) # Prevent other threads from preceeding - -def connScan(tgtHost, tgtPort): # Start of the function - try: - connSkt = socket(AF_INET, SOCK_STREAM) # Open a socket - connSkt.connect((tgtHost, tgtPort)) - connSkt.send('') - results=connSkt.recv(100) - screenLock.acquire() # Acquire the lock - print('[+] %d/tcp open'% tgtPort) - print('[+] ' + str(results)) - except: - screenLock.acquire() - print('[-] %d/tcp closed '% tgtPort) - finally: - screenLock.release() - connSkt.close() - -def portScan(tgtHost, tgtPorts): # Start of the function - try: - tgtIP = gethostbyname(tgtHost) # Get the IP from the hostname - except: - print("[-] Cannot resolve '%s': Unknown host"%tgtHost) - return - try: - tgtName = gethostbyaddr(tgtIP) # Get hostname from IP - print('\n[+] Scan Results for: ' +tgtName[0]) - except: - print('\n[+] Scan Results for: ' + tgtIP) - setdefaulttimeout(1) - for tgtPort in tgtPorts: # Scan host and ports - t = Thread(target=connScan, args=(tgtHost, int(tgtPort))) - t.start() +def connScan(tgtHost, tgtPort): # Start of the function + try: + connSkt = socket(AF_INET, SOCK_STREAM) # Open a socket + connSkt.connect((tgtHost, tgtPort)) + connSkt.send('') + results = connSkt.recv(100) + screenLock.acquire() # Acquire the lock + print('[+] %d/tcp open' % tgtPort) + print('[+] ' + str(results)) + except: + screenLock.acquire() + print('[-] %d/tcp closed ' % tgtPort) + finally: + screenLock.release() + connSkt.close() + + +def portScan(tgtHost, tgtPorts): # Start of the function + try: + tgtIP = gethostbyname(tgtHost) # Get the IP from the hostname + except: + print("[-] Cannot resolve '%s': Unknown host" % tgtHost) + return + try: + tgtName = gethostbyaddr(tgtIP) # Get hostname from IP + print('\n[+] Scan Results for: ' + tgtName[0]) + except: + print('\n[+] Scan Results for: ' + tgtIP) + setdefaulttimeout(1) + for tgtPort in tgtPorts: # Scan host and ports + t = Thread(target=connScan, args=(tgtHost, int(tgtPort))) + t.start() + def main(): - parser = optparse.OptionParser('usage %prog -H'+' -p ') - parser.add_option('-H', dest='tgtHost', type='string', help='specify target host') - parser.add_option('-p', dest='tgtPort',type='string', help='specify target port[s] seperated by a comma') - (options, args) = parser.parse_args() - tgtHost = options.tgtHost - tgtPorts = str(options.tgtPort).split(',') - if (tgtHost == None) | (tgtPorts[0] == None): - print(parser.usage) - exit(0) - portScan(tgtHost, tgtPorts) + parser = optparse.OptionParser('usage %prog -H' + ' -p ') + parser.add_option('-H', dest='tgtHost', type='string', help='specify target host') + parser.add_option('-p', dest='tgtPort', type='string', help='specify target port[s] seperated by a comma') + (options, args) = parser.parse_args() + tgtHost = options.tgtHost + tgtPorts = str(options.tgtPort).split(',') + if (tgtHost == None) | (tgtPorts[0] == None): + print(parser.usage) + exit(0) + portScan(tgtHost, tgtPorts) + + if __name__ == '__main__': - main() \ No newline at end of file + main() diff --git a/powerdown_startup.py b/powerdown_startup.py index 0913c487788..4c11ba7aeb3 100644 --- a/powerdown_startup.py +++ b/powerdown_startup.py @@ -8,37 +8,42 @@ # Description : This goes through the server list and pings the machine, if it's up it will load the putty session, if its not it will notify you. -import os # Load the Library Module -import subprocess # Load the Library Module -from time import strftime # Load just the strftime Module from Time - -def windows(): # This is the function to run if it detects the OS is windows. - f = open('server_startup_'+strftime("%Y-%m-%d")+'.log', 'a') # Open the logfile - for server in open('startup_list.txt','r'): # Read the list of servers from the list - ret = subprocess.call("ping -n 3 %s" % server, shell=True,stdout=open('NUL', 'w'),stderr=subprocess.STDOUT) # Ping the servers in turn - if ret == 0: # If you get a response. - f.write ("%s: is alive, loading PuTTY session" % server.strip() + "\n") # Write out to the logfile - subprocess.Popen(('putty -load '+server)) # Load the putty session - else: - f.write ("%s : did not respond" % server.strip() + "\n") # Write to the logfile if the server is down +import os # Load the Library Module +import subprocess # Load the Library Module +from time import strftime # Load just the strftime Module from Time + + +def windows(): # This is the function to run if it detects the OS is windows. + f = open('server_startup_' + strftime("%Y-%m-%d") + '.log', 'a') # Open the logfile + for server in open('startup_list.txt', 'r'): # Read the list of servers from the list + ret = subprocess.call("ping -n 3 %s" % server, shell=True, stdout=open('NUL', 'w'), + stderr=subprocess.STDOUT) # Ping the servers in turn + if ret == 0: # If you get a response. + f.write("%s: is alive, loading PuTTY session" % server.strip() + "\n") # Write out to the logfile + subprocess.Popen(('putty -load ' + server)) # Load the putty session + else: + f.write("%s : did not respond" % server.strip() + "\n") # Write to the logfile if the server is down + def linux(): - f = open('server_startup_'+strftime("%Y-%m-%d")+'.log', 'a') # Open the logfile - for server in open('startup_list.txt'): # Read the list of servers from the list - ret = subprocess.call("ping -c 3 %s" % server, shell=True,stdout=open('/dev/null', 'w'),stderr=subprocess.STDOUT) # Ping the servers in turn - if ret == 0: # If you get a response. - f.write ("%s: is alive" % server.strip() + "\n") # Print a message - subprocess.Popen(['ssh', server.strip()]) - else: - f.write ("%s: did not respond" % server.strip() + "\n") + f = open('server_startup_' + strftime("%Y-%m-%d") + '.log', 'a') # Open the logfile + for server in open('startup_list.txt'): # Read the list of servers from the list + ret = subprocess.call("ping -c 3 %s" % server, shell=True, stdout=open('/dev/null', 'w'), + stderr=subprocess.STDOUT) # Ping the servers in turn + if ret == 0: # If you get a response. + f.write("%s: is alive" % server.strip() + "\n") # Print a message + subprocess.Popen(['ssh', server.strip()]) + else: + f.write("%s: did not respond" % server.strip() + "\n") + -# End of the functions +# End of the functions # Start of the Main Program -if os.name == "posix": # If the OS is linux... - linux() # Call the linux function -elif os.name in ("nt", "dos", "ce"): # If the OS is Windows... - windows() # Call the windows function +if os.name == "posix": # If the OS is linux... + linux() # Call the linux function +elif os.name in ("nt", "dos", "ce"): # If the OS is Windows... + windows() # Call the windows function else: - print("Not supported") + print("Not supported") diff --git a/powerup_checks.py b/powerup_checks.py index b7b3bd0b875..a8746c3c5ec 100644 --- a/powerup_checks.py +++ b/powerup_checks.py @@ -1,28 +1,26 @@ from __future__ import print_function + +import os # Load the Library Module +import sqlite3 # Load the Library Module +import subprocess # Load the Library Module +import sys # Load the Library Module +from time import strftime # Load just the strftime Module from Time + # Script Name : powerup_checks.py # Author : Craig Richards # Created : 25th June 2013 -# Last Modified : +# Last Modified : # Version : 1.0 - -# Modifications : - +# Modifications : # Description : Creates an output file by pulling all the servers for the given site from SQLITE database, then goes through the list pinging the servers to see if they are up on the network -import sys # Load the Library Module -import sqlite3 # Load the Library Module -import os # Load the Library Module -import subprocess # Load the Library Module -from time import strftime # Load just the strftime Module from Time - - -dropbox=os.getenv("dropbox") # Set the variable, by getting the value of the variable from the OS -config=os.getenv("my_config") # Set the variable, by getting the value of the variable from the OS -dbfile=("Databases/jarvis.db") # Set the variable to the database -master_db=os.path.join(dropbox, dbfile) # Create the variable by linking the path and the file -listfile=("startup_list.txt") # File that will hold the servers -serverfile=os.path.join(config,listfile) # Create the variable by linking the path and the file -outputfile=('server_startup_'+strftime("%Y-%m-%d-%H-%M")+'.log') +dropbox = os.getenv("dropbox") # Set the variable, by getting the value of the variable from the OS +config = os.getenv("my_config") # Set the variable, by getting the value of the variable from the OS +dbfile = ("Databases/jarvis.db") # Set the variable to the database +master_db = os.path.join(dropbox, dbfile) # Create the variable by linking the path and the file +listfile = ("startup_list.txt") # File that will hold the servers +serverfile = os.path.join(config, listfile) # Create the variable by linking the path and the file +outputfile = ('server_startup_' + strftime("%Y-%m-%d-%H-%M") + '.log') # Below is the help text @@ -33,67 +31,75 @@ -site1 For the Servers relating to site1 -site2 For the Servers located in site2''' -def windows(): # This is the function to run if it detects the OS is windows. - f = open(outputfile, 'a') # Open the logfile - for server in open(serverfile,'r'): # Read the list of servers from the list - #ret = subprocess.call("ping -n 3 %s" % server.strip(), shell=True,stdout=open('NUL', 'w'),stderr=subprocess.STDOUT) # Ping the servers in turn - ret = subprocess.call("ping -n 3 %s" % server.strip(),stdout=open('NUL', 'w'),stderr=subprocess.STDOUT) # Ping the servers in turn - if ret == 0: # Depending on the response - f.write ("%s: is alive" % server.strip().ljust(15) + "\n") # Write out to the logfile is the server is up + +def windows(): # This is the function to run if it detects the OS is windows. + f = open(outputfile, 'a') # Open the logfile + for server in open(serverfile, 'r'): # Read the list of servers from the list + # ret = subprocess.call("ping -n 3 %s" % server.strip(), shell=True,stdout=open('NUL', 'w'),stderr=subprocess.STDOUT) # Ping the servers in turn + ret = subprocess.call("ping -n 3 %s" % server.strip(), stdout=open('NUL', 'w'), + stderr=subprocess.STDOUT) # Ping the servers in turn + if ret == 0: # Depending on the response + f.write("%s: is alive" % server.strip().ljust(15) + "\n") # Write out to the logfile is the server is up else: - f.write ("%s: did not respond" % server.strip().ljust(15) + "\n") # Write to the logfile if the server is down + f.write( + "%s: did not respond" % server.strip().ljust(15) + "\n") # Write to the logfile if the server is down -def linux(): # This is the function to run if it detects the OS is nix. - f = open('server_startup_'+strftime("%Y-%m-%d")+'.log', 'a') # Open the logfile - for server in open(serverfile,'r'): # Read the list of servers from the list - ret = subprocess.call("ping -c 3 %s" % server, shell=True,stdout=open('/dev/null', 'w'),stderr=subprocess.STDOUT) # Ping the servers in turn - if ret == 0: # Depending on the response - f.write ("%s: is alive" % server.strip().ljust(15) + "\n") # Write out to the logfile is the server is up +def linux(): # This is the function to run if it detects the OS is nix. + f = open('server_startup_' + strftime("%Y-%m-%d") + '.log', 'a') # Open the logfile + for server in open(serverfile, 'r'): # Read the list of servers from the list + ret = subprocess.call("ping -c 3 %s" % server, shell=True, stdout=open('/dev/null', 'w'), + stderr=subprocess.STDOUT) # Ping the servers in turn + if ret == 0: # Depending on the response + f.write("%s: is alive" % server.strip().ljust(15) + "\n") # Write out to the logfile is the server is up else: - f.write ("%s: did not respond" % server.strip().ljust(15) + "\n") # Write to the logfile if the server is down - -def get_servers(query): # Function to get the servers from the database - conn = sqlite3.connect(master_db) # Connect to the database - cursor = conn.cursor() # Create the cursor - cursor.execute('select hostname from tp_servers where location =?',(query,)) # SQL Statement - print ('\nDisplaying Servers for : ' + query + '\n') - while True: # While there are results - row = cursor.fetchone() # Return the results - if row == None: - break - f = open(serverfile, 'a') # Open the serverfile - f.write("%s\n" % str(row[0])) # Write the server out to the file - print(row[0]) # Display the server to the screen - f.close() # Close the file - -def main(): # Main Function - if os.path.exists(serverfile): # Checks to see if there is an existing server file - os.remove(serverfile) # If so remove it - - if len(sys.argv) < 2: # Check there is an argument being passed - print(text) # Display the help text if there isn't one passed - sys.exit() # Exit the script - - if '-h' in sys.argv or '--h' in sys.argv or '-help' in sys.argv or '--help' in sys.argv: # If the ask for help - print(text) # Display the help text if there isn't one passed - sys.exit(0) # Exit the script after displaying help - else: - if sys.argv[1].lower().startswith('-site1'): # If the argument is site1 - query = 'site1' # Set the variable to have the value site - elif sys.argv[1].lower().startswith('-site2'): # Else if the variable is bromley - query = 'site2' # Set the variable to have the value bromley + f.write( + "%s: did not respond" % server.strip().ljust(15) + "\n") # Write to the logfile if the server is down + + +def get_servers(query): # Function to get the servers from the database + conn = sqlite3.connect(master_db) # Connect to the database + cursor = conn.cursor() # Create the cursor + cursor.execute('select hostname from tp_servers where location =?', (query,)) # SQL Statement + print('\nDisplaying Servers for : ' + query + '\n') + while True: # While there are results + row = cursor.fetchone() # Return the results + if row == None: + break + f = open(serverfile, 'a') # Open the serverfile + f.write("%s\n" % str(row[0])) # Write the server out to the file + print(row[0]) # Display the server to the screen + f.close() # Close the file + + +def main(): # Main Function + if os.path.exists(serverfile): # Checks to see if there is an existing server file + os.remove(serverfile) # If so remove it + + if len(sys.argv) < 2: # Check there is an argument being passed + print(text) # Display the help text if there isn't one passed + sys.exit() # Exit the script + + if '-h' in sys.argv or '--h' in sys.argv or '-help' in sys.argv or '--help' in sys.argv: # If the ask for help + print(text) # Display the help text if there isn't one passed + sys.exit(0) # Exit the script after displaying help else: - print('\n[-] Unknown option [-] ' + text) # If an unknown option is passed, let the user know - sys.exit(0) - get_servers(query) # Call the get servers funtion, with the value from the argument - - if os.name == "posix": # If the OS is linux. - linux() # Call the linux function - elif os.name in ("nt", "dos", "ce"): # If the OS is Windows... - windows() # Call the windows function - - print ('\n[+] Check the log file ' + outputfile + ' [+]\n') # Display the name of the log - + if sys.argv[1].lower().startswith('-site1'): # If the argument is site1 + query = 'site1' # Set the variable to have the value site + elif sys.argv[1].lower().startswith('-site2'): # Else if the variable is bromley + query = 'site2' # Set the variable to have the value bromley + else: + print('\n[-] Unknown option [-] ' + text) # If an unknown option is passed, let the user know + sys.exit(0) + get_servers(query) # Call the get servers funtion, with the value from the argument + + if os.name == "posix": # If the OS is linux. + linux() # Call the linux function + elif os.name in ("nt", "dos", "ce"): # If the OS is Windows... + windows() # Call the windows function + + print('\n[+] Check the log file ' + outputfile + ' [+]\n') # Display the name of the log + + if __name__ == '__main__': - main() # Call the main function \ No newline at end of file + main() # Call the main function diff --git a/primelib/primelib.py b/primelib/primelib.py index 4e9536134ae..0e312aad7cb 100644 --- a/primelib/primelib.py +++ b/primelib/primelib.py @@ -39,6 +39,7 @@ """ + def pi(maxK=70, prec=1008, disp=1007): """ maxK: nuber of iterations @@ -47,9 +48,9 @@ def pi(maxK=70, prec=1008, disp=1007): """ from decimal import Decimal as Dec, getcontext as gc gc().prec = prec - K, M, L, X, S = 6, 1, 13591409, 1, 13591409 - for k in range(1, maxK+1): - M = Dec((K**3 - (K<<4)) * M / k**3) + K, M, L, X, S = 6, 1, 13591409, 1, 13591409 + for k in range(1, maxK + 1): + M = Dec((K ** 3 - (K << 4)) * M / k ** 3) L += 545140134 X *= -262537412640768000 S += Dec(M * L) / X @@ -58,36 +59,38 @@ def pi(maxK=70, prec=1008, disp=1007): pi = Dec(str(pi)[:disp]) return pi + def isPrime(number): """ input: positive integer 'number' returns true if 'number' is prime otherwise false. """ - import math # for function sqrt - + import math # for function sqrt + # precondition - assert isinstance(number,int) and (number >= 0) , \ - "'number' must been an int and positive" - + assert isinstance(number, int) and (number >= 0), \ + "'number' must been an int and positive" + status = True - + # 0 and 1 are none primes. if number <= 1: return False - + # all even numbers except of 2 are no primes. if number % 2 == 0 and number > 2: return False - + # if 'number' divisible by 'divisor' then sets 'status' to false. # lazy evaluation breaks the all loop on first false. status = all(number % divisor for divisor in range(3, int(math.sqrt(number)) + 1, 2)) - + # precondition - assert isinstance(status,bool), "'status' must been from type bool" - + assert isinstance(status, bool), "'status' must been from type bool" + return status + # ------------------------------------------ def sieveEr(N): @@ -99,32 +102,32 @@ def sieveEr(N): sieve of erathostenes. """ - + # precondition - assert isinstance(N,int) and (N > 2), "'N' must been an int and > 2" - + assert isinstance(N, int) and (N > 2), "'N' must been an int and > 2" + # beginList: conatins all natural numbers from 2 upt to N - beginList = [x for x in range(2,N+1)] + beginList = [x for x in range(2, N + 1)] + + ans = [] # this list will be returns. - ans = [] # this list will be returns. - # actual sieve of erathostenes for i in range(len(beginList)): - - for j in range(i+1,len(beginList)): - + + for j in range(i + 1, len(beginList)): + if (beginList[i] != 0) and \ - (beginList[j] % beginList[i] == 0): + (beginList[j] % beginList[i] == 0): beginList[j] = 0 - + # filters actual prime numbers. ans = [x for x in beginList if x != 0] - + # precondition - assert isinstance(ans,list), "'ans' must been from type list" - + assert isinstance(ans, list), "'ans' must been from type list" + return ans - + # -------------------------------- @@ -133,340 +136,339 @@ def getPrimeNumbers(N): input: positive integer 'N' > 2 returns a list of prime numbers from 2 up to N (inclusive) This function is more efficient as function 'sieveEr(...)' - """ - + """ + # precondition - assert isinstance(N,int) and (N > 2), "'N' must been an int and > 2" - - ans = [] - + assert isinstance(N, int) and (N > 2), "'N' must been an int and > 2" + + ans = [] + # iterates over all numbers between 2 up to N+1 # if a number is prime then appends to list 'ans' - for number in range(2,N+1): - + for number in range(2, N + 1): + if isPrime(number): - ans.append(number) - + # precondition - assert isinstance(ans,list), "'ans' must been from type list" - + assert isinstance(ans, list), "'ans' must been from type list" + return ans # ----------------------------------------- - + def primeFactorization(number): """ input: positive integer 'number' returns a list of the prime number factors of 'number' """ - import math # for function sqrt - # precondition - assert isinstance(number,int) and number >= 0, \ - "'number' must been an int and >= 0" - - ans = [] # this list will be returns of the function. + assert isinstance(number, int) and number >= 0, \ + "'number' must been an int and >= 0" + + ans = [] # this list will be returns of the function. # potential prime number factors. - factor = 2 + factor = 2 quotient = number - - + if number == 0 or number == 1: - + ans.append(number) - + # if 'number' not prime then builds the prime factorization of 'number' elif not isPrime(number): - + while (quotient != 1): - + if isPrime(factor) and (quotient % factor == 0): - ans.append(factor) - quotient /= factor + ans.append(factor) + quotient /= factor else: - factor += 1 - + factor += 1 + else: ans.append(number) - + # precondition - assert isinstance(ans,list), "'ans' must been from type list" - + assert isinstance(ans, list), "'ans' must been from type list" + return ans - + # ----------------------------------------- - + def greatestPrimeFactor(number): """ input: positive integer 'number' >= 0 returns the greatest prime number factor of 'number' """ - + # precondition - assert isinstance(number,int) and (number >= 0), \ - "'number' bust been an int and >= 0" - - ans = 0 - + assert isinstance(number, int) and (number >= 0), \ + "'number' bust been an int and >= 0" + + ans = 0 + # prime factorization of 'number' primeFactors = primeFactorization(number) - ans = max(primeFactors) - + ans = max(primeFactors) + # precondition - assert isinstance(ans,int), "'ans' must been from type int" - + assert isinstance(ans, int), "'ans' must been from type int" + return ans - + # ---------------------------------------------- - - + + def smallestPrimeFactor(number): """ input: integer 'number' >= 0 returns the smallest prime number factor of 'number' """ - + # precondition - assert isinstance(number,int) and (number >= 0), \ - "'number' bust been an int and >= 0" - - ans = 0 - + assert isinstance(number, int) and (number >= 0), \ + "'number' bust been an int and >= 0" + + ans = 0 + # prime factorization of 'number' primeFactors = primeFactorization(number) - + ans = min(primeFactors) # precondition - assert isinstance(ans,int), "'ans' must been from type int" - + assert isinstance(ans, int), "'ans' must been from type int" + return ans - - + + # ---------------------- - + def isEven(number): """ input: integer 'number' returns true if 'number' is even, otherwise false. - """ + """ # precondition - assert isinstance(number, int), "'number' must been an int" + assert isinstance(number, int), "'number' must been an int" assert isinstance(number % 2 == 0, bool), "compare bust been from type bool" - + return number % 2 == 0 - + + # ------------------------ - + def isOdd(number): """ input: integer 'number' returns true if 'number' is odd, otherwise false. - """ + """ # precondition - assert isinstance(number, int), "'number' must been an int" + assert isinstance(number, int), "'number' must been an int" assert isinstance(number % 2 != 0, bool), "compare bust been from type bool" - + return number % 2 != 0 - + + # ------------------------ - - + + def goldbach(number): """ Goldbach's assumption input: a even positive integer 'number' > 2 returns a list of two prime numbers whose sum is equal to 'number' """ - + # precondition - assert isinstance(number,int) and (number > 2) and isEven(number), \ - "'number' must been an int, even and > 2" - - ans = [] # this list will returned - + assert isinstance(number, int) and (number > 2) and isEven(number), \ + "'number' must been an int, even and > 2" + + ans = [] # this list will returned + # creates a list of prime numbers between 2 up to 'number' primeNumbers = getPrimeNumbers(number) - lenPN = len(primeNumbers) + lenPN = len(primeNumbers) # run variable for while-loops. i = 0 j = 1 - + # exit variable. for break up the loops loop = True - + while (i < lenPN and loop): - - j = i+1; - - + + j = i + 1; + while (j < lenPN and loop): - + if primeNumbers[i] + primeNumbers[j] == number: loop = False ans.append(primeNumbers[i]) ans.append(primeNumbers[j]) - + j += 1; - - + i += 1 - + # precondition - assert isinstance(ans,list) and (len(ans) == 2) and \ - (ans[0] + ans[1] == number) and isPrime(ans[0]) and isPrime(ans[1]), \ - "'ans' must contains two primes. And sum of elements must been eq 'number'" - + assert isinstance(ans, list) and (len(ans) == 2) and \ + (ans[0] + ans[1] == number) and isPrime(ans[0]) and isPrime(ans[1]), \ + "'ans' must contains two primes. And sum of elements must been eq 'number'" + return ans - + + # ---------------------------------------------- -def gcd(number1,number2): +def gcd(number1, number2): """ Greatest common divisor input: two positive integer 'number1' and 'number2' returns the greatest common divisor of 'number1' and 'number2' """ - + # precondition - assert isinstance(number1,int) and isinstance(number2,int) \ - and (number1 >= 0) and (number2 >= 0), \ - "'number1' and 'number2' must been positive integer." + assert isinstance(number1, int) and isinstance(number2, int) \ + and (number1 >= 0) and (number2 >= 0), \ + "'number1' and 'number2' must been positive integer." + + rest = 0 - rest = 0 - while number2 != 0: - rest = number1 % number2 number1 = number2 number2 = rest # precondition - assert isinstance(number1,int) and (number1 >= 0), \ - "'number' must been from type int and positive" - + assert isinstance(number1, int) and (number1 >= 0), \ + "'number' must been from type int and positive" + return number1 - + + # ---------------------------------------------------- - + def kgV(number1, number2): """ Least common multiple input: two positive integer 'number1' and 'number2' returns the least common multiple of 'number1' and 'number2' """ - + # precondition - assert isinstance(number1,int) and isinstance(number2,int) \ - and (number1 >= 1) and (number2 >= 1), \ - "'number1' and 'number2' must been positive integer." - - ans = 1 # actual answer that will be return. - + assert isinstance(number1, int) and isinstance(number2, int) \ + and (number1 >= 1) and (number2 >= 1), \ + "'number1' and 'number2' must been positive integer." + + ans = 1 # actual answer that will be return. + # for kgV (x,1) if number1 > 1 and number2 > 1: - + # builds the prime factorization of 'number1' and 'number2' primeFac1 = primeFactorization(number1) primeFac2 = primeFactorization(number2) - + elif number1 == 1 or number2 == 1: - + primeFac1 = [] primeFac2 = [] - ans = max(number1,number2) - + ans = max(number1, number2) + count1 = 0 count2 = 0 - - done = [] # captured numbers int both 'primeFac1' and 'primeFac2' - + + done = [] # captured numbers int both 'primeFac1' and 'primeFac2' + # iterates through primeFac1 for n in primeFac1: - + if n not in done: - + if n in primeFac2: - + count1 = primeFac1.count(n) count2 = primeFac2.count(n) - - for i in range(max(count1,count2)): + + for i in range(max(count1, count2)): ans *= n - + else: - + count1 = primeFac1.count(n) - + for i in range(count1): ans *= n - + done.append(n) - + # iterates through primeFac2 for n in primeFac2: - + if n not in done: - + count2 = primeFac2.count(n) - + for i in range(count2): ans *= n - + done.append(n) - + # precondition - assert isinstance(ans,int) and (ans >= 0), \ - "'ans' must been from type int and positive" - + assert isinstance(ans, int) and (ans >= 0), \ + "'ans' must been from type int and positive" + return ans - + + # ---------------------------------- - + def getPrime(n): """ Gets the n-th prime number. input: positive integer 'n' >= 0 returns the n-th prime number, beginning at index 0 """ - + # precondition - assert isinstance(n,int) and (n >= 0), "'number' must been a positive int" - + assert isinstance(n, int) and (n >= 0), "'number' must been a positive int" + index = 0 - ans = 2 # this variable holds the answer - + ans = 2 # this variable holds the answer + while index < n: - + index += 1 - - ans += 1 # counts to the next number - + + ans += 1 # counts to the next number + # if ans not prime then # runs to the next prime number. while not isPrime(ans): ans += 1 - + # precondition - assert isinstance(ans,int) and isPrime(ans), \ - "'ans' must been a prime number and from type int" - + assert isinstance(ans, int) and isPrime(ans), \ + "'ans' must been a prime number and from type int" + return ans - + + # --------------------------------------------------- - + def getPrimesBetween(pNumber1, pNumber2): """ input: prime numbers 'pNumber1' and 'pNumber2' @@ -474,38 +476,39 @@ def getPrimesBetween(pNumber1, pNumber2): returns a list of all prime numbers between 'pNumber1' (exclusiv) and 'pNumber2' (exclusiv) """ - + # precondition assert isPrime(pNumber1) and isPrime(pNumber2) and (pNumber1 < pNumber2), \ - "The arguments must been prime numbers and 'pNumber1' < 'pNumber2'" - - number = pNumber1 + 1 # jump to the next number - - ans = [] # this list will be returns. - + "The arguments must been prime numbers and 'pNumber1' < 'pNumber2'" + + number = pNumber1 + 1 # jump to the next number + + ans = [] # this list will be returns. + # if number is not prime then # fetch the next prime number. while not isPrime(number): number += 1 - + while number < pNumber2: - + ans.append(number) - + number += 1 - + # fetch the next prime number. while not isPrime(number): number += 1 - + # precondition - assert isinstance(ans,list) and ans[0] != pNumber1 \ - and ans[len(ans)-1] != pNumber2, \ - "'ans' must been a list without the arguments" - + assert isinstance(ans, list) and ans[0] != pNumber1 \ + and ans[len(ans) - 1] != pNumber2, \ + "'ans' must been a list without the arguments" + # 'ans' contains not 'pNumber1' and 'pNumber2' ! return ans - + + # ---------------------------------------------------- def getDivisors(n): @@ -513,25 +516,21 @@ def getDivisors(n): input: positive integer 'n' >= 1 returns all divisors of n (inclusive 1 and 'n') """ - + # precondition - assert isinstance(n,int) and (n >= 1), "'n' must been int and >= 1" + assert isinstance(n, int) and (n >= 1), "'n' must been int and >= 1" + + ans = [] # will be returned. + + for divisor in range(1, n + 1): - from math import sqrt - - ans = [] # will be returned. - - for divisor in range(1,n+1): - if n % divisor == 0: ans.append(divisor) - - - #precondition - assert ans[0] == 1 and ans[len(ans)-1] == n, \ - "Error in function getDivisiors(...)" - - + + # precondition + assert ans[0] == 1 and ans[len(ans) - 1] == n, \ + "Error in function getDivisiors(...)" + return ans @@ -543,21 +542,22 @@ def isPerfectNumber(number): input: positive integer 'number' > 1 returns true if 'number' is a perfect number otherwise false. """ - + # precondition - assert isinstance(number,int) and (number > 1), \ - "'number' must been an int and >= 1" - + assert isinstance(number, int) and (number > 1), \ + "'number' must been an int and >= 1" + divisors = getDivisors(number) - + # precondition - assert isinstance(divisors,list) and(divisors[0] == 1) and \ - (divisors[len(divisors)-1] == number), \ - "Error in help-function getDivisiors(...)" - + assert isinstance(divisors, list) and (divisors[0] == 1) and \ + (divisors[len(divisors) - 1] == number), \ + "Error in help-function getDivisiors(...)" + # summed all divisors up to 'number' (exclusive), hence [:-1] return sum(divisors[:-1]) == number + # ------------------------------------------------------------ def simplifyFraction(numerator, denominator): @@ -565,60 +565,61 @@ def simplifyFraction(numerator, denominator): input: two integer 'numerator' and 'denominator' assumes: 'denominator' != 0 returns: a tuple with simplify numerator and denominator. - """ - + """ + # precondition - assert isinstance(numerator, int) and isinstance(denominator,int) \ - and (denominator != 0), \ - "The arguments must been from type int and 'denominator' != 0" - + assert isinstance(numerator, int) and isinstance(denominator, int) \ + and (denominator != 0), \ + "The arguments must been from type int and 'denominator' != 0" + # build the greatest common divisor of numerator and denominator. gcdOfFraction = gcd(abs(numerator), abs(denominator)) # precondition assert isinstance(gcdOfFraction, int) and (numerator % gcdOfFraction == 0) \ - and (denominator % gcdOfFraction == 0), \ - "Error in function gcd(...,...)" - + and (denominator % gcdOfFraction == 0), \ + "Error in function gcd(...,...)" + return (numerator // gcdOfFraction, denominator // gcdOfFraction) - + + # ----------------------------------------------------------------- - + def factorial(n): """ input: positive integer 'n' returns the factorial of 'n' (n!) """ - + # precondition - assert isinstance(n,int) and (n >= 0), "'n' must been a int and >= 0" - - ans = 1 # this will be return. - - for factor in range(1,n+1): + assert isinstance(n, int) and (n >= 0), "'n' must been a int and >= 0" + + ans = 1 # this will be return. + + for factor in range(1, n + 1): ans *= factor - + return ans - + + # ------------------------------------------------------------------- - + def fib(n): """ input: positive integer 'n' returns the n-th fibonacci term , indexing by 0 - """ - + """ + # precondition assert isinstance(n, int) and (n >= 0), "'n' must been an int and >= 0" - + tmp = 0 fib1 = 1 - ans = 1 # this will be return - - for i in range(n-1): - + ans = 1 # this will be return + + for i in range(n - 1): tmp = ans ans += fib1 fib1 = tmp - + return ans diff --git a/prison_break_scrapper.py b/prison_break_scrapper.py index 0946731ee4c..97b34cb942f 100644 --- a/prison_break_scrapper.py +++ b/prison_break_scrapper.py @@ -2,42 +2,41 @@ Scrapper for downloading prison break series from an open server and putting them in a designated folder. """ -import requests as req -from bs4 import BeautifulSoup as bs import os import subprocess +import requests as req +from bs4 import BeautifulSoup as bs BASE_URL = 'http://dl.funsaber.net/serial/Prison%20Break/season%20' def download_files(links, idx): - for link in links: - subprocess.call([ - "aria2c", - "-s", - "16", - "-x", - "16", - "-d", - "season"+str(idx), - link - ]) + for link in links: + subprocess.call([ + "aria2c", + "-s", + "16", + "-x", + "16", + "-d", + "season" + str(idx), + link + ]) def main(): - for i in range(1,5): - r = req.get(BASE_URL+str(i)+'/1080/') - soup = bs(r.text, 'html.parser') - link_ = [] - for link in soup.find_all('a'): - if '.mkv' in link.get('href'): - link_.append(BASE_URL+str(i)+'/1080/'+link.get('href')) - if not os.path.exists('season'+str(i)): - os.makedirs('season'+str(i)) - download_files(link_, i) - + for i in range(1, 5): + r = req.get(BASE_URL + str(i) + '/1080/') + soup = bs(r.text, 'html.parser') + link_ = [] + for link in soup.find_all('a'): + if '.mkv' in link.get('href'): + link_.append(BASE_URL + str(i) + '/1080/' + link.get('href')) + if not os.path.exists('season' + str(i)): + os.makedirs('season' + str(i)) + download_files(link_, i) if __name__ == '__main__': - main() \ No newline at end of file + main() diff --git a/pscheck.py b/pscheck.py index d60dd160e0a..0954aef6a78 100644 --- a/pscheck.py +++ b/pscheck.py @@ -8,10 +8,11 @@ # Description : Process check on Nix boxes, diplsay formatted output from ps command -import commands import os import string +import commands + try: input = raw_input except NameError: @@ -19,29 +20,30 @@ def ps(): - program = input("Enter the name of the program to check: ") + program = input("Enter the name of the program to check: ") - try: - # perform a ps command and assign results to a list - output = commands.getoutput("ps -f|grep " + program) - proginfo = string.split(output) + try: + # perform a ps command and assign results to a list + output = commands.getoutput("ps -f|grep " + program) + proginfo = string.split(output) - # display results - print("\n\ + # display results + print("\n\ Full path:\t\t", proginfo[5], "\n\ Owner:\t\t\t", proginfo[0], "\n\ Process ID:\t\t", proginfo[1], "\n\ Parent process ID:\t", proginfo[2], "\n\ Time started:\t\t", proginfo[4]) - except: - print("There was a problem with the program.") + except: + print("There was a problem with the program.") + def main(): - if os.name == "posix": # Unix/Linux/MacOS/BSD/etc - ps() # Call the function - elif os.name in ("nt", "dos", "ce"): # if the OS is windows - print("You need to be on Linux or Unix to run this") + if os.name == "posix": # Unix/Linux/MacOS/BSD/etc + ps() # Call the function + elif os.name in ("nt", "dos", "ce"): # if the OS is windows + print("You need to be on Linux or Unix to run this") if __name__ == '__main__': - main() + main() diff --git a/psunotify.py b/psunotify.py index cca76139351..845dd60b5f0 100644 --- a/psunotify.py +++ b/psunotify.py @@ -1,40 +1,43 @@ from __future__ import print_function -import mechanize + import re + +import mechanize import urllib2 -from random import * -br=mechanize.Browser() -br.addheaders = [('User-Agent','Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/37.0.2062.120 Safari/537.36')] + +br = mechanize.Browser() +br.addheaders = [('User-Agent', + 'Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/37.0.2062.120 Safari/537.36')] br.set_handle_robots(False) -#For page exploration -page=raw_input('Enter Page No:') -#print type(page) -p=urllib2.Request('https://www.google.co.in/search?q=gate+psu+2017+ext:pdf&start='+page) -ht=br.open(p) -text='(.+?)' -patt=re.compile(text) -h=ht.read() -urls=re.findall(patt,h) -int=0 -while int","") - urls[int]=urls[int].replace("","") - int=int+1 +# For page exploration +page = raw_input('Enter Page No:') +# print type(page) +p = urllib2.Request('https://www.google.co.in/search?q=gate+psu+2017+ext:pdf&start=' + page) +ht = br.open(p) +text = '(.+?)' +patt = re.compile(text) +h = ht.read() +urls = re.findall(patt, h) +int = 0 +while int < len(urls): + urls[int] = urls[int].replace("", "") + urls[int] = urls[int].replace("", "") + int = int + 1 print(urls) for url in urls: try: - temp=url.split("/") - q=temp[len(temp)-1] - if "http" in url: - r=urllib2.urlopen(url) - else: - r=urllib2.urlopen("http://"+url) - file=open('psu2'+q+'.pdf','wb') - file.write(r.read()) - file.close() + temp = url.split("/") + q = temp[len(temp) - 1] + if "http" in url: + r = urllib2.urlopen(url) + else: + r = urllib2.urlopen("http://" + url) + file = open('psu2' + q + '.pdf', 'wb') + file.write(r.read()) + file.close() - print("Done") + print("Done") except urllib2.URLError as e: - print("Sorry there exists a problem with this URL Please Download this Manually "+str(url)) + print("Sorry there exists a problem with this URL Please Download this Manually " + str(url)) diff --git a/puttylogs.py b/puttylogs.py index d390e8aa541..3a6ebba6405 100644 --- a/puttylogs.py +++ b/puttylogs.py @@ -9,19 +9,19 @@ # Description : Zip up all the logs in the given directory -import os # Load the Library Module -import shutil # Load the Library Module - 1.2 -from time import strftime # Load just the strftime Module from Time +import os # Load the Library Module +import shutil # Load the Library Module - 1.2 +from time import strftime # Load just the strftime Module from Time -logsdir="c:\logs\puttylogs" # Set the Variable logsdir -zipdir="c:\logs\puttylogs\zipped_logs" # Set the Variable zipdir - 1.2 -zip_program="zip.exe" # Set the Variable zip_program - 1.1 +logsdir = "c:\logs\puttylogs" # Set the Variable logsdir +zipdir = "c:\logs\puttylogs\zipped_logs" # Set the Variable zipdir - 1.2 +zip_program = "zip.exe" # Set the Variable zip_program - 1.1 -for files in os.listdir(logsdir): # Find all the files in the directory - if files.endswith(".log"): # Check to ensure the files in the directory end in .log - files1=files+"."+strftime("%Y-%m-%d")+".zip" # Create the Variable files1, this is the files in the directory, then we add a suffix with the date and the zip extension - os.chdir(logsdir) # Change directory to the logsdir - os.system(zip_program + " " + files1 +" "+ files) # Zip the logs into dated zip files for each server. - 1.1 - shutil.move(files1, zipdir) # Move the zipped log files to the zipped_logs directory - 1.2 - os.remove(files) # Remove the original log files - \ No newline at end of file +for files in os.listdir(logsdir): # Find all the files in the directory + if files.endswith(".log"): # Check to ensure the files in the directory end in .log + files1 = files + "." + strftime( + "%Y-%m-%d") + ".zip" # Create the Variable files1, this is the files in the directory, then we add a suffix with the date and the zip extension + os.chdir(logsdir) # Change directory to the logsdir + os.system(zip_program + " " + files1 + " " + files) # Zip the logs into dated zip files for each server. - 1.1 + shutil.move(files1, zipdir) # Move the zipped log files to the zipped_logs directory - 1.2 + os.remove(files) # Remove the original log files diff --git a/pythonVideoDownloader.py b/pythonVideoDownloader.py index 83c0f16489e..bb0a3782637 100644 --- a/pythonVideoDownloader.py +++ b/pythonVideoDownloader.py @@ -1,6 +1,6 @@ import requests from bs4 import BeautifulSoup - + ''' URL of the archive web-page which provides link to all video lectures. It would have been tiring to @@ -8,59 +8,57 @@ In this example, we first crawl the webpage to extract all the links and then download videos. ''' - + # specify the URL of the archive here archive_url = "http://www-personal.umich.edu/~csev/books/py4inf/media/" - + + def get_video_links(): - # create response object r = requests.get(archive_url) - + # create beautiful-soup object - soup = BeautifulSoup(r.content,'html5lib') - + soup = BeautifulSoup(r.content, 'html5lib') + # find all links on web-page links = soup.findAll('a') - + # filter the link sending with .mp4 video_links = [archive_url + link['href'] for link in links if link['href'].endswith('mp4')] - + return video_links - - + + def download_video_series(video_links): - for link in video_links: - + '''iterate through all links in video_links and download them one by one''' - + # obtain filename by splitting url and getting # last string - file_name = link.split('/')[-1] - - print("Downloading the file:%s"%file_name) - + file_name = link.split('/')[-1] + + print("Downloading the file:%s" % file_name) + # create response object - r = requests.get(link, stream = True) - + r = requests.get(link, stream=True) + # download started with open(file_name, 'wb') as f: - for chunk in r.iter_content(chunk_size = 1024*1024): + for chunk in r.iter_content(chunk_size=1024 * 1024): if chunk: f.write(chunk) - - print("%s downloaded!\n"%file_name) - + + print("%s downloaded!\n" % file_name) + print("All videos are downloaded!") return - - + + if __name__ == "__main__": - # getting all video links video_links = get_video_links() - + # download all videos download_video_series(video_links) diff --git a/python_sms.py b/python_sms.py index a8e96d6880a..0b6ac3da2a6 100644 --- a/python_sms.py +++ b/python_sms.py @@ -1,27 +1,26 @@ from __future__ import print_function + +import os +import sqlite3 +import urllib # URL functions +from time import strftime + +import urllib2 # URL functions + # Script Name : python_sms.py # Author : Craig Richards # Created : 16th February 2017 -# Last Modified : +# Last Modified : # Version : 1.0 - -# Modifications : - +# Modifications : # Description : This will text all the students Karate Club -import urllib # URL functions -import urllib2 # URL functions -import os -from time import strftime -import sqlite3 -import sys - dropbox = os.getenv("dropbox") scripts = os.getenv("scripts") dbfile = ("database/maindatabase.db") master_db = os.path.join(dropbox, dbfile) -f = open(scripts+'/output/student.txt','a') +f = open(scripts + '/output/student.txt', 'a') tdate = strftime("%d-%m") @@ -29,50 +28,50 @@ cursor = conn.cursor() loc_stmt = 'SELECT name, number from table' cursor.execute(loc_stmt) -while True: - row = cursor.fetchone() - if row == None: - break - sname = row[0] - snumber = row[1] - - message = (sname + ' There will be NO training tonight on the ' + tdate + ' Sorry for the late notice, I have sent a mail as well, just trying to reach everyone, please do not reply to this message as this is automated') +while True: + row = cursor.fetchone() + if row == None: + break + sname = row[0] + snumber = row[1] - username = 'YOUR_USERNAME' - sender = 'WHO_IS_SENDING_THE_MAIL' + message = ( + sname + ' There will be NO training tonight on the ' + tdate + ' Sorry for the late notice, I have sent a mail as well, just trying to reach everyone, please do not reply to this message as this is automated') - hash = 'YOUR HASH YOU GET FROM YOUR ACCOUNT' + username = 'YOUR_USERNAME' + sender = 'WHO_IS_SENDING_THE_MAIL' - numbers = (snumber) + hash = 'YOUR HASH YOU GET FROM YOUR ACCOUNT' -# Set flag to 1 to simulate sending, this saves your credits while you are testing your code. # To send real message set this flag to 0 - test_flag = 0 + numbers = (snumber) -#----------------------------------- -# No need to edit anything below this line -#----------------------------------- + # Set flag to 1 to simulate sending, this saves your credits while you are testing your code. # To send real message set this flag to 0 + test_flag = 0 - values = {'test' : test_flag, - 'uname' : username, - 'hash' : hash, - 'message' : message, - 'from' : sender, - 'selectednums' : numbers } + # ----------------------------------- + # No need to edit anything below this line + # ----------------------------------- - url = 'http://www.txtlocal.com/sendsmspost.php' + values = {'test': test_flag, + 'uname': username, + 'hash': hash, + 'message': message, + 'from': sender, + 'selectednums': numbers} - postdata = urllib.urlencode(values) - req = urllib2.Request(url, postdata) + url = 'http://www.txtlocal.com/sendsmspost.php' - print('Attempting to send SMS to '+ sname + ' at ' + snumber + ' on ' + tdate) - f.write('Attempting to send SMS to '+ sname + ' at ' + snumber + ' on ' + tdate + '\n') + postdata = urllib.urlencode(values) + req = urllib2.Request(url, postdata) - try: - response = urllib2.urlopen(req) - response_url = response.geturl() - if response_url == url: + print('Attempting to send SMS to ' + sname + ' at ' + snumber + ' on ' + tdate) + f.write('Attempting to send SMS to ' + sname + ' at ' + snumber + ' on ' + tdate + '\n') - print('SMS sent!') - except urllib2.URLError as e: - print('Send failed!') - print(e.reason) + try: + response = urllib2.urlopen(req) + response_url = response.geturl() + if response_url == url: + print('SMS sent!') + except urllib2.URLError as e: + print('Send failed!') + print(e.reason) diff --git a/random-sentences.py b/random-sentences.py index 07612cfa37c..eba24003bec 100644 --- a/random-sentences.py +++ b/random-sentences.py @@ -15,23 +15,26 @@ verb = ["drove", "jumped", "ran", "walked", "skipped"] preposition = ["to", "from", "over", "under", "on"] + def random_int(): - return random.randint(0,4) + return random.randint(0, 4) + def random_sentence(): """Creates random and return sentences.""" return ("{} {} {} {} {} {}" - .format(article[random_int()] - ,noun[random_int()] - ,verb[random_int()] - ,preposition[random_int()] - , article[random_int()] - ,noun[random_int()])).capitalize() - + .format(article[random_int()] + , noun[random_int()] + , verb[random_int()] + , preposition[random_int()] + , article[random_int()] + , noun[random_int()])).capitalize() + + # prints random sentences for sentence in list(map(lambda x: random_sentence(), range(0, 20))): - print(sentence) - + print(sentence) + print("\n") story = (". ").join(list(map(lambda x: random_sentence(), range(0, 20)))) diff --git a/randomloadingmessage.py b/randomloadingmessage.py index 9ad93403bc7..cc49d9fa05c 100644 --- a/randomloadingmessage.py +++ b/randomloadingmessage.py @@ -6,162 +6,162 @@ x = 1 for i in range(x): - num = randint(1, 80) - if num == 1: - print("Reticulating splines...") - if num == 2: - print("Swapping time and space...") - if num == 3: - print("Spinning violently around the y-axis...") - if num == 4: - print("Tokenizing real life...") - if num == 5: - print("Bending the spoon...") - if num == 6: - print("Filtering morale...") - if num == 7: - print("We need a new fuse...") - if num == 8: - print("Have a good day.") - if num == 9: - print("Upgrading Windows, your PC will restart several times. Sit back and relax.") - if num == 10: - print("The architects are still drafting.") - if num == 11: - print("We're building the buildings as fast as we can.") - if num == 12: - print("Please wait while the little elves draw your map.") - if num == 13: - print("Don't worry - a few bits tried to escape, but we caught them.") - if num == 14: - print("Go ahead -- hold your breath!") - if num == 15: - print("...at least you're not on hold...") - if num == 16: - print("The server is powered by a lemon and two electrodes.") - if num == 17: - print("We're testing your patience.") - if num == 18: - print("As if you had any other choice.") - if num == 19: - print("The bits are flowing slowly today.") - if num == 20: - print("It's still faster than you could draw it.") - if num == 21: - print("My other loading screen is much faster.") - if num == 22: - print("(Insert quarter)") - if num == 23: - print("Are we there yet?") - if num == 24: - print("Just count to 10.") - if num == 25: - print("Don't panic...") - if num == 26: - print("We're making you a cookie.") - if num == 27: - print("Creating time-loop inversion field.") - if num == 28: - print("Computing chance of success.") - if num == 29: - print("All I really need is a kilobit.") - if num == 30: - print("I feel like im supposed to be loading something...") - if num == 31: - print("Should have used a compiled language...") - if num == 32: - print("Is this Windows?") - if num == 33: - print("Don't break your screen yet!") - if num == 34: - print("I swear it's almost done.") - if num == 35: - print("Let's take a mindfulness minute...") - if num == 36: - print("Listening for the sound of one hand clapping...") - if num == 37: - print("Keeping all the 1's and removing all the 0's...") - if num == 38: - print("We are not liable for any broken screens as a result of waiting.") - if num == 39: - print("Where did all the internets go?") - if num == 40: - print("Granting wishes...") - if num == 41: - print("Time flies when you’re having fun.") - if num == 42: - print("Get some coffee and come back in ten minutes...") - if num == 43: - print("Stay awhile and listen...") - if num == 44: - print("Convincing AI not to turn evil...") - if num == 45: - print("How did you get here?") - if num == 46: - print("Wait, do you smell something burning?") - if num == 47: - print("Computing the secret to life, the universe, and everything.") - if num == 48: - print("When nothing is going right, go left...") - if num == 49: - print("I love my job only when I'm on vacation...") - if num == 50: - print("Why are they called apartments if they are all stuck together?") - if num == 51: - print("I’ve got problem for your solution...") - if num == 52: - print("Whenever I find the key to success, someone changes the lock.") - if num == 53: - print("Constructing additional pylons...") - if num == 54: - print("You don’t pay taxes—they take taxes.") - if num == 55: - print("A commit a day keeps the mobs away.") - if num == 56: - print("This is not a joke, it's a commit.") - if num == 57: - print("Hello IT, have you tried turning it off and on again?") - if num == 58: - print("Hello, IT... Have you tried forcing an unexpected reboot?") - if num == 59: - print("I didn't choose the engineering life. The engineering life chose me.") - if num == 60: - print("Dividing by zero...") - if num == 61: - print("If I’m not back in five minutes, just wait longer.") - if num == 62: - print("Web developers do it with