├── .github ├── CODE_TEMPLATES │ ├── Snippets.md │ └── Tests.md ├── ISSUE_TEMPLATE │ ├── bug_report.yml │ ├── documentation_update.yml │ └── feature_request.yml ├── PR_Template.md ├── dependabot.yml └── workflows │ ├── auto-comment-on-issue-close.yml │ ├── auto-comment-on-issue.yml │ ├── auto-label.yml │ ├── auto_message_on_pr_open.yml │ ├── ci.yml │ ├── detect-duplicate.yml │ └── directory_writer.yml ├── .gitignore ├── .gitpod.yml ├── .idea ├── PySnippets.iml ├── inspectionProfiles │ ├── Project_Default.xml │ └── profiles_settings.xml ├── misc.xml ├── vcs.xml └── workspace.xml ├── .pre-commit-config.yaml ├── CODE_OF_CONDUCT.md ├── CONTRIBUTING.md ├── DIRECTORY.md ├── LICENSE ├── README.md ├── SECURITY.md ├── Structure.md ├── Tests ├── Dynamic-Programming │ └── test_matrix_chain_multiplication.py ├── GUIinPy │ └── testLogic.py ├── IDT_library │ ├── interactive_decision_tree.py │ ├── sankey_template.html │ ├── test_IDT.py │ ├── titanic_sankey.html │ ├── titanic_tree.html │ └── tree_template.html ├── Performance │ ├── test_functoolslru_cache_AutomaticMemoization.py │ ├── test_memoize.py │ └── test_timer.py ├── Web │ ├── test_get_html.py │ ├── test_get_image.py │ └── test_get_text.py ├── algorithms │ ├── test_adjacency_list.py │ ├── test_adjacency_matrix.py │ ├── test_advanced_encryption_standard.py │ ├── test_astar.py │ ├── test_asymmetric_encryption_algorithm.py │ ├── test_bellman_ford.py │ ├── test_bfs.py │ ├── test_bidirectional_bfs.py │ ├── test_binary_search.py │ ├── test_breadth_first_search.py │ ├── test_btree.py │ ├── test_depth_first_search.py │ ├── test_dfs.py │ ├── test_dijkstra.py │ ├── test_dijkstras.py │ ├── test_elliptic_curve_cryptography.py │ ├── test_fibonacci.py │ ├── test_floyds.py │ ├── test_hashing.py │ ├── test_kruskals.py │ ├── test_prim.py │ ├── test_prims.py │ ├── test_searching_sorting.py │ ├── test_symmetric_encryption_algorithm.py │ ├── test_topological_ordering.py │ └── test_warshalls.py ├── analysis │ └── test_analysis.py ├── database │ ├── test_mongo.py │ └── test_sql.py ├── dictionary │ ├── test_dict_manipulation.py │ └── test_dictionarywithindices.py ├── email_utils │ └── test_email_utils.py ├── files │ ├── test_file_organizer.py │ └── test_file_reader.py ├── greedy-algorithms │ └── test_job_sequencing.py ├── library_snippets │ ├── test_matplotlib_snippet.py │ ├── test_numpy_snippet.py │ ├── test_pandas_snippet.py │ └── test_requests_snippet.py ├── qrcode │ ├── test_generate_qr_code.py │ └── test_scan_qr_code.py ├── strings │ ├── test_list_to_comma_string.py │ ├── test_string_manipulation.py │ └── test_string_manipulation_added.py ├── system │ ├── test_disk_space_checker.py │ ├── test_environment_variable_manager.py │ ├── test_process_manager.py │ ├── test_resource_manager.py │ └── test_temporary_file_handler.py ├── tkinter │ ├── test_dialogs.py │ ├── test_init.py │ ├── test_main.py │ ├── test_styles.py │ ├── test_utils.py │ └── test_widgets.py └── utilities │ ├── test_caching.py │ ├── test_deep_copy.py │ ├── test_flatten.py │ ├── test_retry.py │ └── test_time_execution.py ├── docs └── .gitkeep ├── library_snippets ├── matplotlib_snippet.py ├── numpy_snippet.py ├── pandas_snippet.py └── requests_snippet.py ├── mkdocs.yml ├── pyproject.toml ├── pysnippets ├── API_module │ ├── API_module.md │ ├── __init__.py │ ├── api_requests.py │ ├── path_params.py │ ├── query_params.py │ ├── response_handling.py │ └── test_all.py ├── Asynchronous │ ├── Asynchronous.md │ ├── __init__.py │ ├── advanced_error_handling.py │ ├── advanced_error_handling_continued.py │ ├── async_context_managers.py │ ├── async_generators.py │ ├── async_with_databases.py │ ├── basic_async.py │ ├── concurrency.py │ ├── data_classes.py │ ├── error_handling.py │ ├── event_handling.py │ ├── file_operations.py │ ├── handling_timeouts.py │ ├── http_requests.py │ ├── integrating_sync.py │ ├── performance_monitoring.py │ ├── task_cancellation.py │ ├── testing_async_code.py │ ├── using_locks.py │ ├── using_semaphores.py │ └── websockets.py ├── Bitwise │ ├── Bitwise.md │ ├── __init__.py │ ├── clear_lsb_upto_n.py │ ├── count_bits.py │ ├── find_unique.py │ ├── flip_bit.py │ ├── isolate_right_one.py │ ├── power.py │ ├── swap.py │ └── test_all.py ├── Bot-app │ ├── NLP_bot.md │ ├── __init__.py │ ├── app.py │ └── test_all.py ├── Cipher_algorithms │ ├── Rail_Fence_Cipher.py │ ├── Vigenère_Cipher.py │ ├── __init__.py │ ├── affine_cipher.py │ ├── caesar_cipher.py │ ├── cipher_manager.py │ ├── hill_cipher.py │ ├── playfair_cipher.py │ └── test_cipher_manager.py ├── Communication │ ├── __init__.py │ ├── communication.md │ ├── send_email.py │ └── test_send_email.py ├── Complex_number │ ├── Complex Number.md │ ├── __init__.py │ ├── complex_number.py │ ├── exceptions.py │ ├── logger_config.py │ ├── operations.py │ ├── test_all.py │ ├── test_complex_number.py │ ├── test_operations.py │ ├── test_utils.py │ └── utils.py ├── Computer_vision │ ├── README.md │ ├── __init__.py │ ├── depth_estimation.py │ ├── edge_detection.py │ ├── face_recognition.py │ ├── feature_matching.py │ ├── image_classification.py │ ├── image_enhancement.py │ ├── image_segmentation.py │ ├── object_detection.py │ ├── optical_flow.py │ ├── test_depth_estimation.py │ ├── test_edge_detection.py │ ├── test_face_recognition.py │ ├── test_feature_matching.py │ ├── test_image_classification.py │ ├── test_image_enhancement.py │ ├── test_image_segmentation.py │ ├── test_object_detection.py │ ├── test_optical_flow.py │ ├── test_video_tracking.py │ └── video_tracking.py ├── DYnamic_classes │ ├── Dynamic_class.py │ ├── Property.py │ ├── __init__.py │ ├── attribute.py │ ├── method.py │ ├── test_Dynamic_class.py │ ├── test_all.py │ ├── test_attribute.py │ ├── test_method.py │ ├── test_property.py │ ├── test_type.py │ └── type.py ├── Data_preprocessing │ ├── __init__.py │ ├── data_cleaning.py │ ├── data_transformation.py │ ├── encoding.py │ ├── feature_scaling.py │ ├── missing_values.py │ ├── outlier_detection.py │ ├── test_data_cleaning.py │ ├── test_data_transformation.py │ ├── test_encoding.py │ ├── test_feature_scaling.py │ ├── test_missing_values.py │ └── test_outlier_detection.py ├── Dynamic Programming │ ├── Longest_path_in_DAG.py │ ├── Two-City-Scheduling-3D-DP.md │ ├── __init__.py │ ├── approaches.md │ ├── coin_change.py │ ├── dynamic-programming-optimizations.md │ ├── edit_distance.py │ ├── how-to-identify.md │ ├── longest_common_subsequence.md │ ├── longest_common_subsequence.py │ ├── matrix_chain_multiplication.py │ ├── maximum_subarray_sum.py │ ├── practice-problems-different-patterns.md │ ├── test_all.py │ ├── two_city_scheduling.py │ └── unique_paths.py ├── Files │ ├── __init__.py │ ├── binary_file_appender.py │ ├── binary_file_data_finder.py │ ├── binary_file_data_replacer.py │ ├── binary_file_reader.py │ ├── binary_file_writer.py │ ├── file_organizer.py │ ├── file_reader.py │ ├── files.md │ └── sample_data.pkl ├── GUIinPy │ ├── Gui.py │ ├── __init__.py │ ├── components.py │ ├── dialogs.py │ ├── guiLogic.py │ ├── menus.py │ └── readme.md ├── Hashing │ ├── Hashing.md │ ├── Hashing.py │ ├── __init__.py │ ├── bcrypt_hasher.py │ ├── hmac_generator.py │ ├── md5_hasher.py │ ├── pbkdf2_hasher.py │ ├── sha3_hasher.py │ ├── test_bcrypt_hasher.py │ ├── test_hashing.py │ ├── test_hmac_generator.py │ ├── test_md5_hasher.py │ ├── test_pbkdf2_hasher.py │ └── test_sha3_hasher.py ├── IDT_library │ ├── README.md │ ├── __init__.py │ ├── interactive_decision_tree.py │ ├── sankey_template.html │ ├── test.ipynb │ ├── test.py │ ├── titanic-sankey.html │ ├── titanic-tree.html │ └── tree_template.html ├── Image_Processing │ ├── ImageAugmentation.md │ ├── __init__.py │ ├── image_augmentation_module.py │ ├── image_processing.py │ ├── test_image.webp │ ├── test_image_processing.py │ └── usage.py ├── LinkedList │ ├── Circular_Linked_List.py │ ├── Doubly_Linked_List.py │ ├── LinkedList.md │ ├── Singly_Linked_List.py │ ├── _init_.py │ └── test_linked_lists.py ├── ML_snippets │ ├── _init__.py │ ├── decision_tree.py │ ├── knearest_neighbors.py │ ├── linear_regression.py │ ├── random_forest.py │ ├── svm.py │ ├── test_decision_tree.py │ ├── test_knearest_neighbors.py │ ├── test_linear_regression.py │ ├── test_random_forest.py │ └── test_svm.py ├── Mathematics │ ├── Euler Function │ │ ├── euler.py │ │ └── test_euler.py │ ├── Jacobain _Function │ │ ├── jacobian.py │ │ └── test_jacobian.py │ ├── complex_number_operations.py │ ├── determinant.py │ ├── fibonacci_sequence.py │ ├── matrix_operations.py │ ├── pascals_triangle.py │ ├── probability.py │ ├── test_all.py │ ├── test_prob.py │ └── vector_operations.py ├── Memoisation │ ├── Memoization.md │ ├── __init__.py │ ├── class_based_memoization.py │ ├── decorator.py │ ├── factorial.py │ ├── fibonacci.py │ ├── knapsack.py │ ├── lcs.py │ ├── test_all.py │ ├── test_class_based_memoization.py │ ├── test_decorator.py │ ├── test_factorial.py │ ├── test_fibonacci.py │ ├── test_knapsack.py │ └── test_lcs.py ├── NLP │ ├── NLP.md │ ├── __init__.py │ ├── cosine_similarity_texts.py │ ├── extract_entities.py │ ├── generate_text.py │ ├── lda_topic_modeling.py │ ├── lemmatize_text.py │ ├── preprocess_text.py │ ├── stem_text.py │ ├── test_all.py │ ├── tfidf_vectorize.py │ ├── tokenize_text.py │ ├── train_text_classifier.py │ └── word2vec_similarity.py ├── Numbers │ ├── __init__.py │ ├── binary_to_decimal.py │ ├── decimal_to-binary.py │ ├── decimal_to_hex.py │ ├── format_to_2_decimal.py │ ├── hex_to_decimal.py │ ├── number_formatting.py │ ├── numbers.md │ ├── octal_to_decimal.py │ ├── pad_with_zeros.py │ ├── percentage_format.py │ ├── prime_factorization.py │ └── test_numbers.py ├── PDF_Manipulation │ ├── PDF_Manipulation.md │ ├── __init__.py │ ├── pdf_manipulator.py │ ├── pdf_merger.py │ ├── pdf_reader.py │ ├── pdf_security.py │ ├── pdf_splitter.py │ └── test_pdf_manipulation.py ├── Path_Algoithms │ ├── Path.md │ ├── __init__.py │ ├── a_star.py │ ├── data_classes.py │ ├── dijkstra.py │ ├── gui.py │ ├── logger_config.py │ ├── test_a_star.py │ ├── test_all.py │ ├── test_dijkstra.py │ └── utils.py ├── Performance │ ├── __init__.py │ ├── memoize.py │ ├── performance.md │ └── timer.py ├── Recursion │ ├── Recursoin.md │ ├── __init__.py │ ├── binary_search.py │ ├── factorial.py │ ├── fibonacci.py │ ├── merge_sort.py │ ├── permutations.py │ ├── quick_sort.py │ ├── subsets.py │ ├── test_all.py │ └── tower_of_hanoi.py ├── Scrubs │ ├── README.md │ ├── __init__.py │ ├── backup.py │ ├── clean.py │ ├── clip.py │ ├── compress.py │ ├── dummies.py │ ├── pipeline.py │ └── utils.py ├── Searching │ ├── Exponential_search.py │ ├── Fibonacci_search.py │ ├── Interpolation.py │ ├── Jump_search.py │ ├── Linear_Search.py │ ├── Ternary_search.py │ ├── __init__.py │ ├── iterative_binary_search.py │ ├── recursive_binary_search.py │ ├── searching.md │ └── test_searching.py ├── Sorting │ ├── __init__.py │ ├── bubble_sort.py │ ├── bubble_sort_test.py │ ├── bucket_sort.py │ ├── bucket_sort_test.py │ ├── cocktail_shaker_sort.py │ ├── cocktail_shaker_sort_test.py │ ├── cocktail_sort.py │ ├── cocktail_sort_test.py │ ├── counting_sort.py │ ├── counting_sort_test.py │ ├── heap_sort.py │ ├── heap_sort_test.py │ ├── insertion_sort.py │ ├── insertion_sort_test.py │ ├── merge_sort.py │ ├── merge_sort_test.py │ ├── quick_sort.py │ ├── quick_sort_test.py │ ├── radiix_sort.py │ ├── radix_sort.py │ ├── radix_sort_test.py │ ├── selection_sort.py │ ├── sorting.md │ ├── test_all.py │ ├── topological_sort.py │ └── topological_sort_test.py ├── SpecialNumbers │ ├── Abundant.py │ ├── Armstrong.py │ ├── Automorphic.py │ ├── Deficient.py │ ├── Happy.py │ ├── Kaprekar.py │ ├── Neon.py │ ├── Palindrome.py │ ├── PerfectNumber.py │ ├── Strong.py │ ├── __init__.py │ └── logging_config.py ├── Strings │ ├── Algorithms.md │ ├── Algoritms.py │ ├── Capitalization.py │ ├── Strings.md │ ├── __init__.py │ ├── anagram_detector.py │ ├── basic_conversion.py │ ├── dict_conversion.py │ ├── inflect_conversion.py │ ├── levenshtein_distance.py │ ├── list_to_comma_string.py │ ├── palindrome_checker.py │ ├── regex.py │ ├── regex_utils.py │ ├── snake_to_camel.py │ ├── string_formatter.py │ ├── string_manipulation.py │ ├── string_normalizer.py │ ├── string_statistics.py │ ├── string_utils.py │ ├── template_engine.py │ ├── test_anagram_detector.py │ ├── test_capitalization.py │ ├── test_conversion.py │ ├── test_levenshtein_distance.py │ ├── test_snake_to_camel.py │ ├── test_string_normalizer.py │ ├── test_template_engine.py │ └── word_frequency_analyzer.py ├── Task Planner │ ├── Readme.md │ └── task_planner.py ├── Traversal │ ├── Traversal.md │ ├── __init__.py │ ├── bfs.py │ ├── data_classes.py │ ├── dfs.py │ ├── iterative_deepening.py │ ├── logger_config.py │ ├── parallel_bfs.py │ └── test_all.py ├── Tries │ ├── __init__.py │ ├── trie.md │ └── tries.py ├── Visualization │ ├── Annonated_Heatmap.py │ ├── Boxplot_with_notches.py │ ├── Circular_bar.py │ ├── Density_Shade.py │ ├── Dual_axis_line.py │ ├── Filled_area.py │ ├── Heatmap_cluster.py │ ├── Scatter_regression.py │ ├── Stacked_Bar_Chart.py │ ├── ThreeD_surface.py │ ├── Violin_split.py │ ├── Visualization.md │ ├── __init__.py │ └── test_all.py ├── Web │ ├── __init__.py │ ├── get_html.py │ ├── get_image.py │ ├── get_text.py │ └── web.md ├── __init__.py ├── algorithms │ ├── Encryption algorithm │ │ ├── advanced_encryption_standard.py │ │ ├── asymmetric_encryption_algorithm.py │ │ ├── elliptic_curve_cryptography.py │ │ ├── hashing.py │ │ └── symmetric_encryption_algorithm.py │ ├── __init__.py │ ├── adjacency_list.py │ ├── adjacency_matrix.py │ ├── algorithms.md │ ├── astar.py │ ├── bellman_ford.py │ ├── bfs.py │ ├── bidirectional_bfs.py │ ├── binary_search.py │ ├── breadth_first_search.py │ ├── btree.py │ ├── depth_first_search.py │ ├── dfs.py │ ├── dijkstra.py │ ├── dijkstras.py │ ├── fibonacci.py │ ├── floyds.py │ ├── kruskals.py │ ├── prim.py │ ├── prims.py │ ├── topological_ordering.py │ └── warshalls.py ├── analysis │ ├── DataUtils.py │ ├── ModelUtils.py │ ├── __init__.py │ └── analysis.md ├── clipboard_online │ ├── __init__.py │ ├── package │ │ ├── __init__.py │ │ ├── clip.py │ │ ├── create.py │ │ ├── display.py │ │ ├── password.py │ │ ├── scrap │ │ │ └── grab.py │ │ ├── show.py │ │ ├── stash │ │ │ ├── __init__.py │ │ │ └── test.py │ │ ├── test.py │ │ └── write.py │ ├── test_clip.py │ ├── test_display.py │ ├── test_scrap.py │ ├── test_show.py │ └── test_write.py ├── database │ ├── __init__.py │ ├── database.md │ ├── mongodb │ │ ├── __init__.py │ │ ├── mongo_connection_manager.py │ │ ├── mongo_document_insertion.py │ │ ├── mongo_document_query.py │ │ ├── mongo_document_update.py │ │ └── mongo_index_management.py │ └── mysql │ │ ├── __init__.py │ │ ├── sql_connection_manager.py │ │ ├── sql_data_insertion.py │ │ ├── sql_execute_query.py │ │ ├── sql_schema_creation.py │ │ └── sql_transaction_handling.py ├── date_utils │ ├── __init__.py │ ├── date_utils.md │ └── date_utils.py ├── dictionary │ ├── __init__.py │ ├── dict_manipulation.md │ ├── dict_manipulation.py │ ├── dictionarywithindices.md │ └── dictionarywithindices.py ├── documentation.md ├── email_utils │ ├── Email Utils.md │ ├── __init__.py │ ├── bulk.py │ ├── client.py │ ├── exceptions.py │ └── requirements.txt ├── encryption │ ├── __init__.py │ ├── encryption.md │ ├── encryption.py │ ├── test.txt │ └── test_encryption.py ├── graphing │ ├── __init__.py │ ├── advanced_graphing.py │ ├── graphing-example.py │ ├── graphing.md │ └── test_advanced_graphing.py ├── greedyalgorithms │ └── job_sequencing.py ├── list │ ├── __init__.py │ ├── list_manipulation.md │ ├── list_manipulation.py │ └── test_list_manipulation.py ├── models │ ├── CV_means.py │ ├── Catboost.py │ ├── Ensemble.py │ ├── Grid_search.py │ ├── KMeans.py │ ├── LightGBM.py │ ├── Linear_regression.py │ ├── Logistic_regression.py │ ├── XGB.py │ └── __init__.py ├── password_generator │ ├── __init__.py │ ├── data_classes.py │ ├── hasher.py │ ├── logging_config.py │ ├── password_generator.py │ ├── test_all.py │ ├── test_hasher.py │ ├── test_password_generator.py │ ├── test_validators.py │ └── validators.py ├── qrcode │ ├── __init__.py │ ├── generate_qr_code.py │ ├── qrcode.md │ └── scan_qr_code.py ├── stats │ ├── __init__.py │ ├── coeffecient_variation.py │ ├── correlation.py │ ├── iqr.py │ ├── kurtosis.py │ ├── mean_median_mode.py │ ├── quantile.py │ ├── skewness.py │ ├── standard_deviation.py │ ├── stats.md │ ├── variance.py │ └── z_score_normalization.py ├── system │ ├── __init__.py │ ├── cpu_memory_monitor.py │ ├── disk_space_checker.py │ ├── env_var_manager.py │ ├── environment_variable_manager.py │ ├── process_manager.py │ ├── system.md │ ├── system_resource_monitor.py │ ├── temp_file_handler.py │ ├── test_all.py │ ├── test_cpu_memory_monitor.py │ ├── test_disk_space_checker.py │ ├── test_env_var_manager.py │ ├── test_process_manager.py │ └── test_temp_file_handler.py ├── testcase1.py ├── testcase2.py ├── testcase3.py ├── testcase4.py ├── testcase5.py ├── testcase6.py ├── testcase7.py ├── testcase8.py ├── tkinter │ ├── __init__.py │ ├── dialogs.py │ ├── main.py │ ├── styles.py │ ├── utils.py │ └── widgets.py ├── utilities │ ├── __init__.py │ ├── advanced_logger.py │ ├── caching.md │ ├── caching.py │ ├── config_loader.py │ ├── deep_copy.md │ ├── deep_copy.py │ ├── email_sender.py │ ├── flatten.py │ ├── flatten_nested_list.md │ ├── json_serializer.py │ ├── rate_limiter.py │ ├── retry.py │ ├── timer.py │ └── utilities.md └── webscrape │ ├── __init__.py │ ├── scraper.py │ ├── test_scraper.py │ └── webscrape.md ├── scripts ├── build.sh ├── build_directory_md.py ├── install.sh └── validate_filenames.py ├── setup.py └── stargazers ├── .eslintrc ├── .gitignore ├── .prettierrc ├── out └── main.mp4 ├── package-lock.json ├── package.json ├── remotion.config.ts ├── src ├── Content.tsx ├── Main.tsx ├── Root.tsx ├── cache.ts ├── fetch │ ├── fetch-data.ts │ ├── via-graphql.ts │ └── via-rest.ts ├── gh-styles.css ├── index.ts ├── repo-header.tsx ├── utils.ts └── wait-for-no-input.ts └── tsconfig.json /.github/CODE_TEMPLATES/Snippets.md: -------------------------------------------------------------------------------- 1 | ## Snippets Template 2 | 3 | ```python 4 | # .py 5 | 6 | def (): 7 | """ 8 | 9 | 10 | Args: 11 | (): 12 | 13 | Returns: 14 | : 15 | 16 | Example: 17 | >>> () 18 | 19 | """ 20 | # Function logic here 21 | 22 | # Example usage 23 | if __name__ == "__main__": 24 | # Example usage of the function 25 | result = () 26 | print(result) 27 | ``` 28 | -------------------------------------------------------------------------------- /.github/CODE_TEMPLATES/Tests.md: -------------------------------------------------------------------------------- 1 | ## Tests Template 2 | 3 | ```python 4 | import unittest 5 | from snippets.. import 6 | 7 | class Test(unittest.TestCase): 8 | 9 | def test_case_1(self): 10 | # Test case for normal behavior 11 | self.assertEqual((), ) 12 | 13 | def test_case_2(self): 14 | # Test case for edge behavior 15 | self.assertEqual((), ) 16 | 17 | def test_case_invalid(self): 18 | # Test case for invalid input 19 | with self.assertRaises(): 20 | () 21 | 22 | if __name__ == '__main__': 23 | unittest.main() 24 | ``` 25 | -------------------------------------------------------------------------------- /.github/dependabot.yml: -------------------------------------------------------------------------------- 1 | # Keep GitHub Actions up to date with Dependabot... 2 | # https://docs.github.com/en/code-security/dependabot/working-with-dependabot/keeping-your-actions-up-to-date-with-dependabot 3 | version: 2 4 | updates: 5 | - package-ecosystem: "github-actions" 6 | directory: "/" 7 | schedule: 8 | interval: "daily" 9 | -------------------------------------------------------------------------------- /.github/workflows/ci.yml: -------------------------------------------------------------------------------- 1 | name: ci 2 | on: 3 | push: 4 | branches: 5 | - master 6 | - main 7 | permissions: 8 | contents: write 9 | jobs: 10 | deploy: 11 | runs-on: ubuntu-latest 12 | steps: 13 | - uses: actions/checkout@v4 14 | - name: Ensure docs directory exists 15 | run: | 16 | mkdir -p docs 17 | - name: Configure Git Credentials 18 | run: | 19 | git config --global user.name "$GITHUB_ACTOR" 20 | git config --global user.email "$GITHUB_ACTOR@users.noreply.github.com" 21 | - uses: actions/setup-python@v5 22 | with: 23 | python-version: 3.x 24 | - run: echo "cache_id=$(date --utc '+%V')" >> $GITHUB_ENV 25 | - uses: actions/cache@v4 26 | with: 27 | key: mkdocs-material-${{ env.cache_id }} 28 | path: .cache 29 | restore-keys: | 30 | mkdocs-material- 31 | - run: pip install mkdocs-material 32 | - run: mkdocs gh-deploy --force 33 | -------------------------------------------------------------------------------- /.github/workflows/detect-duplicate.yml: -------------------------------------------------------------------------------- 1 | name: Duplicate Issue Detection 2 | 3 | on: 4 | issues: 5 | types: [opened] 6 | 7 | jobs: 8 | detect-duplicate: 9 | runs-on: ubuntu-latest 10 | 11 | steps: 12 | - name: Check out the repository 13 | uses: actions/checkout@v4 14 | 15 | - name: Run Duplicate Issue Checker 16 | uses: ahmadnassri/action-similar-issue@v1 17 | id: duplicate-check 18 | with: 19 | repo-token: ${{ secrets.GITHUB_TOKEN }} 20 | min-confidence: 0.8 # Confidence level for similarity (80%) 21 | 22 | - name: Add Duplicate Label 23 | if: steps.duplicate-check.outputs.similar == 'true' 24 | run: | 25 | gh issue edit ${{ github.event.issue.number }} --add-label "duplicate" 26 | 27 | - name: Handle Duplicate Issues 28 | if: steps.duplicate-check.outputs.similar == 'true' 29 | run: | 30 | gh issue close ${{ github.event.issue.number }} -c "Duplicate issue detected. Please refer to #${{ steps.duplicate-check.outputs.duplicate_issue_number }}." 31 | -------------------------------------------------------------------------------- /.github/workflows/directory_writer.yml: -------------------------------------------------------------------------------- 1 | # The objective of this GitHub Action is to update the DIRECTORY.md file (if needed) 2 | # when doing a git push 3 | name: directory_writer 4 | on: [push] 5 | jobs: 6 | build: 7 | runs-on: ubuntu-latest 8 | steps: 9 | - uses: actions/checkout@v4 10 | with: 11 | fetch-depth: 0 12 | - uses: actions/setup-python@v5 13 | with: 14 | python-version: 3.x 15 | - name: Write DIRECTORY.md 16 | run: | 17 | scripts/build_directory_md.py 2>&1 | tee DIRECTORY.md 18 | git config --global user.name "$GITHUB_ACTOR" 19 | git config --global user.email "$GITHUB_ACTOR@users.noreply.github.com" 20 | git remote set-url origin https://x-access-token:${{ secrets.GITHUB_TOKEN }}@github.com/$GITHUB_REPOSITORY 21 | - name: Update DIRECTORY.md 22 | run: | 23 | git add DIRECTORY.md 24 | git commit -am "updating DIRECTORY.md" || true 25 | git push --force origin HEAD:$GITHUB_REF || true 26 | -------------------------------------------------------------------------------- /.gitpod.yml: -------------------------------------------------------------------------------- 1 | tasks: 2 | - init: pip3 install -r ./requirements.txt 3 | -------------------------------------------------------------------------------- /.idea/PySnippets.iml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 7 | 8 | 10 | -------------------------------------------------------------------------------- /.idea/inspectionProfiles/Project_Default.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 13 | -------------------------------------------------------------------------------- /.idea/inspectionProfiles/profiles_settings.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 6 | -------------------------------------------------------------------------------- /.idea/misc.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 6 | 7 | -------------------------------------------------------------------------------- /.idea/vcs.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | -------------------------------------------------------------------------------- /DIRECTORY.md: -------------------------------------------------------------------------------- 1 | /home/runner/work/_temp/0d348b40-ee10-4617-a82a-a9b8b7f1343f.sh: line 1: scripts/build_directory_md.py: Permission denied 2 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | MIT License 2 | 3 | Copyright (c) 2024 UTSAV SINGHAL 4 | 5 | Permission is hereby granted, free of charge, to any person obtaining a copy 6 | of this software and associated documentation files (the "Software"), to deal 7 | in the Software without restriction, including without limitation the rights 8 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 9 | copies of the Software, and to permit persons to whom the Software is 10 | furnished to do so, subject to the following conditions: 11 | 12 | The above copyright notice and this permission notice shall be included in all 13 | copies or substantial portions of the Software. 14 | 15 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 16 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 17 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 18 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 19 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 20 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE 21 | SOFTWARE. 22 | -------------------------------------------------------------------------------- /Tests/Dynamic-Programming/test_matrix_chain_multiplication.py: -------------------------------------------------------------------------------- 1 | import unittest 2 | from pysnippets.Dynamic Programming.matrix_chain_multiplication import matrix_multiplication 3 | 4 | class TestMatrixChainMultiplication(unittest.TestCase): 5 | 6 | def test_matrix_multiplication_case1(self): 7 | arr = [10, 20, 30, 40, 50] 8 | self.assertEqual(matrix_multiplication(arr, len(arr)), 38000) 9 | 10 | def test_matrix_multiplication_case2(self): 11 | arr = [10, 20, 30] 12 | self.assertEqual(matrix_multiplication(arr, len(arr)), 6000) 13 | 14 | def test_matrix_multiplication_case3(self): 15 | arr = [40, 20, 30, 10, 30] 16 | self.assertEqual(matrix_multiplication(arr, len(arr)), 26000) 17 | 18 | def test_matrix_multiplication_case4(self): 19 | arr = [10, 20, 30] 20 | self.assertEqual(matrix_multiplication(arr, len(arr)), 6000) 21 | 22 | if __name__ == "__main__": 23 | unittest.main() 24 | -------------------------------------------------------------------------------- /Tests/GUIinPy/testLogic.py: -------------------------------------------------------------------------------- 1 | import unittest 2 | from pysnippets.GUIinPy.components import SomeComponent 3 | from pysnippets.GUIinPy.menus import SomeMenu 4 | from pysnippets.GUIinPy.dialogs import SomeDialog 5 | 6 | class TestGUIComponents(unittest.TestCase): 7 | def test_component_functionality(self): 8 | comp = SomeComponent() 9 | self.assertTrue(comp.some_method()) # Assuming some_method returns True on success 10 | 11 | def test_menu_functionality(self): 12 | menu = SomeMenu() 13 | self.assertEqual(menu.some_action(), "Expected Result") # Assuming some_action returns a result 14 | 15 | def test_dialog_functionality(self): 16 | dialog = SomeDialog() 17 | self.assertFalse(dialog.some_check()) # Assuming some_check returns False on failure 18 | 19 | if __name__ == '__main__': 20 | unittest.main() 21 | -------------------------------------------------------------------------------- /Tests/Performance/test_functoolslru_cache_AutomaticMemoization.py: -------------------------------------------------------------------------------- 1 | 2 | import unittest 3 | from functoolslru_cache_AutomaticMemoization import fibonacci 4 | 5 | class TestFibonacciMemoization(unittest.TestCase): 6 | def test_fibonacci(self): 7 | self.assertEqual(fibonacci(0), 0) 8 | self.assertEqual(fibonacci(1), 1) 9 | self.assertEqual(fibonacci(10), 55) 10 | self.assertEqual(fibonacci(20), 6765) 11 | 12 | if __name__ == '__main__': 13 | unittest.main() 14 | -------------------------------------------------------------------------------- /Tests/algorithms/test_adjacency_matrix.py: -------------------------------------------------------------------------------- 1 | import unittest 2 | from pysnippets.algorithms.adjacency_matrix import create_graph 3 | 4 | class TestGraphAdjacency(unittest.TestCase): 5 | 6 | def test_create_graph(self): 7 | no_of_nodes = 5 8 | adj = [[0] * no_of_nodes for _ in range(no_of_nodes)] 9 | neighbors_info = { 10 | 0: [1, 2], 11 | 1: [0, 3], 12 | 2: [0, 3], 13 | 3: [2, 1, 4], 14 | 4: [3] 15 | } 16 | create_graph(adj, no_of_nodes, neighbors_info) 17 | 18 | # Expected adjacency matrix based on the hardcoded input 19 | expected_adj = [ 20 | [0, 1, 1, 0, 0], 21 | [1, 0, 0, 1, 0], 22 | [1, 0, 0, 1, 0], 23 | [0, 1, 1, 0, 1], 24 | [0, 0, 0, 1, 0] 25 | ] 26 | 27 | self.assertEqual(adj, expected_adj) 28 | 29 | def test_empty_graph(self): 30 | no_of_nodes = 0 31 | adj = [] 32 | neighbors_info = {} 33 | create_graph(adj, no_of_nodes, neighbors_info) 34 | expected_adj = [] 35 | self.assertEqual(adj, expected_adj) 36 | 37 | if __name__ == "__main__": 38 | unittest.main() 39 | -------------------------------------------------------------------------------- /Tests/algorithms/test_astar.py: -------------------------------------------------------------------------------- 1 | import unittest 2 | from pysnippets.algorithms.astar import astar 3 | 4 | class TestAStarAlgorithm(unittest.TestCase): 5 | def setUp(self): 6 | self.graph = { 7 | 'A': {'B': 1, 'C': 3}, 8 | 'B': {'A': 1, 'C': 3, 'D': 6}, 9 | 'C': {'A': 3, 'B': 3, 'D': 4}, 10 | 'D': {'B': 6, 'C': 4} 11 | } 12 | self.heuristics = { 13 | 'A': 7, 14 | 'B': 6, 15 | 'C': 2, 16 | 'D': 1 17 | } 18 | 19 | def test_astar_algorithm(self): 20 | path = astar(self.graph, self.heuristics, 'A', 'D') 21 | expected_path = ['A', 'C', 'D'] 22 | self.assertEqual(path, expected_path) 23 | 24 | def test_unreachable_destination(self): 25 | path = astar(self.graph, self.heuristics, 'A', 'Z') # Non-existent node 'Z' 26 | self.assertIsNone(path) 27 | 28 | if __name__ == '__main__': 29 | unittest.main() -------------------------------------------------------------------------------- /Tests/algorithms/test_bellman_ford.py: -------------------------------------------------------------------------------- 1 | import unittest 2 | from pysnippets.algorithms.bellman_ford import Graph 3 | 4 | class TestBellmanFordAlgorithm(unittest.TestCase): 5 | def setUp(self): 6 | self.graph = { 7 | 'A': {'B': 1, 'C': 4}, 8 | 'B': {'C': -3, 'D': 2}, 9 | 'C': {'D': 3}, 10 | 'D': {} 11 | } 12 | 13 | def test_bellman_ford_algorithm(self): 14 | distances, predecessors = Graph.bellman_ford(self.graph, 'A') 15 | expected_distances = { 16 | 'A': 0, 17 | 'B': 1, 18 | 'C': -2, 19 | 'D': 0 20 | } 21 | expected_predecessors = { 22 | 'A': None, 23 | 'B': 'A', 24 | 'C': 'B', 25 | 'D': 'B' 26 | } 27 | self.assertEqual(distances, expected_distances) 28 | self.assertEqual(predecessors, expected_predecessors) 29 | 30 | def test_negative_cycle(self): 31 | self.graph['C']['A'] = -5 # Introducing a negative cycle 32 | with self.assertRaises(ValueError): 33 | Graph.bellman_ford(self.graph, 'A') 34 | 35 | if __name__ == '__main__': 36 | unittest.main() -------------------------------------------------------------------------------- /Tests/algorithms/test_bfs.py: -------------------------------------------------------------------------------- 1 | import unittest 2 | from pysnippets.algorithms.bfs import bfs 3 | 4 | class TestBFSAlgorithm(unittest.TestCase): 5 | def setUp(self): 6 | self.graph = { 7 | 'A': ['B', 'C'], 8 | 'B': ['A', 'C', 'D'], 9 | 'C': ['A', 'B', 'D'], 10 | 'D': ['B', 'C'] 11 | } 12 | 13 | def test_bfs_algorithm(self): 14 | bfs_result = bfs(self.graph, 'A') 15 | expected_bfs_result = ['A', 'B', 'C', 'D'] 16 | self.assertEqual(bfs_result, expected_bfs_result) 17 | 18 | def test_single_node(self): 19 | graph = {'A': []} 20 | bfs_result = bfs(graph, 'A') 21 | expected_bfs_result = ['A'] 22 | self.assertEqual(bfs_result, expected_bfs_result) 23 | 24 | if __name__ == '__main__': 25 | unittest.main() 26 | -------------------------------------------------------------------------------- /Tests/algorithms/test_binary_search.py: -------------------------------------------------------------------------------- 1 | import unittest 2 | from pysnippets.algorithms.binary_search import binary_search 3 | 4 | class TestBinarySearch(unittest.TestCase): 5 | 6 | def test_case_1(self): 7 | # Test case for normal behavior 8 | self.assertEqual(binary_search([1, 2, 3, 4, 5], 3), 2) 9 | 10 | def test_case_2(self): 11 | # Test case when element is not present 12 | self.assertEqual(binary_search([1, 2, 3, 4, 5], 6), -1) 13 | 14 | def test_case_invalid(self): 15 | # Test case for invalid input (empty array) 16 | self.assertEqual(binary_search([], 1), -1) 17 | 18 | def test_repeated_elements(self): 19 | self.assertEqual(binary_search([1, 2, 2, 2, 3], 2), 2) 20 | 21 | if __name__ == '__main__': 22 | unittest.main() 23 | -------------------------------------------------------------------------------- /Tests/algorithms/test_breadth_first_search.py: -------------------------------------------------------------------------------- 1 | import unittest 2 | from pysnippets.algorithms.breadth_first_search import bfs 3 | 4 | class TestBFS(unittest.TestCase): 5 | 6 | def test_connected_graph(self): 7 | # Test case for normal behavior on a connected graph 8 | graph = { 9 | 'A': ['B', 'C'], 10 | 'B': ['A', 'D'], 11 | 'C': ['A', 'D'], 12 | 'D': ['B', 'C'] 13 | } 14 | self.assertEqual(bfs(graph, 'A'), ['A', 'B', 'C', 'D']) # Order may vary 15 | 16 | def test_disconnected_graph(self): 17 | # Test case for a disconnected graph 18 | graph = { 19 | 'A': ['B'], 20 | 'B': ['A'], 21 | 'C': ['D'], 22 | 'D': ['C'] 23 | } 24 | self.assertEqual(bfs(graph, 'A'), ['A', 'B']) # Only reachable nodes 25 | 26 | def test_empty_graph(self): 27 | # Test case for an empty graph 28 | graph = {} 29 | self.assertEqual(bfs(graph, 'A'), []) # Should handle gracefully 30 | 31 | if __name__ == '__main__': 32 | unittest.main() 33 | -------------------------------------------------------------------------------- /Tests/algorithms/test_dfs.py: -------------------------------------------------------------------------------- 1 | import unittest 2 | from pysnippets.algorithms.dfs import dfs # Assuming dfs is implemented in this module 3 | 4 | class TestDFSAlgorithm(unittest.TestCase): 5 | def setUp(self): 6 | self.graph = { 7 | 'A': ['B', 'C'], 8 | 'B': ['A', 'C', 'D'], 9 | 'C': ['A', 'B', 'D'], 10 | 'D': ['B', 'C'] 11 | } 12 | 13 | def test_dfs_algorithm(self): 14 | visited = dfs(self.graph, 'A') 15 | expected_visited = ['A', 'B', 'C', 'D'] # Adjust this based on your DFS implementation 16 | self.assertEqual(visited, expected_visited) 17 | 18 | if __name__ == '__main__': 19 | unittest.main() 20 | -------------------------------------------------------------------------------- /Tests/algorithms/test_dijkstras.py: -------------------------------------------------------------------------------- 1 | import unittest 2 | from pysnippets.algorithms.dijkstras import dijkstra 3 | 4 | class TestDijkstrasAlgorithm(unittest.TestCase): 5 | def setUp(self): 6 | self.graph = { 7 | 'A': {'B': 1, 'C': 3}, 8 | 'B': {'A': 1, 'C': 3, 'D': 6}, 9 | 'C': {'A': 3, 'B': 3, 'D': 4}, 10 | 'D': {'B': 6, 'C': 4} 11 | } 12 | 13 | def test_dijkstras_algorithm(self): 14 | distances, previous_nodes = dijkstra(self.graph, 'A') 15 | expected_distances = { 16 | 'A': 0, 17 | 'B': 1, 18 | 'C': 3, 19 | 'D': 7 20 | } 21 | expected_previous_nodes = { 22 | 'A': None, 23 | 'B': 'A', 24 | 'C': 'A', 25 | 'D': 'C' 26 | } 27 | self.assertEqual(distances, expected_distances) 28 | self.assertEqual(previous_nodes, expected_previous_nodes) 29 | 30 | if __name__ == '__main__': 31 | unittest.main() -------------------------------------------------------------------------------- /Tests/algorithms/test_fibonacci.py: -------------------------------------------------------------------------------- 1 | import unittest 2 | from pysnippets.algorithms.fibonacci import fibonacci 3 | 4 | class TestFibonacci(unittest.TestCase): 5 | 6 | def test_basic_case(self): 7 | # Test case for basic Fibonacci numbers 8 | self.assertEqual(fibonacci(0), 0) 9 | self.assertEqual(fibonacci(1), 1) 10 | self.assertEqual(fibonacci(2), 1) 11 | self.assertEqual(fibonacci(3), 2) 12 | self.assertEqual(fibonacci(4), 3) 13 | self.assertEqual(fibonacci(5), 5) 14 | 15 | def test_large_input(self): 16 | # Test case for larger input 17 | self.assertEqual(fibonacci(30), 832040) 18 | 19 | def test_negative_input(self): 20 | # Test case for negative input 21 | with self.assertRaises(ValueError): 22 | fibonacci(-1) 23 | 24 | if __name__ == '__main__': 25 | unittest.main() 26 | -------------------------------------------------------------------------------- /Tests/algorithms/test_floyds.py: -------------------------------------------------------------------------------- 1 | import unittest 2 | from pysnippets.algorithms.floyds import floyds 3 | 4 | class TestFloydsAlgorithm(unittest.TestCase): 5 | def setUp(self): 6 | self.graph = { 7 | 'A': {'A': 0, 'B': 1, 'C': float('inf'), 'D': float('inf')}, 8 | 'B': {'A': 1, 'B': 0, 'C': 3, 'D': float('inf')}, 9 | 'C': {'A': float('inf'), 'B': 3, 'C': 0, 'D': 4}, 10 | 'D': {'A': float('inf'), 'B': float('inf'), 'C': 4, 'D': 0} 11 | } 12 | 13 | def test_floyds_algorithm(self): 14 | dist = floyds(self.graph) 15 | expected_dist = { 16 | 'A': {'A': 0, 'B': 1, 'C': 4, 'D': 8}, 17 | 'B': {'A': 1, 'B': 0, 'C': 3, 'D': 7}, 18 | 'C': {'A': 4, 'B': 3, 'C': 0, 'D': 4}, 19 | 'D': {'A': 8, 'B': 7, 'C': 4, 'D': 0} 20 | } 21 | self.assertEqual(dist, expected_dist) 22 | 23 | def test_single_node(self): 24 | graph = {'A': {'A': 0}} 25 | dist = floyds(graph) 26 | expected_dist = {'A': {'A': 0}} 27 | self.assertEqual(dist, expected_dist) 28 | 29 | if __name__ == '__main__': 30 | unittest.main() -------------------------------------------------------------------------------- /Tests/algorithms/test_kruskals.py: -------------------------------------------------------------------------------- 1 | import unittest 2 | from pysnippets.algorithms.kruskals import KruskalAlgorithm 3 | 4 | class TestKruskalsAlgorithm(unittest.TestCase): 5 | def setUp(self): 6 | self.graph = { 7 | 'A': {'B': 1, 'C': 3}, 8 | 'B': {'A': 1, 'C': 3, 'D': 6}, 9 | 'C': {'A': 3, 'B': 3, 'D': 4}, 10 | 'D': {'B': 6, 'C': 4} 11 | } 12 | 13 | def test_kruskals_algorithm(self): 14 | mst = KruskalAlgorithm.kruskal(self.graph) 15 | expected_mst = [ 16 | ('A', 'B', 1), 17 | ('A', 'C', 3), 18 | ('C', 'D', 4) 19 | ] 20 | self.assertEqual(sorted(mst), sorted(expected_mst)) 21 | 22 | def test_disconnected_graph(self): 23 | graph = {'A': {}, 'B': {}} 24 | mst = KruskalAlgorithm.kruskal(graph) 25 | self.assertEqual(mst, []) 26 | 27 | if __name__ == '__main__': 28 | unittest.main() 29 | -------------------------------------------------------------------------------- /Tests/algorithms/test_prims.py: -------------------------------------------------------------------------------- 1 | import unittest 2 | from pysnippets.algorithms.prims import prims 3 | 4 | class TestPrimsAlgorithm(unittest.TestCase): 5 | def setUp(self): 6 | self.graph = { 7 | 'A': {'B': 1, 'C': 3}, 8 | 'B': {'A': 1, 'C': 3, 'D': 6}, 9 | 'C': {'A': 3, 'B': 3, 'D': 4}, 10 | 'D': {'B': 6, 'C': 4} 11 | } 12 | 13 | def test_prims_algorithm(self): 14 | mst = prims(self.graph, 'A') 15 | expected_mst = { 16 | 'A': {'B': 1, 'C': 3}, 17 | 'B': {'A': 1}, 18 | 'C': {'A': 3, 'D': 4}, 19 | 'D': {'C': 4} 20 | } 21 | self.assertEqual(mst, expected_mst) 22 | 23 | if __name__ == '__main__': 24 | unittest.main() -------------------------------------------------------------------------------- /Tests/algorithms/test_topological_ordering.py: -------------------------------------------------------------------------------- 1 | import unittest 2 | from pysnippets.algorithms.topological_ordering import topological_ordering 3 | 4 | class TestTopologicalOrdering(unittest.TestCase): 5 | def setUp(self): 6 | self.graph = { 7 | 'A': ['B', 'C'], 8 | 'B': ['D'], 9 | 'C': ['D'], 10 | 'D': [] 11 | } 12 | 13 | def test_topological_ordering(self): 14 | order = topological_ordering(self.graph) 15 | expected_order = ['A', 'B', 'C', 'D'] # One possible valid topological order 16 | self.assertEqual(order, expected_order) 17 | 18 | if __name__ == '__main__': 19 | unittest.main() 20 | -------------------------------------------------------------------------------- /Tests/algorithms/test_warshalls.py: -------------------------------------------------------------------------------- 1 | import unittest 2 | from pysnippets.algorithms.warshalls import warshall_algorithm 3 | 4 | class TestWarshallsAlgorithm(unittest.TestCase): 5 | def setUp(self): 6 | self.graph = [ 7 | [0, 1, float('inf'), 1], 8 | [1, 0, 1, float('inf')], 9 | [float('inf'), 1, 0, 1], 10 | [1, float('inf'), 1, 0] 11 | ] 12 | 13 | def test_warshalls_algorithm(self): 14 | transitive_closure = warshall_algorithm(self.graph) 15 | expected_closure = [ 16 | [1, 1, 1, 1], 17 | [1, 1, 1, 1], 18 | [1, 1, 1, 1], 19 | [1, 1, 1, 1] 20 | ] 21 | self.assertEqual(transitive_closure, expected_closure) 22 | 23 | if __name__ == '__main__': 24 | unittest.main() -------------------------------------------------------------------------------- /Tests/dictionary/test_dictionarywithindices.py: -------------------------------------------------------------------------------- 1 | 2 | import unittest 3 | from dictionarywithindices import convert_list_to_dict_with_indices 4 | 5 | class TestConvertListToDictWithIndices(unittest.TestCase): 6 | def test_conversion(self): 7 | self.assertEqual(convert_list_to_dict_with_indices(['a', 'b', 'c']), {'a': 0, 'b': 1, 'c': 2}) 8 | self.assertEqual(convert_list_to_dict_with_indices([10, 20, 30]), {10: 0, 20: 1, 30: 2}) 9 | self.assertEqual(convert_list_to_dict_with_indices([]), {}) 10 | 11 | if __name__ == '__main__': 12 | unittest.main() 13 | -------------------------------------------------------------------------------- /Tests/files/test_file_reader.py: -------------------------------------------------------------------------------- 1 | # test_file_reader.py 2 | 3 | import os 4 | import unittest 5 | from pysnippets.files.file_reader import read_file 6 | 7 | 8 | class TestFileReader(unittest.TestCase): 9 | 10 | def setUp(self): 11 | # Create a temporary file for testing 12 | self.test_file = "test_file.txt" 13 | with open(self.test_file, "w") as f: 14 | f.write("This is a test file.") 15 | 16 | def tearDown(self): 17 | # Remove the temporary file after the test 18 | os.remove(self.test_file) 19 | 20 | def test_read_file(self): 21 | content = read_file(self.test_file) 22 | self.assertEqual(content, "This is a test file.") 23 | 24 | def test_file_not_found(self): 25 | with self.assertRaises(FileNotFoundError): 26 | read_file("non_existent_file.txt") 27 | 28 | 29 | if __name__ == "__main__": 30 | unittest.main() 31 | -------------------------------------------------------------------------------- /Tests/library_snippets/test_matplotlib_snippet.py: -------------------------------------------------------------------------------- 1 | import unittest 2 | import matplotlib.pyplot as plt 3 | from library_snippets.matplotlib_snippet import plot_line, plot_bar 4 | 5 | class TestMatplotlibSnippet(unittest.TestCase): 6 | def test_plot_line(self): 7 | """ Test line plot creation. """ 8 | try: 9 | plot_line([1, 2, 3], [1, 4, 9], 'Test Line Plot', 'x-axis', 'y-axis') 10 | except Exception as e: 11 | self.fail(f"plot_line raised an exception {e}") 12 | 13 | def test_plot_bar(self): 14 | """ Test bar plot creation. """ 15 | try: 16 | plot_bar(['a', 'b', 'c'], [5, 3, 9], 'Test Bar Plot', 'Categories', 'Values') 17 | except Exception as e: 18 | self.fail(f"plot_bar raised an exception {e}") 19 | 20 | # Additional tests for scatter, histogram, and pie can be added similarly. 21 | 22 | if __name__ == '__main__': 23 | unittest.main() -------------------------------------------------------------------------------- /Tests/library_snippets/test_numpy_snippet.py: -------------------------------------------------------------------------------- 1 | import unittest 2 | import numpy as np 3 | from library_snippets.numpy_snippet import add, multiply 4 | 5 | class TestNumpySnippet(unittest.TestCase): 6 | def test_add(self): 7 | """ Test addition of two arrays. """ 8 | result = add(np.array([1, 2, 3]), np.array([4, 5, 6])) 9 | np.testing.assert_array_equal(result, np.array([5, 7, 9])) 10 | 11 | def test_multiply(self): 12 | """ Test multiplication of two arrays. """ 13 | result = multiply(np.array([1, 2, 3]), np.array([4, 5, 6])) 14 | np.testing.assert_array_equal(result, np.array([4, 10, 18])) 15 | 16 | # Additional tests for subtract, divide, power, etc., can be added similarly. 17 | 18 | if __name__ == '__main__': 19 | unittest.main() -------------------------------------------------------------------------------- /Tests/library_snippets/test_pandas_snippet.py: -------------------------------------------------------------------------------- 1 | import unittest 2 | import pandas as pd 3 | from library_snippets.pandas_snippet import filter, save 4 | 5 | class TestPandasSnippet(unittest.TestCase): 6 | def setUp(self): 7 | self.df = pd.DataFrame({ 8 | 'Name': ['Alice', 'Bob', 'Charlie'], 9 | 'Age': [25, 30, 35] 10 | }) 11 | 12 | def test_filter(self): 13 | """ Test filtering DataFrame by column value. """ 14 | result = filter(self.df, 'Name', 'Alice') 15 | expected = pd.DataFrame({ 16 | 'Name': ['Alice'], 17 | 'Age': [25] 18 | }) 19 | pd.testing.assert_frame_equal(result, expected) 20 | 21 | def test_save(self): 22 | """ Test saving DataFrame to CSV. """ 23 | # This test would ideally check file output, but here we'll just run the function. 24 | try: 25 | save(self.df, 'test_output.csv') 26 | except Exception as e: 27 | self.fail(f"save raised an exception {e}") 28 | 29 | # Additional tests for other DataFrame operations can be added similarly. 30 | 31 | if __name__ == '__main__': 32 | unittest.main() -------------------------------------------------------------------------------- /Tests/library_snippets/test_requests_snippet.py: -------------------------------------------------------------------------------- 1 | import unittest 2 | from unittest.mock import patch 3 | from library_snippets.requests_snippet import fetch, parse 4 | 5 | class TestRequestsSnippet(unittest.TestCase): 6 | @patch('library_snippets.requests_snippet.requests.get') 7 | def test_fetch(self, mock_get): 8 | """ Test fetching HTML content. """ 9 | mock_get.return_value.text = 'Mocked page content' 10 | result = fetch('http://example.com') 11 | self.assertEqual(result, 'Mocked page content') 12 | 13 | def test_parse(self): 14 | """ Test parsing HTML content. """ 15 | html_content = 'Test

Hello World

' 16 | soup = parse(html_content) 17 | self.assertEqual(soup.title.string, 'Test') 18 | 19 | # Additional tests for extracting links and text can be added similarly. 20 | 21 | if __name__ == '__main__': 22 | unittest.main() -------------------------------------------------------------------------------- /Tests/strings/test_list_to_comma_string.py: -------------------------------------------------------------------------------- 1 | # test_list_to_comma_string.py 2 | 3 | import unittest 4 | from pysnippets.strings.list_to_comma_string import list_to_comma_string 5 | 6 | 7 | class TestListToCommaString(unittest.TestCase): 8 | 9 | def test_normal_case(self): 10 | self.assertEqual( 11 | list_to_comma_string(["apple", "banana", "cherry"]), "apple, banana, cherry" 12 | ) 13 | 14 | def test_empty_list(self): 15 | self.assertEqual(list_to_comma_string([]), "") 16 | 17 | def test_single_item(self): 18 | self.assertEqual(list_to_comma_string(["apple"]), "apple") 19 | 20 | def test_non_string_item(self): 21 | with self.assertRaises(ValueError): 22 | list_to_comma_string(["apple", 123, "cherry"]) 23 | 24 | 25 | if __name__ == "__main__": 26 | unittest.main() 27 | -------------------------------------------------------------------------------- /Tests/system/test_disk_space_checker.py: -------------------------------------------------------------------------------- 1 | import unittest 2 | from pysnippets.system.disk_space_checker import check_disk_space 3 | import os 4 | 5 | class TestDiskSpaceChecker(unittest.TestCase): 6 | 7 | def test_check_disk_space(self): 8 | disk_info = check_disk_space('/') 9 | self.assertTrue(disk_info['total_space'] > 0) # Total space should be positive 10 | self.assertTrue(disk_info['free_space'] > 0) # Free space should be positive 11 | self.assertTrue(disk_info['used_space'] >= 0) # Used space should be non-negative 12 | 13 | def test_invalid_path(self): 14 | invalid_path = '/invalidpath' 15 | with self.assertRaises(FileNotFoundError): 16 | check_disk_space(invalid_path) # Should raise an error for invalid path 17 | 18 | if __name__ == '__main__': 19 | unittest.main() 20 | -------------------------------------------------------------------------------- /Tests/system/test_environment_variable_manager.py: -------------------------------------------------------------------------------- 1 | import unittest 2 | import os 3 | from pysnippets.system.environment_variable_manager import get_env_variable, set_env_variable, delete_env_variable 4 | 5 | class TestEnvVariableManager(unittest.TestCase): 6 | 7 | def test_set_and_get_env_variable(self): 8 | set_env_variable('TEST_VAR', 'test_value') 9 | self.assertEqual(get_env_variable('TEST_VAR'), 'test_value') 10 | 11 | def test_delete_env_variable(self): 12 | set_env_variable('TEST_VAR', 'test_value') 13 | delete_env_variable('TEST_VAR') 14 | self.assertIsNone(get_env_variable('TEST_VAR')) # After deletion, it should return None 15 | 16 | def test_get_nonexistent_variable(self): 17 | self.assertIsNone(get_env_variable('NONEXISTENT_VAR')) # Should return None if not set 18 | 19 | if __name__ == '__main__': 20 | unittest.main() 21 | -------------------------------------------------------------------------------- /Tests/system/test_resource_manager.py: -------------------------------------------------------------------------------- 1 | import unittest 2 | from pysnippets.system.system_resource_monitor import get_cpu_usage, get_memory_usage 3 | 4 | class TestSystemResourceMonitor(unittest.TestCase): 5 | 6 | def test_get_cpu_usage(self): 7 | cpu_usage = get_cpu_usage() 8 | self.assertTrue(0 <= cpu_usage <= 100) # CPU usage should be between 0 and 100% 9 | 10 | def test_get_memory_usage(self): 11 | memory_info = get_memory_usage() 12 | self.assertTrue(memory_info['total_memory'] > 0) # Total memory should be positive 13 | self.assertTrue(memory_info['used_memory'] > 0) # Used memory should be positive 14 | 15 | if __name__ == '__main__': 16 | unittest.main() 17 | -------------------------------------------------------------------------------- /Tests/tkinter/test_init.py: -------------------------------------------------------------------------------- 1 | import unittest 2 | from unittest.mock import patch 3 | import tkinter as tk 4 | from pysnippets.tkinter.__init__ import App 5 | 6 | class TestApp(unittest.TestCase): 7 | def setUp(self): 8 | self.root = tk.Tk() 9 | self.app = App(self.root) 10 | 11 | def tearDown(self): 12 | self.root.destroy() 13 | 14 | def test_app_initialization(self): 15 | self.assertEqual(self.app.root.title(), "Tkinter Example App") 16 | self.assertEqual(self.app.root.geometry(), "300x200") 17 | self.assertIsInstance(self.app.label, tk.Label) 18 | self.assertEqual(self.app.label['text'], "Hello, Tkinter!") 19 | self.assertIsInstance(self.app.button, tk.Button) 20 | self.assertEqual(self.app.button['text'], "Click Me") 21 | 22 | @patch('tkinter.messagebox.showinfo') 23 | def test_on_button_click(self, mock_showinfo): 24 | self.app.on_button_click() 25 | mock_showinfo.assert_called_once_with("Information", "Button was clicked!") 26 | 27 | if __name__ == '__main__': 28 | unittest.main() -------------------------------------------------------------------------------- /Tests/tkinter/test_main.py: -------------------------------------------------------------------------------- 1 | import unittest 2 | from unittest.mock import patch 3 | import tkinter as tk 4 | from pysnippets.tkinter.main import main 5 | 6 | class TestMain(unittest.TestCase): 7 | @patch('pysnippets.tkinter.main.show_confirmation') 8 | @patch('tkinter.Tk') 9 | def test_on_exit_confirm(self, mock_tk, mock_show_confirmation): 10 | mock_show_confirmation.return_value = True 11 | with patch.object(tk.Tk, 'destroy') as mock_destroy: 12 | main() 13 | mock_show_confirmation.assert_called() 14 | mock_destroy.assert_called() 15 | 16 | @patch('pysnippets.tkinter.main.show_confirmation') 17 | @patch('tkinter.Tk') 18 | def test_on_exit_cancel(self, mock_tk, mock_show_confirmation): 19 | mock_show_confirmation.return_value = False 20 | with patch.object(tk.Tk, 'destroy') as mock_destroy: 21 | main() 22 | mock_show_confirmation.assert_called() 23 | mock_destroy.assert_not_called() 24 | 25 | if __name__ == '__main__': 26 | unittest.main() -------------------------------------------------------------------------------- /Tests/utilities/test_caching.py: -------------------------------------------------------------------------------- 1 | 2 | import unittest 3 | from caching import cache 4 | 5 | @cache 6 | def expensive_function(n): 7 | return n * n 8 | 9 | class TestCache(unittest.TestCase): 10 | def test_cache(self): 11 | self.assertEqual(expensive_function(4), 16) 12 | self.assertEqual(expensive_function(4), 16) # Cached result 13 | 14 | if __name__ == '__main__': 15 | unittest.main() 16 | -------------------------------------------------------------------------------- /Tests/utilities/test_deep_copy.py: -------------------------------------------------------------------------------- 1 | 2 | import unittest 3 | from deep_copy import deep_copy 4 | 5 | class TestDeepCopy(unittest.TestCase): 6 | def test_deep_copy(self): 7 | original = {'a': 1, 'b': [2, 3, 4]} 8 | copy = deep_copy(original) 9 | self.assertEqual(copy, original) 10 | self.assertIsNot(copy, original) 11 | 12 | if __name__ == '__main__': 13 | unittest.main() 14 | -------------------------------------------------------------------------------- /Tests/utilities/test_flatten.py: -------------------------------------------------------------------------------- 1 | 2 | import unittest 3 | from flatten import flatten_list 4 | 5 | class TestFlattenList(unittest.TestCase): 6 | def test_flatten_list(self): 7 | nested_list = [1, [2, [3, 4], 5], 6] 8 | self.assertEqual(flatten_list(nested_list), [1, 2, 3, 4, 5, 6]) 9 | 10 | if __name__ == '__main__': 11 | unittest.main() 12 | -------------------------------------------------------------------------------- /Tests/utilities/test_time_execution.py: -------------------------------------------------------------------------------- 1 | import unittest 2 | import time 3 | from pysnippets.utilities.timer import time_execution 4 | from io import StringIO 5 | import sys 6 | 7 | 8 | class TestTimeExecution(unittest.TestCase): 9 | 10 | def test_time_execution_output(self): 11 | @time_execution 12 | def slow_function(x: int) -> int: 13 | time.sleep(1) 14 | return x * 2 15 | 16 | captured_output = StringIO() 17 | sys.stdout = captured_output 18 | result = slow_function(5) 19 | sys.stdout = sys.__stdout__ 20 | 21 | self.assertEqual(result, 10) 22 | output = captured_output.getvalue() 23 | self.assertIn("Execution time", output) 24 | 25 | 26 | if __name__ == "__main__": 27 | unittest.main() 28 | -------------------------------------------------------------------------------- /docs/.gitkeep: -------------------------------------------------------------------------------- 1 | 2 | -------------------------------------------------------------------------------- /library_snippets/numpy_snippet.py: -------------------------------------------------------------------------------- 1 | import numpy as np 2 | from numpy import ndarray 3 | 4 | def add(arr1: ndarray, arr2: ndarray) -> ndarray: 5 | return np.add(arr1, arr2) 6 | 7 | def subtract(arr1: ndarray, arr2: ndarray) -> ndarray: 8 | return np.subtract(arr1, arr2) 9 | 10 | def multiply(arr1: ndarray, arr2: ndarray) -> ndarray: 11 | return np.multiply(arr1, arr2) 12 | 13 | def divide(arr1: ndarray, arr2: ndarray) -> ndarray: 14 | return np.divide(arr1, arr2) 15 | 16 | def power(arr1: ndarray, arr2: ndarray) -> ndarray: 17 | return np.power(arr1, arr2) 18 | 19 | def sqrt(arr: ndarray) -> ndarray: 20 | return np.sqrt(arr) 21 | 22 | def log(arr: ndarray) -> ndarray: 23 | return np.log(arr) 24 | 25 | def exp(arr: ndarray) -> ndarray: 26 | return np.exp(arr) 27 | 28 | def sin(arr: ndarray) -> ndarray: 29 | return np.sin(arr) 30 | 31 | def cos(arr: ndarray) -> ndarray: 32 | return np.cos(arr) 33 | 34 | def tan(arr: ndarray) -> ndarray: 35 | return np.tan(arr) 36 | 37 | def abs(arr: ndarray) -> ndarray: 38 | return np.abs(arr) -------------------------------------------------------------------------------- /library_snippets/requests_snippet.py: -------------------------------------------------------------------------------- 1 | import requests 2 | from bs4 import BeautifulSoup 3 | from typing import List 4 | 5 | def fetch(url: str) -> str: 6 | try: 7 | response = requests.get(url) 8 | response.raise_for_status() # Raises HTTPError for bad responses 9 | return response.text 10 | except requests.RequestException as e: 11 | return str(e) 12 | 13 | def parse(html: str) -> BeautifulSoup: 14 | return BeautifulSoup(html, 'html.parser') 15 | 16 | def extract_links(soup: BeautifulSoup) -> List[str]: 17 | return [a['href'] for a in soup.find_all('a', href=True)] 18 | 19 | def extract_text(soup: BeautifulSoup, tag: str) -> List[str]: 20 | return [element.get_text() for element in soup.find_all(tag)] -------------------------------------------------------------------------------- /pysnippets/API_module/__init__.py: -------------------------------------------------------------------------------- 1 | from .api_requests import get, post, put, delete, get_with_path_params 2 | from .query_params import serialize_params 3 | from .path_params import construct_url 4 | from .response_handling import handle_response 5 | 6 | __all__ = [ 7 | "get", "post", "put", "delete", "get_with_path_params", 8 | "serialize_params", "construct_url", 9 | "handle_response" 10 | ] 11 | -------------------------------------------------------------------------------- /pysnippets/API_module/path_params.py: -------------------------------------------------------------------------------- 1 | from urllib.parse import quote 2 | 3 | def construct_url(base_url, path_params): 4 | """ 5 | Construct a URL by appending path parameters to a base URL. 6 | Path parameters are URL-encoded to handle special characters. 7 | 8 | Args: 9 | base_url (str): The base URL to which path parameters will be appended. 10 | path_params (list or tuple): A sequence of path parameters to append to the URL. 11 | 12 | Returns: 13 | str: The fully constructed URL. 14 | """ 15 | encoded_params = [quote(str(param)) for param in path_params] 16 | return f"{base_url}/{'/'.join(encoded_params)}" -------------------------------------------------------------------------------- /pysnippets/API_module/query_params.py: -------------------------------------------------------------------------------- 1 | from urllib.parse import urlencode 2 | 3 | def serialize_params(params): 4 | """ 5 | Serialize complex query parameters into a URL-encoded string. 6 | Handles lists, dictionaries, and nested combinations. 7 | 8 | Args: 9 | params (dict): The dictionary of parameters to serialize. 10 | 11 | Returns: 12 | str: URL-encoded query parameters. 13 | """ 14 | # Recursively encode parameters 15 | def encode_dict(data): 16 | for key, value in data.items(): 17 | if isinstance(value, dict): 18 | for subkey, subvalue in encode_dict(value).items(): 19 | yield f"{key}[{subkey}]", subvalue 20 | elif isinstance(value, list): 21 | for subvalue in value: 22 | yield f"{key}[]", subvalue 23 | else: 24 | yield key, value 25 | 26 | encoded_params = dict(encode_dict(params)) 27 | return urlencode(encoded_params, doseq=True) -------------------------------------------------------------------------------- /pysnippets/API_module/response_handling.py: -------------------------------------------------------------------------------- 1 | import zipfile 2 | import os 3 | import logging 4 | 5 | def handle_response(response, save_path): 6 | try: 7 | content_type = response.headers.get('Content-Type', '') 8 | if 'application/zip' in content_type: 9 | with open('temp.zip', 'wb') as f: 10 | f.write(response.content) 11 | with zipfile.ZipFile('temp.zip', 'r') as zip_ref: 12 | zip_ref.extractall(save_path) 13 | os.remove('temp.zip') 14 | logging.info("Zip file processed and extracted.") 15 | else: 16 | logging.info("Response content type: {content_type} - no special handling applied.") 17 | except Exception as e: 18 | logging.error(f"Failed to handle response: {e}") -------------------------------------------------------------------------------- /pysnippets/Asynchronous/__init__.py: -------------------------------------------------------------------------------- 1 | import asyncio 2 | import logging 3 | 4 | # Setup basic logging 5 | logging.basicConfig(level=logging.INFO, format='%(asctime)s - %(levelname)s - %(message)s') 6 | 7 | async def fetch_data(url): 8 | logging.info(f"Fetching data from {url}") 9 | await asyncio.sleep(1) # Simulate network delay 10 | return f"Data from {url}" 11 | 12 | async def main(): 13 | result = await fetch_data("http://example.com") 14 | logging.info(f"Received: {result}") 15 | 16 | if __name__ == "__main__": 17 | asyncio.run(main()) 18 | -------------------------------------------------------------------------------- /pysnippets/Asynchronous/advanced_error_handling.py: -------------------------------------------------------------------------------- 1 | import asyncio 2 | import logging 3 | 4 | async def error_prone_request(): 5 | try: 6 | logging.info("Making a risky request") 7 | await asyncio.sleep(1) 8 | raise Exception("Something went wrong!") 9 | except Exception as e: 10 | logging.error(f"Caught an error: {e}") 11 | return None 12 | 13 | async def main(): 14 | result = await error_prone_request() 15 | if result is None: 16 | logging.info("Handling fallback") 17 | else: 18 | logging.info(f"Received: {result}") 19 | 20 | if __name__ == "__main__": 21 | asyncio.run(main()) -------------------------------------------------------------------------------- /pysnippets/Asynchronous/advanced_error_handling_continued.py: -------------------------------------------------------------------------------- 1 | import asyncio 2 | import logging 3 | 4 | async def risky_task(): 5 | try: 6 | logging.info("Starting risky task") 7 | await asyncio.sleep(1) 8 | raise ValueError("Something went wrong") 9 | except ValueError as e: 10 | logging.error(f"Caught an error: {e}") 11 | return "Handled error" 12 | 13 | async def main(): 14 | result = await risky_task() 15 | logging.info(f"Result: {result}") 16 | 17 | if __name__ == "__main__": 18 | asyncio.run(main()) -------------------------------------------------------------------------------- /pysnippets/Asynchronous/async_context_managers.py: -------------------------------------------------------------------------------- 1 | import asyncio 2 | import logging 3 | 4 | class AsyncContextManager: 5 | async def __aenter__(self): 6 | logging.info("Enter context") 7 | return self 8 | 9 | async def __aexit__(self, exc_type, exc, tb): 10 | logging.info("Exit context") 11 | 12 | async def main(): 13 | async with AsyncContextManager(): 14 | logging.info("Doing work inside the context") 15 | 16 | if __name__ == "__main__": 17 | asyncio.run(main()) -------------------------------------------------------------------------------- /pysnippets/Asynchronous/async_generators.py: -------------------------------------------------------------------------------- 1 | import asyncio 2 | import logging 3 | 4 | async def async_generator(): 5 | for i in range(5): 6 | await asyncio.sleep(1) 7 | yield i 8 | logging.info(f"Yielded {i}") 9 | 10 | async def main(): 11 | async for value in async_generator(): 12 | logging.info(f"Received {value}") 13 | 14 | if __name__ == "__main__": 15 | asyncio.run(main()) -------------------------------------------------------------------------------- /pysnippets/Asynchronous/async_with_databases.py: -------------------------------------------------------------------------------- 1 | import asyncio 2 | import asyncpg 3 | import logging 4 | 5 | async def fetch_from_db(): 6 | conn = await asyncpg.connect(user='user', password='password', database='db', host='localhost') 7 | logging.info("Connected to database") 8 | data = await conn.fetch('SELECT * FROM my_table') 9 | await conn.close() 10 | return data 11 | 12 | async def main(): 13 | data = await fetch_from_db() 14 | logging.info(f"Data fetched from database: {data}") 15 | 16 | if __name__ == "__main__": 17 | asyncio.run(main()) -------------------------------------------------------------------------------- /pysnippets/Asynchronous/concurrency.py: -------------------------------------------------------------------------------- 1 | import asyncio 2 | import logging 3 | 4 | # Setup basic logging 5 | logging.basicConfig(level=logging.INFO, format='%(asctime)s - %(levelname)s - %(message)s') 6 | 7 | async def task(name, delay): 8 | """Simulates an async task with a delay""" 9 | logging.info(f"Task {name} starting") 10 | await asyncio.sleep(delay) 11 | logging.info(f"Task {name} completed") 12 | return f"Result from task {name}" 13 | 14 | async def main(): 15 | # Create multiple tasks to run concurrently 16 | tasks = [ 17 | asyncio.create_task(task("A", 2)), 18 | asyncio.create_task(task("B", 1)), 19 | asyncio.create_task(task("C", 3)) 20 | ] 21 | 22 | # Wait for all tasks to complete 23 | results = await asyncio.gather(*tasks) 24 | 25 | # Process results 26 | for result in results: 27 | logging.info(result) 28 | 29 | if __name__ == "__main__": 30 | asyncio.run(main()) -------------------------------------------------------------------------------- /pysnippets/Asynchronous/data_classes.py: -------------------------------------------------------------------------------- 1 | from dataclasses import dataclass 2 | import asyncio 3 | import logging 4 | 5 | @dataclass 6 | class WebsiteData: 7 | url: str 8 | content: str 9 | 10 | async def fetch_data(url): 11 | logging.info(f"Fetching data from {url}") 12 | await asyncio.sleep(1) # Simulate network delay 13 | return WebsiteData(url, f"Content from {url}") 14 | 15 | async def main(): 16 | website = await fetch_data("http://example.com") 17 | logging.info(f"Fetched {website.content} from {website.url}") 18 | 19 | if __name__ == "__main__": 20 | asyncio.run(main()) 21 | -------------------------------------------------------------------------------- /pysnippets/Asynchronous/error_handling.py: -------------------------------------------------------------------------------- 1 | import asyncio 2 | import logging 3 | 4 | async def fetch_data(url): 5 | try: 6 | logging.info(f"Attempting to fetch data from {url}") 7 | await asyncio.sleep(1) # Simulate a network delay 8 | if url == "http://error.com": 9 | raise ValueError("Invalid URL") 10 | return f"Data from {url}" 11 | except ValueError as e: 12 | logging.error(f"Error fetching data: {e}") 13 | return None 14 | 15 | async def main(): 16 | urls = ["http://example.com", "http://error.com"] 17 | for url in urls: 18 | result = await fetch_data(url) 19 | if result: 20 | logging.info(f"Successfully received data: {result}") 21 | else: 22 | logging.info("Failed to fetch data") 23 | 24 | if __name__ == "__main__": 25 | asyncio.run(main()) -------------------------------------------------------------------------------- /pysnippets/Asynchronous/file_operations.py: -------------------------------------------------------------------------------- 1 | import asyncio 2 | import aiofiles 3 | import logging 4 | 5 | async def read_file_async(path): 6 | async with aiofiles.open(path, mode='r') as file: 7 | content = await file.read() 8 | logging.info(f"Read content: {content[:100]}") # Display first 100 characters 9 | return content 10 | 11 | async def main(): 12 | await read_file_async('example.txt') 13 | logging.info("File read successfully") 14 | 15 | if __name__ == "__main__": 16 | asyncio.run(main()) -------------------------------------------------------------------------------- /pysnippets/Asynchronous/handling_timeouts.py: -------------------------------------------------------------------------------- 1 | import asyncio 2 | import logging 3 | 4 | async def fetch_with_timeout(url, timeout): 5 | logging.info(f"Fetching {url} with a timeout of {timeout} seconds") 6 | try: 7 | await asyncio.wait_for(asyncio.sleep(3), timeout=timeout) # Simulate a delay that might exceed timeout 8 | logging.info("Fetch successful") 9 | return f"Data from {url}" 10 | except asyncio.TimeoutError: 11 | logging.error("Fetch timed out") 12 | return None 13 | 14 | async def main(): 15 | result = await fetch_with_timeout("http://example.com", 2) 16 | if result is None: 17 | logging.info("Operation timed out") 18 | else: 19 | logging.info(f"Received: {result}") 20 | 21 | if __name__ == "__main__": 22 | asyncio.run(main()) -------------------------------------------------------------------------------- /pysnippets/Asynchronous/http_requests.py: -------------------------------------------------------------------------------- 1 | import asyncio 2 | import aiohttp 3 | import logging 4 | 5 | async def fetch_url(url): 6 | logging.info(f"Fetching URL: {url}") 7 | async with aiohttp.ClientSession() as session: 8 | async with session.get(url) as response: 9 | result = await response.text() 10 | logging.info(f"Received data from {url}") 11 | return result 12 | 13 | async def main(): 14 | url = "http://example.com" 15 | content = await fetch_url(url) 16 | logging.info(f"Content from {url}: {content[:100]}") # Print first 100 characters 17 | 18 | if __name__ == "__main__": 19 | asyncio.run(main()) -------------------------------------------------------------------------------- /pysnippets/Asynchronous/integrating_sync.py: -------------------------------------------------------------------------------- 1 | import asyncio 2 | import logging 3 | 4 | def synchronous_function(): 5 | logging.info("Running synchronous function") 6 | 7 | async def main(): 8 | loop = asyncio.get_running_loop() 9 | await loop.run_in_executor(None, synchronous_function) 10 | 11 | if __name__ == "__main__": 12 | asyncio.run(main()) -------------------------------------------------------------------------------- /pysnippets/Asynchronous/performance_monitoring.py: -------------------------------------------------------------------------------- 1 | import asyncio 2 | import time 3 | import logging 4 | 5 | async def task(): 6 | logging.info("Starting task") 7 | await asyncio.sleep(1) 8 | logging.info("Task completed") 9 | 10 | async def main(): 11 | start_time = time.time() 12 | await task() 13 | elapsed_time = time.time() - start_time 14 | logging.info(f"Task completed in {elapsed_time:.2f} seconds") 15 | 16 | if __name__ == "__main__": 17 | asyncio.run(main()) -------------------------------------------------------------------------------- /pysnippets/Asynchronous/task_cancellation.py: -------------------------------------------------------------------------------- 1 | import asyncio 2 | import logging 3 | 4 | async def cancellable_task(): 5 | try: 6 | logging.info("Task started") 7 | await asyncio.sleep(10) # Long running task 8 | logging.info("Task completed") 9 | except asyncio.CancelledError: 10 | logging.info("Task was cancelled") 11 | raise 12 | 13 | async def main(): 14 | task = asyncio.create_task(cancellable_task()) 15 | await asyncio.sleep(1) # Let the task start 16 | task.cancel() 17 | try: 18 | await task 19 | except asyncio.CancelledError: 20 | logging.info("Main noticed that the task was cancelled") 21 | 22 | if __name__ == "__main__": 23 | asyncio.run(main()) -------------------------------------------------------------------------------- /pysnippets/Asynchronous/testing_async_code.py: -------------------------------------------------------------------------------- 1 | import asyncio 2 | import unittest 3 | 4 | class TestAsync(unittest.IsolatedAsyncioTestCase): 5 | async def test_simple_task(self): 6 | async def task(): 7 | return 123 8 | result = await task() 9 | self.assertEqual(result, 123) 10 | 11 | if __name__ == "__main__": 12 | unittest.main() -------------------------------------------------------------------------------- /pysnippets/Asynchronous/using_locks.py: -------------------------------------------------------------------------------- 1 | import asyncio 2 | import logging 3 | 4 | async def task_with_lock(lock, item): 5 | async with lock: 6 | logging.info(f"Start processing {item}") 7 | await asyncio.sleep(2) # Simulate work 8 | logging.info(f"End processing {item}") 9 | 10 | async def main(): 11 | lock = asyncio.Lock() 12 | tasks = [asyncio.create_task(task_with_lock(lock, i)) for i in range(5)] 13 | await asyncio.gather(*tasks) 14 | 15 | if __name__ == "__main__": 16 | asyncio.run(main()) -------------------------------------------------------------------------------- /pysnippets/Asynchronous/using_semaphores.py: -------------------------------------------------------------------------------- 1 | import asyncio 2 | import logging 3 | 4 | async def limited_access(sem, item): 5 | async with sem: 6 | logging.info(f"Processing {item}") 7 | await asyncio.sleep(2) # Simulate work 8 | logging.info(f"Finished processing {item}") 9 | 10 | async def main(): 11 | sem = asyncio.Semaphore(2) # Limit concurrent access to 2 12 | tasks = [asyncio.create_task(limited_access(sem, i)) for i in range(5)] 13 | await asyncio.gather(*tasks) 14 | 15 | if __name__ == "__main__": 16 | asyncio.run(main()) 17 | -------------------------------------------------------------------------------- /pysnippets/Asynchronous/websockets.py: -------------------------------------------------------------------------------- 1 | import asyncio 2 | import websockets 3 | import logging 4 | 5 | async def websocket_echo(uri): 6 | async with websockets.connect(uri) as websocket: 7 | await websocket.send("Hello Server!") 8 | logging.info("Message sent to server") 9 | response = await websocket.recv() 10 | logging.info(f"Received from server: {response}") 11 | 12 | async def main(): 13 | await websocket_echo('ws://localhost:8765') 14 | 15 | if __name__ == "__main__": 16 | asyncio.run(main()) -------------------------------------------------------------------------------- /pysnippets/Bitwise/__init__.py: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/UTSAVS26/PySnippets/7d663efc569f46c1550a16fbba42fa8e6e815b7e/pysnippets/Bitwise/__init__.py -------------------------------------------------------------------------------- /pysnippets/Bitwise/clear_lsb_upto_n.py: -------------------------------------------------------------------------------- 1 | def clear_lsb_up_to_pos(n, pos): 2 | """Clears all least significant bits up to a given position using bitwise operations for efficiency.""" 3 | return n & ~((1 << pos) - 1) # Clear LSBs up to pos using bitwise operations 4 | -------------------------------------------------------------------------------- /pysnippets/Bitwise/count_bits.py: -------------------------------------------------------------------------------- 1 | def count_set_bits(n): 2 | """Counts the number of set bits (1s) in an integer n using a more efficient approach.""" 3 | count = 0 4 | while n: 5 | count += n & 1 # Increment count if the least significant bit is 1 6 | n >>= 1 # Right shift n to process the next bit 7 | return count 8 | -------------------------------------------------------------------------------- /pysnippets/Bitwise/find_unique.py: -------------------------------------------------------------------------------- 1 | def find_unique(arr): 2 | """Finds the unique number in an array where every other number appears twice using XOR for efficiency.""" 3 | unique = 0 4 | for num in arr: 5 | unique ^= num # XOR all numbers; duplicates will cancel out 6 | return unique 7 | -------------------------------------------------------------------------------- /pysnippets/Bitwise/flip_bit.py: -------------------------------------------------------------------------------- 1 | def flip_bit(n, pos): 2 | """Flips the bit at the specified position in n using bitwise XOR.""" 3 | return n ^ (1 << pos) # Flip the bit at position pos 4 | -------------------------------------------------------------------------------- /pysnippets/Bitwise/isolate_right_one.py: -------------------------------------------------------------------------------- 1 | def isolate_rightmost_one(n): 2 | """Isolates the rightmost 1-bit in n using bitwise operations.""" 3 | return n & -n # Use two's complement to isolate the rightmost 1-bit 4 | -------------------------------------------------------------------------------- /pysnippets/Bitwise/power.py: -------------------------------------------------------------------------------- 1 | def is_power_of_two(n): 2 | """Checks if a number is a power of two using a bitwise trick.""" 3 | return n > 0 and (n & (n - 1)) == 0 # A power of two has only one bit set 4 | -------------------------------------------------------------------------------- /pysnippets/Bitwise/swap.py: -------------------------------------------------------------------------------- 1 | def swap_numbers(a, b): 2 | """Swaps two numbers using XOR for efficiency.""" 3 | a ^= b 4 | b ^= a 5 | a ^= b 6 | return a, b 7 | -------------------------------------------------------------------------------- /pysnippets/Bot-app/__init__.py: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/UTSAVS26/PySnippets/7d663efc569f46c1550a16fbba42fa8e6e815b7e/pysnippets/Bot-app/__init__.py -------------------------------------------------------------------------------- /pysnippets/Cipher_algorithms/__init__.py: -------------------------------------------------------------------------------- 1 | from .cipher_manager import encrypt_affine, decrypt_affine, encrypt_caesar, decrypt_caesar, encrypt_hill, decrypt_hill, encrypt_playfair, decrypt_playfair, encrypt_rail_fence, decrypt_rail_fence, encrypt_vigenere, decrypt_vigenere 2 | 3 | __all__ = [ 4 | "encrypt_affine", "decrypt_affine", "encrypt_caesar", "decrypt_caesar", "encrypt_hill", "decrypt_hill", "encrypt_playfair", "decrypt_playfair", "encrypt_rail_fence", "decrypt_rail_fence", "encrypt_vigenere", "decrypt_vigenere" 5 | ] 6 | 7 | -------------------------------------------------------------------------------- /pysnippets/Communication/__init__.py: -------------------------------------------------------------------------------- 1 | from .send_email import send_email 2 | -------------------------------------------------------------------------------- /pysnippets/Complex_number/__init__.py: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/UTSAVS26/PySnippets/7d663efc569f46c1550a16fbba42fa8e6e815b7e/pysnippets/Complex_number/__init__.py -------------------------------------------------------------------------------- /pysnippets/Complex_number/exceptions.py: -------------------------------------------------------------------------------- 1 | class ComplexNumberError(Exception): 2 | """Base exception class for ComplexNumber operations.""" 3 | pass 4 | 5 | class DivisionByZeroError(ComplexNumberError): 6 | """Exception raised when attempting to divide by zero.""" 7 | pass -------------------------------------------------------------------------------- /pysnippets/Complex_number/logger_config.py: -------------------------------------------------------------------------------- 1 | import logging 2 | 3 | def setup_logger(name: str, level: int = logging.INFO) -> logging.Logger: 4 | logger = logging.getLogger(name) 5 | if not logger.handlers: 6 | handler = logging.StreamHandler() 7 | formatter = logging.Formatter('%(asctime)s - %(name)s - %(levelname)s - %(message)s') 8 | handler.setFormatter(formatter) 9 | logger.setLevel(level) 10 | logger.addHandler(handler) 11 | return logger -------------------------------------------------------------------------------- /pysnippets/Complex_number/operations.py: -------------------------------------------------------------------------------- 1 | from complex_number import ComplexNumber 2 | from logger_config import setup_logger 3 | 4 | logger = setup_logger(__name__) 5 | 6 | def power(complex_num: ComplexNumber, exponent: int) -> ComplexNumber: 7 | if exponent == 0: 8 | logger.info(f"Power: {complex_num} ** {exponent} = 1 + 0i") 9 | return ComplexNumber(1, 0) 10 | if exponent < 0: 11 | logger.error("Negative exponents are not supported.") 12 | raise ValueError("Negative exponents are not supported.") 13 | try: 14 | result = ComplexNumber(1, 0) # Initialize result as 1 + 0i 15 | for _ in range(exponent): 16 | result = result.multiply(complex_num) 17 | logger.info(f"Power: {complex_num} ** {exponent} = {result}") 18 | return result 19 | except Exception as e: 20 | logger.error(f"Error computing power: {e}") 21 | raise ValueError("Invalid exponent value.") -------------------------------------------------------------------------------- /pysnippets/Complex_number/test_all.py: -------------------------------------------------------------------------------- 1 | import unittest 2 | from test_complex_number import TestComplexNumber 3 | from test_operations import TestOperations 4 | from test_utils import TestUtils 5 | 6 | def suite(): 7 | suite = unittest.TestSuite() 8 | suite.addTest(unittest.makeSuite(TestComplexNumber)) 9 | suite.addTest(unittest.makeSuite(TestOperations)) 10 | suite.addTest(unittest.makeSuite(TestUtils)) 11 | return suite 12 | 13 | if __name__ == '__main__': 14 | runner = unittest.TextTestRunner() 15 | runner.run(suite()) -------------------------------------------------------------------------------- /pysnippets/Complex_number/test_complex_number.py: -------------------------------------------------------------------------------- 1 | import unittest 2 | from complex_number import ComplexNumber 3 | from exceptions import DivisionByZeroError 4 | 5 | class TestComplexNumber(unittest.TestCase): 6 | 7 | def setUp(self): 8 | self.c1 = ComplexNumber(1, 2) 9 | self.c2 = ComplexNumber(3, 4) 10 | 11 | def test_division(self): 12 | result = self.c1.divide(self.c2) 13 | self.assertAlmostEqual(result.real, 0.44) 14 | self.assertAlmostEqual(result.imaginary, 0.08) 15 | 16 | def test_division_by_zero(self): 17 | c_zero = ComplexNumber(0, 0) 18 | with self.assertRaises(DivisionByZeroError): 19 | self.c1.divide(c_zero) 20 | 21 | if __name__ == '__main__': 22 | unittest.main() -------------------------------------------------------------------------------- /pysnippets/Complex_number/test_operations.py: -------------------------------------------------------------------------------- 1 | import unittest 2 | from complex_number import ComplexNumber 3 | from operations import power 4 | 5 | class TestOperations(unittest.TestCase): 6 | # ... existing tests ... 7 | 8 | def test_power_zero_exponent(self): 9 | c = ComplexNumber(2, 3) 10 | result = power(c, 0) 11 | self.assertEqual(result.real, 1) 12 | self.assertEqual(result.imaginary, 0) 13 | 14 | def test_power_negative_exponent(self): 15 | c = ComplexNumber(1, -1) 16 | with self.assertRaises(ValueError): 17 | power(c, -2) 18 | # ... existing code ... -------------------------------------------------------------------------------- /pysnippets/Complex_number/test_utils.py: -------------------------------------------------------------------------------- 1 | import unittest 2 | from utils import parse_complex 3 | 4 | class TestUtils(unittest.TestCase): 5 | 6 | def test_parse_valid_positive(self): 7 | c = parse_complex("3 + 4i") 8 | self.assertEqual(c.real, 3) 9 | self.assertEqual(c.imaginary, 4) 10 | 11 | def test_parse_valid_negative(self): 12 | c = parse_complex("5 - 6i") 13 | self.assertEqual(c.real, 5) 14 | self.assertEqual(c.imaginary, -6) 15 | 16 | def test_parse_invalid_format(self): 17 | with self.assertRaises(ValueError): 18 | parse_complex("invalid") 19 | 20 | def test_parse_missing_imaginary(self): 21 | with self.assertRaises(ValueError): 22 | parse_complex("3 + i") 23 | 24 | def test_parse_missing_real(self): 25 | with self.assertRaises(ValueError): 26 | parse_complex("+ 4i") 27 | 28 | if __name__ == '__main__': 29 | unittest.main() -------------------------------------------------------------------------------- /pysnippets/Complex_number/utils.py: -------------------------------------------------------------------------------- 1 | from complex_number import ComplexNumber 2 | import logging 3 | 4 | logger = logging.getLogger(__name__) 5 | 6 | def parse_complex(number_str: str) -> ComplexNumber: 7 | try: 8 | parts = number_str.replace('i', '').split('+') if '+' in number_str else number_str.replace('i', '').split('-') 9 | real = float(parts[0].strip()) 10 | imaginary = float(parts[1].strip()) 11 | if '-' in number_str and '+' not in number_str: 12 | imaginary = -imaginary 13 | complex_num = ComplexNumber(real, imaginary) 14 | logger.info(f"Parsed string '{number_str}' into {complex_num}") 15 | return complex_num 16 | except Exception as e: 17 | logger.error(f"Failed to parse '{number_str}': {e}") 18 | raise ValueError(f"Invalid complex number format: {number_str}") -------------------------------------------------------------------------------- /pysnippets/Computer_vision/__init__.py: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/UTSAVS26/PySnippets/7d663efc569f46c1550a16fbba42fa8e6e815b7e/pysnippets/Computer_vision/__init__.py -------------------------------------------------------------------------------- /pysnippets/Computer_vision/image_enhancement.py: -------------------------------------------------------------------------------- 1 | import cv2 2 | import numpy as np 3 | 4 | def enhance_image(image): 5 | # Input validation 6 | if image is None or len(image.shape) != 3: 7 | raise ValueError("Invalid input image") 8 | 9 | # Convert to YUV color space 10 | yuv = cv2.cvtColor(image, cv2.COLOR_BGR2YUV) 11 | 12 | # Enhance the luminance channel 13 | yuv[:,:,0] = cv2.equalizeHist(yuv[:,:,0]) 14 | 15 | # Apply Gaussian blur to reduce noise 16 | yuv[:,:,0] = cv2.GaussianBlur(yuv[:,:,0], (3,3), 0) 17 | 18 | # Enhance contrast 19 | yuv[:,:,0] = cv2.convertScaleAbs(yuv[:,:,0], alpha=1.2, beta=5) 20 | 21 | # Convert back to BGR color space 22 | enhanced_image = cv2.cvtColor(yuv, cv2.COLOR_YUV2BGR) 23 | 24 | # Apply sharpening 25 | kernel = np.array([[-1,-1,-1], 26 | [-1, 9,-1], 27 | [-1,-1,-1]]) 28 | enhanced_image = cv2.filter2D(enhanced_image, -1, kernel) 29 | 30 | # Ensure output is in valid range 31 | enhanced_image = np.clip(enhanced_image, 0, 255) 32 | enhanced_image = enhanced_image.astype(np.uint8) 33 | 34 | return enhanced_image -------------------------------------------------------------------------------- /pysnippets/Computer_vision/optical_flow.py: -------------------------------------------------------------------------------- 1 | import cv2 2 | import numpy as np 3 | 4 | def calculate_optical_flow(prev_frame, next_frame): 5 | # Convert frames to grayscale 6 | prev_gray = cv2.cvtColor(prev_frame, cv2.COLOR_BGR2GRAY) 7 | next_gray = cv2.cvtColor(next_frame, cv2.COLOR_BGR2GRAY) 8 | 9 | # Calculate optical flow using Farneback method 10 | flow = cv2.calcOpticalFlowFarneback(prev_gray, next_gray, None, 0.5, 3, 15, 3, 5, 1.2, 0) 11 | 12 | # Create visualization 13 | magnitude, angle = cv2.cartToPolar(flow[..., 0], flow[..., 1]) 14 | 15 | # Create HSV image for visualization 16 | hsv = np.zeros_like(prev_frame) 17 | hsv[..., 1] = 255 # Saturation 18 | 19 | # Use angle for hue and magnitude for value 20 | hsv[..., 0] = angle * 180 / np.pi / 2 21 | hsv[..., 2] = cv2.normalize(magnitude, None, 0, 255, cv2.NORM_MINMAX) 22 | 23 | # Convert HSV to BGR for visualization 24 | flow_visualization = cv2.cvtColor(hsv, cv2.COLOR_HSV2BGR) 25 | 26 | return flow, flow_visualization 27 | -------------------------------------------------------------------------------- /pysnippets/Computer_vision/test_depth_estimation.py: -------------------------------------------------------------------------------- 1 | import cv2 2 | import matplotlib.pyplot as plt 3 | from depth_estimation import estimate_depth 4 | 5 | def test_depth_estimation(): 6 | # Load stereo image pair 7 | left_img = cv2.imread('data/left.jpg') 8 | right_img = cv2.imread('data/right.jpg') 9 | 10 | # Convert to grayscale 11 | left_gray = cv2.cvtColor(left_img, cv2.COLOR_BGR2GRAY) 12 | right_gray = cv2.cvtColor(right_img, cv2.COLOR_BGR2GRAY) 13 | 14 | # Estimate depth map 15 | depth_map = estimate_depth(left_gray, right_gray) 16 | 17 | # Visualize results 18 | plt.figure(figsize=(12,5)) 19 | 20 | plt.subplot(131) 21 | plt.imshow(left_img[...,::-1]) 22 | plt.title('Left Image') 23 | plt.axis('off') 24 | 25 | plt.subplot(132) 26 | plt.imshow(right_img[...,::-1]) 27 | plt.title('Right Image') 28 | plt.axis('off') 29 | 30 | plt.subplot(133) 31 | plt.imshow(depth_map, cmap='plasma') 32 | plt.title('Estimated Depth Map') 33 | plt.colorbar() 34 | plt.axis('off') 35 | 36 | plt.tight_layout() 37 | plt.show() 38 | 39 | if __name__ == '__main__': 40 | test_depth_estimation() -------------------------------------------------------------------------------- /pysnippets/Computer_vision/test_edge_detection.py: -------------------------------------------------------------------------------- 1 | import cv2 2 | import numpy as np 3 | from edge_detection import detect_edges 4 | 5 | # Load a real test image 6 | test_image = cv2.imread('test_image.jpg') 7 | if test_image is None: 8 | # If no image found, create dummy data 9 | test_image = np.random.randint(0, 256, (100, 100, 3), dtype=np.uint8) 10 | 11 | # Convert to grayscale 12 | gray = cv2.cvtColor(test_image, cv2.COLOR_BGR2GRAY) 13 | 14 | # Apply Gaussian blur to reduce noise 15 | blurred = cv2.GaussianBlur(gray, (5, 5), 0) 16 | 17 | # Detect edges using imported function 18 | edges = detect_edges(blurred) 19 | 20 | # Display original and edges side by side 21 | cv2.imshow('Original', test_image) 22 | cv2.imshow('Edges', edges) 23 | 24 | # Wait for key press and close windows 25 | key = cv2.waitKey(0) 26 | if key == ord('q') or key == 27: # Exit on 'q' or ESC 27 | cv2.destroyAllWindows() -------------------------------------------------------------------------------- /pysnippets/Computer_vision/test_image_segmentation.py: -------------------------------------------------------------------------------- 1 | import cv2 2 | import numpy as np 3 | from image_segmentation import segment_image 4 | 5 | # Create test image with two distinct areas 6 | test_image = np.zeros((100, 100, 3), dtype=np.uint8) 7 | cv2.rectangle(test_image, (25, 25), (75, 75), (255, 255, 255), -1) 8 | 9 | # Add some noise to make it more realistic 10 | noise = np.random.normal(0, 25, test_image.shape).astype(np.uint8) 11 | test_image = cv2.add(test_image, noise) 12 | 13 | # Save original image 14 | cv2.imwrite('original.jpg', test_image) 15 | 16 | # Perform segmentation 17 | segmented_image = segment_image(test_image) 18 | 19 | # Display original and segmented images side by side 20 | combined = np.hstack((test_image, segmented_image)) 21 | cv2.imshow('Original | Segmented', combined) 22 | cv2.imwrite('segmented.jpg', segmented_image) 23 | 24 | # Wait for key press and close windows 25 | key = cv2.waitKey(0) 26 | if key == ord('q'): 27 | cv2.destroyAllWindows() -------------------------------------------------------------------------------- /pysnippets/Computer_vision/test_object_detection.py: -------------------------------------------------------------------------------- 1 | import cv2 2 | import numpy as np 3 | from object_detection import detect_objects 4 | 5 | # Dummy data: Create an image with random shapes 6 | test_image = np.zeros((100, 100, 3), dtype=np.uint8) 7 | cv2.rectangle(test_image, (20, 20), (80, 80), (0, 255, 0), -1) # Simulated object 8 | 9 | # Detect objects in the image 10 | detected_objects = detect_objects(test_image) 11 | 12 | # Draw bounding boxes around detected objects 13 | output_image = test_image.copy() 14 | if detected_objects: 15 | for (x, y, w, h) in detected_objects: 16 | # Draw rectangle around detected object 17 | cv2.rectangle(output_image, (x, y), (x + w, y + h), (0, 0, 255), 2) 18 | # Add label 19 | cv2.putText(output_image, 'Object', (x, y-10), 20 | cv2.FONT_HERSHEY_SIMPLEX, 0.5, (0, 0, 255), 2) 21 | 22 | # Display the original and detected objects 23 | cv2.imshow('Original Image', test_image) 24 | cv2.imshow('Object Detection', output_image) 25 | cv2.waitKey(0) 26 | cv2.destroyAllWindows() -------------------------------------------------------------------------------- /pysnippets/DYnamic_classes/Dynamic_class.py: -------------------------------------------------------------------------------- 1 | # Function to dynamically create a function and assign it to a class 2 | def create_dynamic_function(name, expression): 3 | def func(self, x, y): 4 | return eval(expression) 5 | func.__name__ = name 6 | return func 7 | 8 | # Class to hold dynamic functions 9 | class MathOperations: 10 | pass 11 | 12 | # Adding dynamically created functions to the class 13 | MathOperations.add = create_dynamic_function("add", "x + y") 14 | MathOperations.multiply = create_dynamic_function("multiply", "x * y") 15 | 16 | -------------------------------------------------------------------------------- /pysnippets/DYnamic_classes/Property.py: -------------------------------------------------------------------------------- 1 | # Function to create dynamic properties in a class 2 | def create_dynamic_property(name, initial_value=None): 3 | def getter(self): 4 | return getattr(self, f"_{name}", initial_value) 5 | 6 | def setter(self, value): 7 | setattr(self, f"_{name}", value) 8 | 9 | return property(getter, setter) 10 | 11 | # Class to use dynamic properties 12 | class UserProfile: 13 | name = create_dynamic_property("name") 14 | age = create_dynamic_property("age") 15 | 16 | # Creating an instance and setting dynamic properties 17 | user = UserProfile() 18 | user.name = "Alice" 19 | user.age = 25 20 | -------------------------------------------------------------------------------- /pysnippets/DYnamic_classes/__init__.py: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/UTSAVS26/PySnippets/7d663efc569f46c1550a16fbba42fa8e6e815b7e/pysnippets/DYnamic_classes/__init__.py -------------------------------------------------------------------------------- /pysnippets/DYnamic_classes/attribute.py: -------------------------------------------------------------------------------- 1 | # Dynamic attribute assignment to a class instance 2 | class Config: 3 | def __init__(self, **kwargs): 4 | for key, value in kwargs.items(): 5 | setattr(self, key, value) 6 | 7 | # Creating a config object dynamically with different attributes 8 | config = Config(database="MySQL", user="admin", password="securepass") 9 | -------------------------------------------------------------------------------- /pysnippets/DYnamic_classes/method.py: -------------------------------------------------------------------------------- 1 | # Dynamic method creation and assignment 2 | class Calculator: 3 | def __init__(self): 4 | self.operations = {} 5 | 6 | def add_operation(self, name, func): 7 | self.operations[name] = func 8 | setattr(self, name, func) 9 | 10 | # Adding dynamic methods 11 | calc = Calculator() 12 | calc.add_operation("add", lambda x, y: x + y) 13 | calc.add_operation("subtract", lambda x, y: x - y) -------------------------------------------------------------------------------- /pysnippets/DYnamic_classes/test_Dynamic_class.py: -------------------------------------------------------------------------------- 1 | from Dynamic_class import MathOperations 2 | 3 | # Test Cases 4 | def test_dynamic_functions(): 5 | math_ops = MathOperations() 6 | assert math_ops.add(4, 5) == 9, "Test case failed: Incorrect addition result" 7 | assert math_ops.multiply(4, 5) == 20, "Test case failed: Incorrect multiplication result" 8 | 9 | # Running test cases 10 | test_dynamic_functions() 11 | print("Test cases passed for dynamic functions.") 12 | -------------------------------------------------------------------------------- /pysnippets/DYnamic_classes/test_all.py: -------------------------------------------------------------------------------- 1 | import unittest 2 | 3 | # Importing test functions from other test files 4 | from test_property import test_dynamic_property_creation 5 | from test_Dynamic_class import test_dynamic_functions 6 | from test_type import test_dynamic_class_creation 7 | from test_method import test_dynamic_method_creation 8 | from test_attribute import test_dynamic_attribute_assignment 9 | 10 | # Creating a test suite 11 | def suite(): 12 | suite = unittest.TestSuite() 13 | suite.addTest(unittest.FunctionTestCase(test_dynamic_property_creation)) 14 | suite.addTest(unittest.FunctionTestCase(test_dynamic_functions)) 15 | suite.addTest(unittest.FunctionTestCase(test_dynamic_class_creation)) 16 | suite.addTest(unittest.FunctionTestCase(test_dynamic_method_creation)) 17 | suite.addTest(unittest.FunctionTestCase(test_dynamic_attribute_assignment)) 18 | return suite 19 | 20 | # Running the test suite 21 | if __name__ == '__main__': 22 | runner = unittest.TextTestRunner() 23 | runner.run(suite()) 24 | -------------------------------------------------------------------------------- /pysnippets/DYnamic_classes/test_attribute.py: -------------------------------------------------------------------------------- 1 | from attribute import config 2 | 3 | # Test Cases 4 | def test_dynamic_attribute_assignment(): 5 | assert config.database == "MySQL", "Test case failed: Incorrect database" 6 | assert config.user == "admin", "Test case failed: Incorrect user" 7 | assert config.password == "securepass", "Test case failed: Incorrect password" 8 | 9 | # Running test cases 10 | test_dynamic_attribute_assignment() 11 | print("Test cases passed for dynamic attribute assignment.") 12 | -------------------------------------------------------------------------------- /pysnippets/DYnamic_classes/test_method.py: -------------------------------------------------------------------------------- 1 | from method import calc 2 | 3 | # Test Cases 4 | def test_dynamic_method_creation(): 5 | assert calc.add(10, 5) == 15, "Test case failed: Incorrect addition result" 6 | assert calc.subtract(10, 5) == 5, "Test case failed: Incorrect subtraction result" 7 | 8 | # Running test cases 9 | test_dynamic_method_creation() 10 | print("Test cases passed for dynamic method creation.") 11 | -------------------------------------------------------------------------------- /pysnippets/DYnamic_classes/test_property.py: -------------------------------------------------------------------------------- 1 | from Property import user 2 | 3 | # Test Cases 4 | def test_dynamic_property_creation(): 5 | assert user.name == "Alice", "Test case failed: Incorrect name" 6 | assert user.age == 25, "Test case failed: Incorrect age" 7 | 8 | # Running test cases 9 | test_dynamic_property_creation() 10 | print("Test cases passed for dynamic property creation.") 11 | -------------------------------------------------------------------------------- /pysnippets/DYnamic_classes/test_type.py: -------------------------------------------------------------------------------- 1 | from type import DynamicPerson 2 | 3 | # Test Cases 4 | def test_dynamic_class_creation(): 5 | person = DynamicPerson() 6 | assert person.name == "John Doe", "Test case failed: Incorrect name" 7 | assert person.age == 30, "Test case failed: Incorrect age" 8 | assert person.greet() == "Hello, I am John Doe and I am 30 years old.", "Test case failed: Incorrect greeting" 9 | 10 | # Running test case 11 | test_dynamic_class_creation() 12 | print("Test case passed for dynamic class creation.") 13 | -------------------------------------------------------------------------------- /pysnippets/DYnamic_classes/type.py: -------------------------------------------------------------------------------- 1 | # Dynamic class creation using `type` 2 | def create_dynamic_class(class_name, base_classes=(), attributes=None): 3 | attributes = attributes or {} 4 | return type(class_name, base_classes, attributes) 5 | 6 | # Define a class with dynamic attributes 7 | DynamicPerson = create_dynamic_class("DynamicPerson", attributes={ 8 | 'name': "John Doe", 9 | 'age': 30, 10 | 'greet': lambda self: f"Hello, I am {self.name} and I am {self.age} years old." 11 | }) 12 | -------------------------------------------------------------------------------- /pysnippets/Data_preprocessing/__init__.py: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/UTSAVS26/PySnippets/7d663efc569f46c1550a16fbba42fa8e6e815b7e/pysnippets/Data_preprocessing/__init__.py -------------------------------------------------------------------------------- /pysnippets/Dynamic Programming/__init__.py: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/UTSAVS26/PySnippets/7d663efc569f46c1550a16fbba42fa8e6e815b7e/pysnippets/Dynamic Programming/__init__.py -------------------------------------------------------------------------------- /pysnippets/Dynamic Programming/how-to-identify.md: -------------------------------------------------------------------------------- 1 | To identify whether a problem can be solved using Dynamic Programming (DP), you typically look for two key properties: 2 | 3 | ### Optimal Substructure: 4 | 5 | - A problem exhibits optimal substructure if an optimal solution to the problem can be constructed from optimal solutions to its subproblems. In other words, if you can solve a problem by combining the solutions of smaller instances of the same problem, it likely has optimal substructure. 6 | 7 | ### Overlapping Subproblems: 8 | 9 | - A problem has overlapping subproblems if the same subproblems are solved multiple times during the computation of the solution. DP is useful when the same calculations are needed multiple times, and it allows you to store and reuse these solutions to avoid redundant work. 10 | -------------------------------------------------------------------------------- /pysnippets/Dynamic Programming/matrix_chain_multiplication.py: -------------------------------------------------------------------------------- 1 | def f(arr, i, j): 2 | # Base condition 3 | if i == j: 4 | return 0 5 | 6 | mini = float('inf') 7 | 8 | # Partitioning loop 9 | for k in range(i, j): 10 | ans = f(arr, i, k) + f(arr, k + 1, j) + arr[i - 1] * arr[k] * arr[j] 11 | mini = min(mini, ans) 12 | 13 | return mini 14 | 15 | def matrix_multiplication(arr, N): 16 | i = 1 17 | j = N - 1 18 | return f(arr, i, j) 19 | 20 | def main(): 21 | arr = [5, 10, 15, 20, 25] 22 | n = len(arr) 23 | print("The minimum number of operations are", matrix_multiplication(arr, n)) 24 | 25 | if __name__ == "__main__": 26 | main() 27 | -------------------------------------------------------------------------------- /pysnippets/Files/__init__.py: -------------------------------------------------------------------------------- 1 | # __init__.py 2 | 3 | # This file allows the snippets folder to be treated as a package. 4 | # It can be empty or used to expose certain functions for easy imports. 5 | -------------------------------------------------------------------------------- /pysnippets/Files/file_reader.py: -------------------------------------------------------------------------------- 1 | # file_reader.py 2 | 3 | 4 | def read_file(file_path): 5 | """ 6 | Read the contents of a text file. 7 | 8 | Args: 9 | file_path (str): The path to the file. 10 | 11 | Returns: 12 | str: The contents of the file as a string, or None if an error occurred. 13 | 14 | Example: 15 | >>> read_file('example.txt') 16 | 'File contents here...' 17 | """ 18 | try: 19 | with open(file_path, "r") as file: 20 | return file.read() 21 | except FileNotFoundError: 22 | print(f"Error: File '{file_path}' not found.") 23 | return None 24 | except IOError as e: 25 | print(f"Error reading file '{file_path}': {e}") 26 | return None 27 | 28 | # Example usage 29 | if __name__ == "__main__": 30 | content = read_file("example.txt") 31 | if content is not None: 32 | print(content) -------------------------------------------------------------------------------- /pysnippets/Files/sample_data.pkl: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/UTSAVS26/PySnippets/7d663efc569f46c1550a16fbba42fa8e6e815b7e/pysnippets/Files/sample_data.pkl -------------------------------------------------------------------------------- /pysnippets/GUIinPy/__init__.py: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/UTSAVS26/PySnippets/7d663efc569f46c1550a16fbba42fa8e6e815b7e/pysnippets/GUIinPy/__init__.py -------------------------------------------------------------------------------- /pysnippets/GUIinPy/dialogs.py: -------------------------------------------------------------------------------- 1 | import tkinter as tk 2 | from tkinter import messagebox 3 | 4 | def show_info(title, message): 5 | messagebox.showinfo(title, message) 6 | 7 | def show_warning(title, message): 8 | messagebox.showwarning(title, message) -------------------------------------------------------------------------------- /pysnippets/GUIinPy/guiLogic.py: -------------------------------------------------------------------------------- 1 | # gui_logic.py 2 | def handle_input(user_input): 3 | """Handles user input and returns appropriate messages.""" 4 | if user_input: 5 | return f"You entered: {user_input}" 6 | else: 7 | return "Please enter some text!" 8 | -------------------------------------------------------------------------------- /pysnippets/GUIinPy/menus.py: -------------------------------------------------------------------------------- 1 | import tkinter as tk 2 | from tkinter import Menu 3 | 4 | def create_menu(root): 5 | menubar = Menu(root) 6 | filemenu = Menu(menubar, tearoff=0) 7 | filemenu.add_command(label="Open", command=lambda: None) 8 | filemenu.add_command(label="Save", command=lambda: None) 9 | filemenu.add_separator() 10 | filemenu.add_command(label="Exit", command=root.quit) 11 | menubar.add_cascade(label="File", menu=filemenu) 12 | root.config(menu=menubar) 13 | return menubar -------------------------------------------------------------------------------- /pysnippets/Hashing/__init__.py: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/UTSAVS26/PySnippets/7d663efc569f46c1550a16fbba42fa8e6e815b7e/pysnippets/Hashing/__init__.py -------------------------------------------------------------------------------- /pysnippets/Hashing/hmac_generator.py: -------------------------------------------------------------------------------- 1 | import hmac 2 | import hashlib 3 | import logging 4 | from dataclasses import dataclass 5 | 6 | logging.basicConfig(level=logging.INFO, format='%(asctime)s - %(levelname)s - %(message)s') 7 | 8 | @dataclass 9 | class HMACGenerator: 10 | key: bytes 11 | message: str 12 | digestmod: str = 'sha256' 13 | 14 | def generate_hmac(self) -> str: 15 | try: 16 | digest = getattr(hashlib, self.digestmod) 17 | hmac_obj = hmac.new(self.key, self.message.encode(), digest) 18 | hmac_hex = hmac_obj.hexdigest() 19 | logging.info(f"Generated HMAC for message '{self.message}' using key '{self.key.decode()}': {hmac_hex}") 20 | return hmac_hex 21 | except AttributeError: 22 | logging.error(f"Unsupported digest mode: {self.digestmod}") 23 | raise 24 | except Exception as e: 25 | logging.error(f"Error generating HMAC: {e}") 26 | raise -------------------------------------------------------------------------------- /pysnippets/Hashing/md5_hasher.py: -------------------------------------------------------------------------------- 1 | import hashlib 2 | import logging 3 | from dataclasses import dataclass 4 | 5 | logging.basicConfig(level=logging.INFO, format='%(asctime)s - %(levelname)s - %(message)s') 6 | 7 | @dataclass 8 | class MD5Hasher: 9 | data: str 10 | 11 | def hash(self) -> str: 12 | try: 13 | hashed = hashlib.md5(self.data.encode()).hexdigest() 14 | logging.info(f"MD5 hashed '{self.data}' to '{hashed}'") 15 | return hashed 16 | except Exception as e: 17 | logging.error(f"Error hashing data: {e}") 18 | raise -------------------------------------------------------------------------------- /pysnippets/Hashing/pbkdf2_hasher.py: -------------------------------------------------------------------------------- 1 | import hashlib 2 | import logging 3 | from dataclasses import dataclass 4 | 5 | logging.basicConfig(level=logging.INFO, format='%(asctime)s - %(levelname)s - %(message)s') 6 | 7 | @dataclass 8 | class PBKDF2Hasher: 9 | password: str 10 | salt: bytes 11 | iterations: int = 100000 12 | dklen: int = 32 13 | hash_name: str = 'sha256' 14 | 15 | def hash_password(self) -> bytes: 16 | try: 17 | hashed = hashlib.pbkdf2_hmac( 18 | self.hash_name, 19 | self.password.encode(), 20 | self.salt, 21 | self.iterations, 22 | self.dklen 23 | ) 24 | logging.info(f"Hashed password using PBKDF2: {hashed.hex()}") 25 | return hashed 26 | except Exception as e: 27 | logging.error(f"Error hashing password: {e}") 28 | raise -------------------------------------------------------------------------------- /pysnippets/Hashing/sha3_hasher.py: -------------------------------------------------------------------------------- 1 | import hashlib 2 | import logging 3 | from dataclasses import dataclass 4 | 5 | logging.basicConfig(level=logging.INFO, format='%(asctime)s - %(levelname)s - %(message)s') 6 | 7 | @dataclass 8 | class SHA3Hasher: 9 | data: str 10 | variant: str = 'sha3_256' 11 | 12 | def hash_data(self) -> str: 13 | try: 14 | hash_func = getattr(hashlib, self.variant) 15 | hashed = hash_func(self.data.encode()).hexdigest() 16 | logging.info(f"SHA3 hashed '{self.data}' using {self.variant}: {hashed}") 17 | return hashed 18 | except AttributeError: 19 | logging.error(f"Unsupported SHA3 variant: {self.variant}") 20 | raise 21 | except Exception as e: 22 | logging.error(f"Error hashing data with SHA3: {e}") 23 | raise -------------------------------------------------------------------------------- /pysnippets/Hashing/test_bcrypt_hasher.py: -------------------------------------------------------------------------------- 1 | import unittest 2 | from bcrypt_hasher import BcryptHasher 3 | import bcrypt 4 | 5 | class TestBcryptHasher(unittest.TestCase): 6 | def test_hash_and_check_password(self): 7 | hasher = BcryptHasher(password="mypassword") 8 | hashed = hasher.hash_password() 9 | self.assertTrue(hasher.check_password(hashed)) 10 | 11 | def test_check_password_incorrect(self): 12 | hasher = BcryptHasher(password="mypassword") 13 | hashed = hasher.hash_password() 14 | hasher_wrong = BcryptHasher(password="wrongpassword") 15 | self.assertFalse(hasher_wrong.check_password(hashed)) 16 | 17 | def test_hash_with_custom_rounds(self): 18 | hasher = BcryptHasher(password="mypassword", rounds=14) 19 | hashed = hasher.hash_password() 20 | self.assertTrue(hasher.check_password(hashed)) 21 | self.assertTrue(hashed.startswith(b'$2b$14$')) 22 | 23 | if __name__ == "__main__": 24 | unittest.main() -------------------------------------------------------------------------------- /pysnippets/Hashing/test_hmac_generator.py: -------------------------------------------------------------------------------- 1 | import unittest 2 | from hmac_generator import HMACGenerator 3 | import hmac 4 | import hashlib 5 | 6 | class TestHMACGenerator(unittest.TestCase): 7 | def test_generate_hmac_sha256(self): 8 | generator = HMACGenerator(key=b'secret_key', message="Test Message", digestmod='sha256') 9 | expected = hmac.new(b'secret_key', b'Test Message', hashlib.sha256).hexdigest() 10 | self.assertEqual(generator.generate_hmac(), expected) 11 | 12 | def test_generate_hmac_sha1(self): 13 | generator = HMACGenerator(key=b'secret_key', message="Test Message", digestmod='sha1') 14 | expected = hmac.new(b'secret_key', b'Test Message', hashlib.sha1).hexdigest() 15 | self.assertEqual(generator.generate_hmac(), expected) 16 | 17 | def test_invalid_digestmod(self): 18 | generator = HMACGenerator(key=b'secret_key', message="Test Message", digestmod='invalid') 19 | with self.assertRaises(AttributeError): 20 | generator.generate_hmac() 21 | 22 | if __name__ == "__main__": 23 | unittest.main() -------------------------------------------------------------------------------- /pysnippets/Hashing/test_md5_hasher.py: -------------------------------------------------------------------------------- 1 | import unittest 2 | from md5_hasher import MD5Hasher 3 | 4 | class TestMD5Hasher(unittest.TestCase): 5 | def test_hash_normal_string(self): 6 | hasher = MD5Hasher(data="Hello, World!") 7 | self.assertEqual(hasher.hash(), "fc3ff98e8c6a0d3087d515c0473f8677") 8 | 9 | def test_hash_empty_string(self): 10 | hasher = MD5Hasher(data="") 11 | self.assertEqual(hasher.hash(), "d41d8cd98f00b204e9800998ecf8427e") 12 | 13 | def test_hash_unicode_string(self): 14 | hasher = MD5Hasher(data="こんにちは") 15 | self.assertEqual(hasher.hash(), "9d735278cfbdb946834416adfb5aaf6c") 16 | 17 | if __name__ == "__main__": 18 | unittest.main() -------------------------------------------------------------------------------- /pysnippets/Hashing/test_pbkdf2_hasher.py: -------------------------------------------------------------------------------- 1 | import unittest 2 | import os 3 | from pbkdf2_hasher import PBKDF2Hasher 4 | import hashlib 5 | 6 | class TestPBKDF2Hasher(unittest.TestCase): 7 | def test_hash_password_default(self): 8 | salt = b'salt123456789012' 9 | hasher = PBKDF2Hasher(password="password", salt=salt) 10 | expected = hashlib.pbkdf2_hmac('sha256', b'password', salt, 100000, 32) 11 | self.assertEqual(hasher.hash_password(), expected) 12 | 13 | def test_hash_password_custom_iterations(self): 14 | salt = b'salt123456789012' 15 | hasher = PBKDF2Hasher(password="password", salt=salt, iterations=200000) 16 | expected = hashlib.pbkdf2_hmac('sha256', b'password', salt, 200000, 32) 17 | self.assertEqual(hasher.hash_password(), expected) 18 | 19 | def test_hash_password_invalid_salt(self): 20 | with self.assertRaises(AttributeError): 21 | PBKDF2Hasher(password="password", salt="not_bytes").hash_password() 22 | 23 | if __name__ == "__main__": 24 | unittest.main() -------------------------------------------------------------------------------- /pysnippets/Hashing/test_sha3_hasher.py: -------------------------------------------------------------------------------- 1 | import unittest 2 | from sha3_hasher import SHA3Hasher 3 | import hashlib 4 | 5 | class TestSHA3Hasher(unittest.TestCase): 6 | def test_hash_sha3_256(self): 7 | hasher = SHA3Hasher(data="Test Data", variant='sha3_256') 8 | expected = hashlib.sha3_256(b'Test Data').hexdigest() 9 | self.assertEqual(hasher.hash_data(), expected) 10 | 11 | def test_hash_sha3_512(self): 12 | hasher = SHA3Hasher(data="Test Data", variant='sha3_512') 13 | expected = hashlib.sha3_512(b'Test Data').hexdigest() 14 | self.assertEqual(hasher.hash_data(), expected) 15 | 16 | def test_invalid_variant(self): 17 | hasher = SHA3Hasher(data="Test Data", variant='sha3_999') 18 | with self.assertRaises(AttributeError): 19 | hasher.hash_data() 20 | 21 | if __name__ == "__main__": 22 | unittest.main() -------------------------------------------------------------------------------- /pysnippets/IDT_library/__init__.py: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/UTSAVS26/PySnippets/7d663efc569f46c1550a16fbba42fa8e6e815b7e/pysnippets/IDT_library/__init__.py -------------------------------------------------------------------------------- /pysnippets/Image_Processing/__init__.py: -------------------------------------------------------------------------------- 1 | from .image_processing import resize, filter_image, rotate 2 | 3 | __all__ = ["resize", "filter_image", "rotate"] 4 | -------------------------------------------------------------------------------- /pysnippets/Image_Processing/image_processing.py: -------------------------------------------------------------------------------- 1 | from PIL import Image, ImageFilter 2 | 3 | def resize(image_path, output_path, size): 4 | """ 5 | Resizes the image to the specified size. 6 | """ 7 | with Image.open(image_path) as img: 8 | img = img.resize(size, Image.ANTIALIAS) # Use ANTIALIAS for better quality 9 | img.save(output_path) 10 | 11 | def filter_image(image_path, output_path, filter_type): 12 | """ 13 | Applies a filter to the image and saves it. 14 | """ 15 | with Image.open(image_path) as img: 16 | if filter_type == 'BLUR': 17 | img = img.filter(ImageFilter.BLUR) 18 | elif filter_type == 'CONTOUR': 19 | img = img.filter(ImageFilter.CONTOUR) 20 | img.save(output_path) 21 | 22 | def rotate(image_path, output_path, angle): 23 | """ 24 | Rotates the image by the specified angle. 25 | """ 26 | with Image.open(image_path) as img: 27 | img = img.rotate(angle, expand=True) # Expand to fit the new size 28 | img.save(output_path) -------------------------------------------------------------------------------- /pysnippets/Image_Processing/test_image.webp: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/UTSAVS26/PySnippets/7d663efc569f46c1550a16fbba42fa8e6e815b7e/pysnippets/Image_Processing/test_image.webp -------------------------------------------------------------------------------- /pysnippets/Image_Processing/test_image_processing.py: -------------------------------------------------------------------------------- 1 | import unittest 2 | from image_processing import resize, filter_image, rotate 3 | 4 | class TestImageProcessing(unittest.TestCase): 5 | def test_resize(self): 6 | resize('input_image.jpg', 'output_image_resized.jpg', (100, 100)) 7 | # Add assertions to check if the output image is as expected 8 | 9 | def test_filter_image(self): 10 | filter_image('input_image.jpg', 'output_image_filtered.jpg', 'BLUR') 11 | # Add assertions to check if the output image is as expected 12 | 13 | def test_rotate(self): 14 | rotate('input_image.jpg', 'output_image_rotated.jpg', 90) 15 | # Add assertions to check if the output image is as expected 16 | 17 | if __name__ == "__main__": 18 | unittest.main() -------------------------------------------------------------------------------- /pysnippets/LinkedList/_init_.py: -------------------------------------------------------------------------------- 1 | import Circular_Linked_List 2 | import Doubly_Linked_List 3 | import Singly_Linked_List 4 | 5 | __all__ = ["Circular_Linked_List", "Doubly_Linked_List", "Singly_Linked_List"] -------------------------------------------------------------------------------- /pysnippets/ML_snippets/_init__.py: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/UTSAVS26/PySnippets/7d663efc569f46c1550a16fbba42fa8e6e815b7e/pysnippets/ML_snippets/_init__.py -------------------------------------------------------------------------------- /pysnippets/Mathematics/pascals_triangle.py: -------------------------------------------------------------------------------- 1 | import logging 2 | from typing import List 3 | 4 | # Configure logging 5 | logging.basicConfig(level=logging.DEBUG) 6 | 7 | def pascals_triangle(rows: int) -> List[List[int]]: 8 | """ 9 | Generate Pascal's Triangle up to a given number of rows. 10 | 11 | Args: 12 | rows (int): The number of rows to generate in Pascal's Triangle. 13 | 14 | Returns: 15 | list of lists: Pascal's Triangle as a list of rows, where each row is a list of integers. 16 | """ 17 | if rows <= 0: 18 | raise ValueError("'rows' must be a positive integer.") 19 | 20 | triangle = [] 21 | for i in range(rows): 22 | row = [1] * (i + 1) 23 | for j in range(1, i): 24 | row[j] = triangle[i - 1][j - 1] + triangle[i - 1][j] 25 | triangle.append(row) 26 | 27 | logging.debug(f"Generated Pascal's Triangle with {rows} rows: {triangle}") 28 | return triangle 29 | 30 | # Example usage 31 | if __name__ == "__main__": 32 | print(pascals_triangle(5)) -------------------------------------------------------------------------------- /pysnippets/Memoisation/__init__.py: -------------------------------------------------------------------------------- 1 | from .fibonacci import fibonacci 2 | from .knapsack import knapsack 3 | from .lcs import lcs 4 | 5 | __all__ = ["fibonacci", "knapsack", "lcs"] 6 | -------------------------------------------------------------------------------- /pysnippets/Memoisation/decorator.py: -------------------------------------------------------------------------------- 1 | import logging 2 | from functools import wraps 3 | 4 | logging.basicConfig(level=logging.INFO) 5 | logger = logging.getLogger(__name__) 6 | 7 | def memoize(func): 8 | cache = {} 9 | 10 | @wraps(func) 11 | def wrapper(*args): 12 | try: 13 | if args in cache: 14 | logger.info(f"Fetching from cache for args: {args}") 15 | return cache[args] 16 | result = func(*args) 17 | cache[args] = result 18 | logger.info(f"Caching result for args: {args}") 19 | return result 20 | except Exception as e: 21 | logger.error(f"Error in memoize decorator: {e}") 22 | raise 23 | return wrapper -------------------------------------------------------------------------------- /pysnippets/Memoisation/factorial.py: -------------------------------------------------------------------------------- 1 | import logging 2 | from dataclasses import dataclass 3 | from decorator import memoize 4 | 5 | logging.basicConfig(level=logging.INFO) 6 | logger = logging.getLogger(__name__) 7 | 8 | @dataclass 9 | class FactorialCalculator: 10 | @staticmethod 11 | @memoize 12 | def factorial(n: int) -> int: 13 | if n < 0: 14 | raise ValueError("Factorial is not defined for negative numbers.") 15 | elif n == 0 or n == 1: 16 | return 1 17 | return n * FactorialCalculator.factorial(n - 1) -------------------------------------------------------------------------------- /pysnippets/Memoisation/fibonacci.py: -------------------------------------------------------------------------------- 1 | import logging 2 | from dataclasses import dataclass 3 | from decorator import memoize 4 | 5 | logging.basicConfig(level=logging.INFO) 6 | logger = logging.getLogger(__name__) 7 | 8 | @dataclass 9 | class FibonacciCalculator: 10 | @staticmethod 11 | @memoize 12 | def fibonacci(n: int) -> int: 13 | if n <= 0: 14 | raise ValueError("Input must be a positive integer.") 15 | elif n == 1 or n == 2: 16 | return 1 17 | return FibonacciCalculator.fibonacci(n-1) + FibonacciCalculator.fibonacci(n-2) -------------------------------------------------------------------------------- /pysnippets/Memoisation/knapsack.py: -------------------------------------------------------------------------------- 1 | import logging 2 | from dataclasses import dataclass 3 | from decorator import memoize 4 | from typing import Tuple 5 | 6 | logging.basicConfig(level=logging.INFO) 7 | logger = logging.getLogger(__name__) 8 | 9 | @dataclass(frozen=True) 10 | class Item: 11 | value: int 12 | weight: int 13 | 14 | @dataclass 15 | class KnapsackSolver: 16 | @staticmethod 17 | @memoize 18 | def knapsack(max_weight: int, items: Tuple[Item, ...], n: int) -> int: 19 | if n == 0 or max_weight == 0: 20 | return 0 21 | current_item = items[n-1] 22 | if current_item.weight > max_weight: 23 | return KnapsackSolver.knapsack(max_weight, items, n-1) 24 | else: 25 | return max( 26 | current_item.value + KnapsackSolver.knapsack(max_weight - current_item.weight, items, n-1), 27 | KnapsackSolver.knapsack(max_weight, items, n-1) 28 | ) -------------------------------------------------------------------------------- /pysnippets/Memoisation/lcs.py: -------------------------------------------------------------------------------- 1 | import logging 2 | from dataclasses import dataclass 3 | from decorator import memoize 4 | 5 | logging.basicConfig(level=logging.INFO) 6 | logger = logging.getLogger(__name__) 7 | 8 | @dataclass 9 | class LCSSolver: 10 | @staticmethod 11 | @memoize 12 | def lcs(X: str, Y: str, m: int, n: int) -> int: 13 | if m == 0 or n == 0: 14 | return 0 15 | if X[m-1] == Y[n-1]: 16 | return 1 + LCSSolver.lcs(X, Y, m-1, n-1) 17 | else: 18 | return max(LCSSolver.lcs(X, Y, m, n-1), LCSSolver.lcs(X, Y, m-1, n)) -------------------------------------------------------------------------------- /pysnippets/Memoisation/test_class_based_memoization.py: -------------------------------------------------------------------------------- 1 | import unittest 2 | from class_based_memoization import CombinatorialCalculator 3 | 4 | class TestCombinatorialCalculator(unittest.TestCase): 5 | 6 | def setUp(self): 7 | self.calculator = CombinatorialCalculator() 8 | 9 | def test_combination_standard_cases(self): 10 | self.assertEqual(self.calculator.get_combination(5, 2), 10) 11 | self.assertEqual(self.calculator.get_combination(10, 5), 252) 12 | self.assertEqual(self.calculator.get_combination(0, 0), 1) 13 | 14 | def test_combination_edge_cases(self): 15 | self.assertEqual(self.calculator.get_combination(5, 0), 1) 16 | self.assertEqual(self.calculator.get_combination(5, 5), 1) 17 | self.assertEqual(self.calculator.get_combination(5, 6), 0) 18 | 19 | def test_combination_invalid_input(self): 20 | with self.assertRaises(TypeError): 21 | self.calculator.get_combination("5", 2) 22 | with self.assertRaises(TypeError): 23 | self.calculator.get_combination(5, "2") 24 | 25 | if __name__ == "__main__": 26 | unittest.main() -------------------------------------------------------------------------------- /pysnippets/Memoisation/test_decorator.py: -------------------------------------------------------------------------------- 1 | import unittest 2 | from decorator import memoize 3 | 4 | class TestMemoizeDecorator(unittest.TestCase): 5 | 6 | def test_memoize_add_function(self): 7 | call_count = 0 8 | 9 | @memoize 10 | def add(a, b): 11 | nonlocal call_count 12 | call_count += 1 13 | return a + b 14 | 15 | self.assertEqual(add(2, 3), 5) 16 | self.assertEqual(add(2, 3), 5) 17 | self.assertEqual(call_count, 1) 18 | 19 | if __name__ == "__main__": 20 | unittest.main() -------------------------------------------------------------------------------- /pysnippets/Memoisation/test_factorial.py: -------------------------------------------------------------------------------- 1 | import unittest 2 | from factorial import FactorialCalculator 3 | 4 | class TestFactorialCalculator(unittest.TestCase): 5 | 6 | def test_factorial_standard_cases(self): 7 | self.assertEqual(FactorialCalculator.factorial(0), 1) 8 | self.assertEqual(FactorialCalculator.factorial(1), 1) 9 | self.assertEqual(FactorialCalculator.factorial(5), 120) 10 | self.assertEqual(FactorialCalculator.factorial(10), 3628800) 11 | 12 | def test_factorial_invalid_input(self): 13 | with self.assertRaises(ValueError): 14 | FactorialCalculator.factorial(-1) 15 | with self.assertRaises(ValueError): 16 | FactorialCalculator.factorial(-10) 17 | 18 | if __name__ == "__main__": 19 | unittest.main() -------------------------------------------------------------------------------- /pysnippets/Memoisation/test_fibonacci.py: -------------------------------------------------------------------------------- 1 | import unittest 2 | from fibonacci import FibonacciCalculator 3 | 4 | class TestFibonacciCalculator(unittest.TestCase): 5 | 6 | def test_fibonacci_standard_cases(self): 7 | self.assertEqual(FibonacciCalculator.fibonacci(1), 1) 8 | self.assertEqual(FibonacciCalculator.fibonacci(5), 5) 9 | self.assertEqual(FibonacciCalculator.fibonacci(10), 55) 10 | 11 | def test_fibonacci_invalid_input(self): 12 | with self.assertRaises(ValueError): 13 | FibonacciCalculator.fibonacci(0) 14 | with self.assertRaises(ValueError): 15 | FibonacciCalculator.fibonacci(-5) 16 | 17 | if __name__ == "__main__": 18 | unittest.main() -------------------------------------------------------------------------------- /pysnippets/Memoisation/test_knapsack.py: -------------------------------------------------------------------------------- 1 | import unittest 2 | from knapsack import KnapsackSolver, Item 3 | 4 | class TestKnapsackSolver(unittest.TestCase): 5 | 6 | def test_knapsack_standard_case(self): 7 | items = ( 8 | Item(value=60, weight=10), 9 | Item(value=100, weight=20), 10 | Item(value=120, weight=30), 11 | ) 12 | self.assertEqual(KnapsackSolver.knapsack(50, items, 3), 220) 13 | 14 | def test_knapsack_no_items(self): 15 | items = () 16 | self.assertEqual(KnapsackSolver.knapsack(50, items, 0), 0) 17 | 18 | def test_knapsack_zero_capacity(self): 19 | items = ( 20 | Item(value=60, weight=10), 21 | ) 22 | self.assertEqual(KnapsackSolver.knapsack(0, items, 1), 0) 23 | 24 | def test_knapsack_item_exceeds_capacity(self): 25 | items = ( 26 | Item(value=100, weight=60), 27 | ) 28 | self.assertEqual(KnapsackSolver.knapsack(50, items, 1), 0) 29 | 30 | if __name__ == "__main__": 31 | unittest.main() -------------------------------------------------------------------------------- /pysnippets/Memoisation/test_lcs.py: -------------------------------------------------------------------------------- 1 | import unittest 2 | from lcs import LCSSolver 3 | 4 | class TestLCSSolver(unittest.TestCase): 5 | 6 | def test_lcs_standard_case(self): 7 | self.assertEqual(LCSSolver.lcs("AGGTAB", "GXTXAYB", 6, 7), 4) 8 | 9 | def test_lcs_no_common_subsequence(self): 10 | self.assertEqual(LCSSolver.lcs("ABC", "DEF", 3, 3), 0) 11 | 12 | def test_lcs_empty_string(self): 13 | self.assertEqual(LCSSolver.lcs("", "ABC", 0, 3), 0) 14 | self.assertEqual(LCSSolver.lcs("ABC", "", 3, 0), 0) 15 | 16 | def test_lcs_complete_overlap(self): 17 | self.assertEqual(LCSSolver.lcs("ABC", "ABC", 3, 3), 3) 18 | 19 | if __name__ == "__main__": 20 | unittest.main() -------------------------------------------------------------------------------- /pysnippets/NLP/__init__.py: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/UTSAVS26/PySnippets/7d663efc569f46c1550a16fbba42fa8e6e815b7e/pysnippets/NLP/__init__.py -------------------------------------------------------------------------------- /pysnippets/NLP/cosine_similarity_texts.py: -------------------------------------------------------------------------------- 1 | from sklearn.feature_extraction.text import CountVectorizer 2 | from sklearn.metrics.pairwise import cosine_similarity 3 | 4 | def cosine_similarity_texts(text1: str, text2: str) -> float: 5 | vectorizer = CountVectorizer() 6 | vectors = vectorizer.fit_transform([text1, text2]) 7 | return cosine_similarity(vectors)[0, 1] -------------------------------------------------------------------------------- /pysnippets/NLP/extract_entities.py: -------------------------------------------------------------------------------- 1 | import spacy 2 | from typing import List, Tuple, Optional 3 | 4 | def extract_entities(text: str) -> Optional[List[Tuple[str, str]]]: 5 | nlp = spacy.load("en_core_web_sm") 6 | doc = nlp(text) 7 | return [(ent.text, ent.label_) for ent in doc.ents] -------------------------------------------------------------------------------- /pysnippets/NLP/generate_text.py: -------------------------------------------------------------------------------- 1 | import random 2 | 3 | def generate_text(text: str, n: int = 3) -> str: 4 | words = text.split() 5 | index = random.randint(0, len(words) - n) 6 | return ' '.join(words[index:index+n]) -------------------------------------------------------------------------------- /pysnippets/NLP/lda_topic_modeling.py: -------------------------------------------------------------------------------- 1 | from sklearn.feature_extraction.text import CountVectorizer 2 | from sklearn.decomposition import LatentDirichletAllocation 3 | from typing import List 4 | 5 | def lda_topic_modeling(documents: List[str], n_topics: int = 2): 6 | vectorizer = CountVectorizer() 7 | X = vectorizer.fit_transform(documents) 8 | lda = LatentDirichletAllocation(n_components=n_topics) 9 | lda.fit(X) 10 | return lda.components_ -------------------------------------------------------------------------------- /pysnippets/NLP/lemmatize_text.py: -------------------------------------------------------------------------------- 1 | from nltk.stem import WordNetLemmatizer 2 | 3 | def lemmatize_text(text: str) -> str: 4 | lemmatizer = WordNetLemmatizer() 5 | words = text.split() 6 | lemmatized_words = [lemmatizer.lemmatize(word) for word in words] 7 | return ' '.join(lemmatized_words) -------------------------------------------------------------------------------- /pysnippets/NLP/preprocess_text.py: -------------------------------------------------------------------------------- 1 | from nltk.tokenize import word_tokenize 2 | from nltk.corpus import stopwords 3 | 4 | def preprocess_text(text: str) -> str: 5 | stop_words = set(stopwords.words('english')) 6 | words = word_tokenize(text) 7 | filtered_words = [word for word in words if word.lower() not in stop_words] 8 | return ' '.join(filtered_words) -------------------------------------------------------------------------------- /pysnippets/NLP/stem_text.py: -------------------------------------------------------------------------------- 1 | from nltk.stem import PorterStemmer 2 | 3 | def stem_text(text: str) -> str: 4 | stemmer = PorterStemmer() 5 | words = text.split() 6 | stemmed_words = [stemmer.stem(word) for word in words] 7 | return ' '.join(stemmed_words) -------------------------------------------------------------------------------- /pysnippets/NLP/tfidf_vectorize.py: -------------------------------------------------------------------------------- 1 | from sklearn.feature_extraction.text import TfidfVectorizer 2 | from typing import List, Optional 3 | import numpy as np 4 | def tfidf_vectorize(documents: List[str]) -> Optional[np.ndarray]: 5 | vectorizer = TfidfVectorizer() 6 | return vectorizer.fit_transform(documents).toarray() -------------------------------------------------------------------------------- /pysnippets/NLP/tokenize_text.py: -------------------------------------------------------------------------------- 1 | from dataclasses import dataclass 2 | from typing import List, Optional 3 | from nltk.tokenize import word_tokenize, sent_tokenize 4 | 5 | @dataclass 6 | class TokenizationResult: 7 | words: Optional[List[str]] = None 8 | sentences: Optional[List[str]] = None 9 | 10 | def tokenize_text(text: str) -> TokenizationResult: 11 | words = word_tokenize(text) 12 | sentences = sent_tokenize(text) 13 | return TokenizationResult(words=words, sentences=sentences) -------------------------------------------------------------------------------- /pysnippets/NLP/train_text_classifier.py: -------------------------------------------------------------------------------- 1 | from sklearn.feature_extraction.text import CountVectorizer 2 | from sklearn.naive_bayes import MultinomialNB 3 | from typing import List 4 | 5 | def train_text_classifier(documents: List[str], labels: List[int]): 6 | vectorizer = CountVectorizer() 7 | X = vectorizer.fit_transform(documents) 8 | classifier = MultinomialNB() 9 | classifier.fit(X, labels) 10 | return classifier, vectorizer -------------------------------------------------------------------------------- /pysnippets/NLP/word2vec_similarity.py: -------------------------------------------------------------------------------- 1 | from gensim.models import KeyedVectors 2 | 3 | def word2vec_similarity(word1: str, word2: str, model_path: str = "path/to/word2vec.bin") -> float: 4 | model = KeyedVectors.load_word2vec_format(model_path, binary=True) 5 | return model.similarity(word1, word2) -------------------------------------------------------------------------------- /pysnippets/Numbers/__init__.py: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/UTSAVS26/PySnippets/7d663efc569f46c1550a16fbba42fa8e6e815b7e/pysnippets/Numbers/__init__.py -------------------------------------------------------------------------------- /pysnippets/Numbers/binary_to_decimal.py: -------------------------------------------------------------------------------- 1 | def binary_to_decimal(binary_str): 2 | try: 3 | decimal_number = int(binary_str, 2) 4 | return decimal_number 5 | except ValueError: 6 | return "Invalid binary number" 7 | 8 | # Example usage 9 | binary_str = "1010" 10 | decimal_number = binary_to_decimal(binary_str) 11 | print(f"The decimal representation of binary {binary_str} is {decimal_number}") 12 | 13 | # Edge Cases and Limitations: 14 | # - Input: "2" (Invalid binary number) 15 | # - Input: "" (Empty string) 16 | 17 | # Optional Improvements: 18 | # - Add support for floating-point binary numbers -------------------------------------------------------------------------------- /pysnippets/Numbers/decimal_to-binary.py: -------------------------------------------------------------------------------- 1 | def decimal_to_binary(decimal_number): 2 | if isinstance(decimal_number, int): 3 | return bin(decimal_number)[2:] 4 | return "Invalid decimal number" 5 | 6 | # Example usage 7 | decimal_number = 10 8 | binary_str = decimal_to_binary(decimal_number) 9 | print(f"The binary representation of decimal {decimal_number} is {binary_str}") 10 | 11 | # Edge Cases and Limitations: 12 | # - Input: -10 (Negative numbers) 13 | # - Input: "10" (String input) 14 | 15 | # Optional Improvements: 16 | # - Add support for floating-point decimal numbers -------------------------------------------------------------------------------- /pysnippets/Numbers/decimal_to_hex.py: -------------------------------------------------------------------------------- 1 | def decimal_to_hex(decimal_number): 2 | if isinstance(decimal_number, int): 3 | return hex(decimal_number)[2:].upper() 4 | return "Invalid decimal number" 5 | 6 | # Example usage 7 | decimal_number = 26 8 | hex_str = decimal_to_hex(decimal_number) 9 | print(f"The hexadecimal representation of decimal {decimal_number} is {hex_str}") 10 | 11 | # Edge Cases and Limitations: 12 | # - Input: -26 (Negative numbers) 13 | # - Input: "26" (String input) 14 | 15 | # Optional Improvements: 16 | # - Add support for floating-point decimal numbers -------------------------------------------------------------------------------- /pysnippets/Numbers/format_to_2_decimal.py: -------------------------------------------------------------------------------- 1 | 2 | def format_to_2_decimal(num): 3 | """ 4 | Format a number to two decimal places. 5 | 6 | Args: 7 | num (float or int): The number to format. 8 | 9 | Returns: 10 | str: The number formatted to two decimal places as a string. 11 | """ 12 | return f"{num:.2f}" 13 | -------------------------------------------------------------------------------- /pysnippets/Numbers/hex_to_decimal.py: -------------------------------------------------------------------------------- 1 | def hex_to_decimal(hex_str): 2 | try: 3 | decimal_number = int(hex_str, 16) 4 | return decimal_number 5 | except ValueError: 6 | return "Invalid hexadecimal number" 7 | 8 | # Example usage 9 | hex_str = "1A" 10 | decimal_number = hex_to_decimal(hex_str) 11 | print(f"The decimal representation of hexadecimal {hex_str} is {decimal_number}") 12 | 13 | # Edge Cases and Limitations: 14 | # - Input: "G" (Invalid hexadecimal number) 15 | # - Input: "" (Empty string) 16 | 17 | # Optional Improvements: 18 | # - Add support for floating-point hexadecimal numbers -------------------------------------------------------------------------------- /pysnippets/Numbers/number_formatting.py: -------------------------------------------------------------------------------- 1 | # number_formatting.py 2 | 3 | 4 | def format_number(num: float, thousands_sep: str = ',', decimal_sep: str = '.') -> str: 5 | """ 6 | Format a number with commas as thousand separators. 7 | 8 | Args: 9 | num (int, float): The number to format. 10 | 11 | Returns: 12 | str: The formatted number as a string. 13 | """ 14 | if not isinstance(num, (int, float)): 15 | raise ValueError("The input should be an integer or a float.") 16 | 17 | formatted_num = f"{num:,}".replace(',', thousands_sep).replace('.', decimal_sep) 18 | return formatted_num 19 | 20 | 21 | # Example usage 22 | if __name__ == "__main__": 23 | print(format_number(1234567)) # Output: "1,234,567" 24 | print(format_number(12345.6789, thousands_sep=' ', decimal_sep=',')) #output: 12 345,6789 25 | print(format_number(-1234567.89)) 26 | print(format_number(1234567.89, ".", ',')) 27 | 28 | -------------------------------------------------------------------------------- /pysnippets/Numbers/octal_to_decimal.py: -------------------------------------------------------------------------------- 1 | def octal_to_decimal(octal_str): 2 | try: 3 | decimal_number = int(octal_str, 8) 4 | return decimal_number 5 | except ValueError: 6 | return "Invalid octal number" 7 | 8 | # Example usage 9 | octal_str = "32" 10 | decimal_number = octal_to_decimal(octal_str) 11 | print(f"The decimal representation of octal {octal_str} is {decimal_number}") 12 | 13 | # Edge Cases and Limitations: 14 | # - Input: "8" (Invalid octal number) 15 | # - Input: "" (Empty string) 16 | 17 | # Optional Improvements: 18 | # - Add support for floating-point octal numbers -------------------------------------------------------------------------------- /pysnippets/Numbers/pad_with_zeros.py: -------------------------------------------------------------------------------- 1 | 2 | def pad_with_zeros(num, width): 3 | """ 4 | Pad a number with leading zeros to a specified width. 5 | 6 | Args: 7 | num (int): The number to pad. 8 | width (int): The total width of the output string. 9 | 10 | Returns: 11 | str: The number padded with leading zeros. 12 | """ 13 | return str(num).zfill(width) 14 | -------------------------------------------------------------------------------- /pysnippets/Numbers/percentage_format.py: -------------------------------------------------------------------------------- 1 | 2 | def percentage_format(num, total, decimals=2): 3 | """ 4 | Format a number as a percentage of a total with specified decimal places. 5 | 6 | Args: 7 | num (float or int): The part value. 8 | total (float or int): The total value. 9 | decimals (int): Number of decimal places. 10 | 11 | Returns: 12 | str: The percentage formatted as a string. 13 | """ 14 | if total == 0: 15 | raise ValueError("Total must not be zero.") 16 | percentage = (num / total) * 100 17 | return f"{percentage:.{decimals}f}%" 18 | -------------------------------------------------------------------------------- /pysnippets/Numbers/prime_factorization.py: -------------------------------------------------------------------------------- 1 | def prime_factorization(n: int) -> list: 2 | """ 3 | Returns the prime factors of the given integer n. 4 | 5 | Args: 6 | n (int): The integer to factorize. Must be a positive integer. 7 | 8 | Returns: 9 | list: A list of prime factors of n. 10 | """ 11 | if not isinstance(n, int): 12 | raise TypeError("Input must be an integer.") 13 | if n <= 0: 14 | raise ValueError("Input must be a positive integer.") 15 | 16 | factors = [] 17 | divisor = 2 18 | while n > 1: 19 | while n % divisor == 0: 20 | factors.append(divisor) 21 | n //= divisor 22 | divisor += 1 23 | return factors 24 | 25 | 26 | if __name__ == "__main__": 27 | # Example usage 28 | result = prime_factorization(28) 29 | print(result) # Output: [2, 2, 7] 30 | -------------------------------------------------------------------------------- /pysnippets/PDF_Manipulation/__init__.py: -------------------------------------------------------------------------------- 1 | from .pdf_reader import read_pdf, read_pdf_metadata 2 | from .pdf_splitter import split_pdf, split_pdf_chunks 3 | from .pdf_merger import merge_pdfs, merge_pdfs_with_pages 4 | from .pdf_manipulator import rotate_pdf_pages, crop_pdf_pages 5 | from .pdf_security import encrypt_pdf, decrypt_pdf 6 | 7 | __all__ = [ 8 | 'read_pdf', 9 | 'read_pdf_metadata', 10 | 'split_pdf', 11 | 'split_pdf_chunks', 12 | 'merge_pdfs', 13 | 'merge_pdfs_with_pages', 14 | 'rotate_pdf_pages', 15 | 'crop_pdf_pages', 16 | 'encrypt_pdf', 17 | 'decrypt_pdf' 18 | ] 19 | 20 | -------------------------------------------------------------------------------- /pysnippets/Path_Algoithms/__init__.py: -------------------------------------------------------------------------------- 1 | from .dijkstra import dijkstra 2 | from .utils import create_graph 3 | from .gui import run_demo 4 | 5 | __all__ = ['dijkstra', 'create_graph', 'run_demo'] 6 | -------------------------------------------------------------------------------- /pysnippets/Path_Algoithms/data_classes.py: -------------------------------------------------------------------------------- 1 | from dataclasses import dataclass 2 | from typing import Dict, List 3 | 4 | @dataclass 5 | class Graph: 6 | vertices: List[str] 7 | edges: Dict[str, Dict[str, int]] -------------------------------------------------------------------------------- /pysnippets/Path_Algoithms/gui.py: -------------------------------------------------------------------------------- 1 | import tkinter as tk 2 | from dijkstra import dijkstra 3 | from utils import create_graph 4 | 5 | def run_demo(): 6 | vertices = ['A', 'B', 'C', 'D'] 7 | edges = { 8 | 'A': {'B': 1, 'C': 4}, 9 | 'B': {'C': 2, 'D': 5}, 10 | 'C': {'D': 1}, 11 | 'D': {} 12 | } 13 | graph = create_graph(vertices, edges) 14 | try: 15 | path, distance = dijkstra(graph, 'A', 'D') 16 | message = f"Path: {' -> '.join(path)}\nTotal distance: {distance}" 17 | except ValueError as ve: 18 | message = str(ve) 19 | except Exception: 20 | message = "An unexpected error occurred." 21 | 22 | root = tk.Tk() 23 | root.title("Dijkstra Demo") 24 | tk.Label(root, text=message).pack(pady=20) 25 | tk.Button(root, text="Exit", command=root.destroy).pack(pady=10) 26 | root.mainloop() 27 | 28 | if __name__ == "__main__": 29 | run_demo() -------------------------------------------------------------------------------- /pysnippets/Path_Algoithms/logger_config.py: -------------------------------------------------------------------------------- 1 | import logging 2 | 3 | def setup_logger(): 4 | logger = logging.getLogger('Path_Algorithms') 5 | logger.setLevel(logging.DEBUG) 6 | handler = logging.StreamHandler() 7 | formatter = logging.Formatter('%(asctime)s %(levelname)s %(message)s') 8 | handler.setFormatter(formatter) 9 | logger.addHandler(handler) 10 | return logger 11 | 12 | logger = setup_logger() -------------------------------------------------------------------------------- /pysnippets/Path_Algoithms/test_all.py: -------------------------------------------------------------------------------- 1 | import unittest 2 | 3 | from test_dijkstra import TestDijkstra 4 | 5 | def load_tests(loader, tests, pattern): 6 | tests.addTests(loader.loadTestsFromTestCase(TestDijkstra)) 7 | return tests 8 | 9 | if __name__ == '__main__': 10 | unittest.main() -------------------------------------------------------------------------------- /pysnippets/Path_Algoithms/test_dijkstra.py: -------------------------------------------------------------------------------- 1 | import unittest 2 | from utils import create_graph 3 | from dijkstra import dijkstra 4 | 5 | class TestDijkstra(unittest.TestCase): 6 | def setUp(self): 7 | vertices = ['A', 'B', 'C', 'D'] 8 | edges = { 9 | 'A': {'B': 1, 'C': 4}, 10 | 'B': {'C': 2, 'D': 5}, 11 | 'C': {'D': 1}, 12 | 'D': {} 13 | } 14 | self.graph = create_graph(vertices, edges) 15 | 16 | def test_shortest_path(self): 17 | path, distance = dijkstra(self.graph, 'A', 'D') 18 | self.assertEqual(path, ['A', 'B', 'C', 'D']) 19 | self.assertEqual(distance, 4) 20 | 21 | def test_no_path(self): 22 | graph = create_graph(['A', 'B'], {'A': {}, 'B': {}}) 23 | with self.assertRaises(ValueError): 24 | dijkstra(graph, 'A', 'B') 25 | 26 | def test_same_start_end(self): 27 | path, distance = dijkstra(self.graph, 'A', 'A') 28 | self.assertEqual(path, ['A']) 29 | self.assertEqual(distance, 0) 30 | 31 | if __name__ == '__main__': 32 | unittest.main() -------------------------------------------------------------------------------- /pysnippets/Path_Algoithms/utils.py: -------------------------------------------------------------------------------- 1 | from data_classes import Graph 2 | from logger_config import logger 3 | from typing import List, Dict 4 | 5 | def create_graph(vertices: List[str], edges: Dict[str, Dict[str, int]]) -> Graph: 6 | try: 7 | graph = Graph(vertices=vertices, edges=edges) 8 | logger.debug("Graph created successfully") 9 | return graph 10 | except Exception as e: 11 | logger.error(f"Error creating graph: {e}") 12 | raise -------------------------------------------------------------------------------- /pysnippets/Performance/__init__.py: -------------------------------------------------------------------------------- 1 | from .memoize import memoize 2 | from .timer import timer 3 | -------------------------------------------------------------------------------- /pysnippets/Performance/timer.py: -------------------------------------------------------------------------------- 1 | import time 2 | from contextlib import ( 3 | contextmanager, 4 | ) # helps in defining a block of setup and teardown logic 5 | 6 | 7 | @contextmanager 8 | def timer(description="Execution"): 9 | """ 10 | A context manager that measures the execution time of a code block. 11 | 12 | Args: 13 | description (str, optional): A description of the operation being timed. Defaults to 'Execution'. 14 | 15 | Yields: 16 | None 17 | 18 | Example: 19 | with timer('Database query'): 20 | # some time-consuming operation 21 | time.sleep(2) 22 | 23 | This will print: 24 | Database query took 2.00 seconds 25 | """ 26 | start = time.time() 27 | yield 28 | elapsed = time.time() - start 29 | print(f"{description} took {elapsed:.2f} seconds") 30 | 31 | 32 | # example usage 33 | if __name__ == "__main__": 34 | with timer("Sample operation"): 35 | # simulate some time-consuming operation 36 | time.sleep(2) 37 | -------------------------------------------------------------------------------- /pysnippets/Recursion/__init__.py: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/UTSAVS26/PySnippets/7d663efc569f46c1550a16fbba42fa8e6e815b7e/pysnippets/Recursion/__init__.py -------------------------------------------------------------------------------- /pysnippets/Recursion/binary_search.py: -------------------------------------------------------------------------------- 1 | import logging 2 | from dataclasses import dataclass 3 | 4 | logging.basicConfig(level=logging.INFO) 5 | 6 | @dataclass 7 | class BinarySearch: 8 | array: list 9 | target: int 10 | 11 | def search(self) -> int: 12 | return self._binary_search_recursive(self.array, self.target, 0, len(self.array) - 1) 13 | 14 | def _binary_search_recursive(self, array, target, left, right): 15 | if right >= left: 16 | mid = left + (right - left) // 2 17 | if array[mid] == target: 18 | logging.info(f"Target {target} found at index {mid}") 19 | return mid 20 | elif array[mid] > target: 21 | return self._binary_search_recursive(array, target, left, mid - 1) 22 | else: 23 | return self._binary_search_recursive(array, target, mid + 1, right) 24 | else: 25 | logging.info(f"Target {target} not found") 26 | return -1 27 | 28 | # Sample usage 29 | if __name__ == "__main__": 30 | bs_instance = BinarySearch([1, 2, 3, 4, 5], 3) 31 | print(f"Index of 3 is {bs_instance.search()}") # Output: 2 -------------------------------------------------------------------------------- /pysnippets/Recursion/factorial.py: -------------------------------------------------------------------------------- 1 | import logging 2 | from dataclasses import dataclass 3 | 4 | logging.basicConfig(level=logging.INFO) 5 | 6 | @dataclass 7 | class Factorial: 8 | n: int 9 | 10 | def calculate(self) -> int: 11 | if self.n < 0: 12 | raise ValueError("Input must be a non-negative integer") 13 | return self._factorial_recursive(self.n) 14 | 15 | def _factorial_recursive(self, current: int) -> int: 16 | if current == 0: 17 | return 1 18 | else: 19 | result = current * self._factorial_recursive(current - 1) 20 | logging.info(f"Factorial({current}) = {result}") 21 | return result 22 | 23 | # Sample usage 24 | if __name__ == "__main__": 25 | factorial_instance = Factorial(5) 26 | print(f"Factorial of 5 is {factorial_instance.calculate()}") # Output: 120 -------------------------------------------------------------------------------- /pysnippets/Recursion/fibonacci.py: -------------------------------------------------------------------------------- 1 | import logging 2 | from dataclasses import dataclass 3 | 4 | logging.basicConfig(level=logging.INFO) 5 | 6 | @dataclass 7 | class Fibonacci: 8 | n: int 9 | 10 | def calculate(self) -> int: 11 | if self.n < 0: 12 | raise ValueError("Input must be a non-negative integer") 13 | return self._fibonacci_recursive(self.n) 14 | 15 | def _fibonacci_recursive(self, current: int) -> int: 16 | if current in (0, 1): 17 | return current 18 | result = self._fibonacci_recursive(current - 1) + self._fibonacci_recursive(current - 2) 19 | logging.info(f"Fibonacci({current}) = {result}") 20 | return result 21 | 22 | # Sample usage 23 | if __name__ == "__main__": 24 | fib_instance = Fibonacci(10) 25 | print(f"Fibonacci of 10 is {fib_instance.calculate()}") # Output: 55 -------------------------------------------------------------------------------- /pysnippets/Recursion/merge_sort.py: -------------------------------------------------------------------------------- 1 | import logging 2 | from dataclasses import dataclass 3 | 4 | logging.basicConfig(level=logging.INFO) 5 | 6 | @dataclass 7 | class MergeSort: 8 | array: list 9 | 10 | def sort(self) -> list: 11 | if len(self.array) > 1: 12 | mid = len(self.array) // 2 13 | left_half = self.array[:mid] 14 | right_half = self.array[mid:] 15 | 16 | left_sort = MergeSort(left_half).sort() 17 | right_sort = MergeSort(right_half).sort() 18 | 19 | return self._merge(left_sort, right_sort) 20 | else: 21 | return self.array 22 | 23 | def _merge(self, left, right): 24 | sorted_array = [] 25 | while left and right: 26 | if left[0] < right[0]: 27 | sorted_array.append(left.pop(0)) 28 | else: 29 | sorted_array.append(right.pop(0)) 30 | sorted_array.extend(left or right) 31 | return sorted_array 32 | 33 | # Sample usage 34 | if __name__ == "__main__": 35 | ms_instance = MergeSort([34, 7, 23, 32, 5, 62]) 36 | print(f"Sorted array: {ms_instance.sort()}") # Output: [5, 7, 23, 32, 34, 62] -------------------------------------------------------------------------------- /pysnippets/Recursion/permutations.py: -------------------------------------------------------------------------------- 1 | import logging 2 | from dataclasses import dataclass 3 | 4 | logging.basicConfig(level=logging.INFO) 5 | 6 | @dataclass 7 | class Permutations: 8 | string: str 9 | 10 | def generate(self): 11 | return self._permute(self.string) 12 | 13 | def _permute(self, s, answer=''): 14 | if len(s) == 0: 15 | logging.info(f"Permutation: {answer}") 16 | return [answer] 17 | results = [] 18 | for i in range(len(s)): 19 | char = s[i] 20 | left_substr = s[0:i] 21 | right_substr = s[i + 1:] 22 | results += self._permute(left_substr + right_substr, answer + char) 23 | return results 24 | 25 | # Sample usage 26 | if __name__ == "__main__": 27 | perm = Permutations("abc") 28 | print(perm.generate()) # Output: All permutations of 'abc' -------------------------------------------------------------------------------- /pysnippets/Recursion/quick_sort.py: -------------------------------------------------------------------------------- 1 | import logging 2 | from dataclasses import dataclass 3 | 4 | logging.basicConfig(level=logging.INFO) 5 | 6 | @dataclass 7 | class QuickSort: 8 | array: list 9 | 10 | def sort(self) -> list: 11 | return self._quick_sort_recursive(self.array, 0, len(self.array) - 1) 12 | 13 | def _quick_sort_recursive(self, array, low, high): 14 | if low < high: 15 | pi = self._partition(array, low, high) 16 | self._quick_sort_recursive(array, low, pi - 1) 17 | self._quick_sort_recursive(array, pi + 1, high) 18 | return array 19 | 20 | def _partition(self, array, low, high): 21 | pivot = array[high] 22 | i = low - 1 23 | for j in range(low, high): 24 | if array[j] <= pivot: 25 | i += 1 26 | array[i], array[j] = array[j], array[i] 27 | array[i + 1], array[high] = array[high], array[i + 1] 28 | return i + 1 29 | 30 | # Sample usage 31 | if __name__ == "__main__": 32 | qs_instance = QuickSort([10, 80, 30, 90, 40, 50, 70]) 33 | print(f"Sorted array: {qs_instance.sort()}") # Output: [10, 30, 40, 50, 70, 80, 90] -------------------------------------------------------------------------------- /pysnippets/Recursion/subsets.py: -------------------------------------------------------------------------------- 1 | import logging 2 | from dataclasses import dataclass 3 | 4 | logging.basicConfig(level=logging.INFO) 5 | 6 | @dataclass 7 | class Subsets: 8 | set: list 9 | 10 | def generate(self): 11 | return self._subsets_recursive([], sorted(self.set)) 12 | 13 | def _subsets_recursive(self, current, set): 14 | if not set: 15 | logging.info(f"Subset: {current}") 16 | return [current] 17 | return self._subsets_recursive(current + [set[0]], set[1:]) + self._subsets_recursive(current, set[1:]) 18 | 19 | # Sample usage 20 | if __name__ == "__main__": 21 | subset_gen = Subsets([1, 2, 3]) 22 | print(subset_gen.generate()) # Output: All subsets of [1, 2, 3] -------------------------------------------------------------------------------- /pysnippets/Recursion/tower_of_hanoi.py: -------------------------------------------------------------------------------- 1 | import logging 2 | from dataclasses import dataclass 3 | 4 | logging.basicConfig(level=logging.INFO) 5 | 6 | @dataclass 7 | class TowerOfHanoi: 8 | num_disks: int 9 | 10 | def solve(self, from_rod, to_rod, aux_rod): 11 | if self.num_disks <= 0: 12 | raise ValueError("Number of disks must be greater than zero") 13 | if self.num_disks == 1: 14 | logging.info(f"Move disk 1 from rod {from_rod} to rod {to_rod}") 15 | return [(from_rod, to_rod)] 16 | moves = [] 17 | moves += self.solve(from_rod, aux_rod, to_rod) 18 | moves.append((from_rod, to_rod)) 19 | logging.info(f"Move disk {self.num_disks} from rod {from_rod} to rod {to_rod}") 20 | moves += self.solve(aux_rod, to_rod, from_rod) 21 | return moves 22 | 23 | # Sample usage 24 | if __name__ == "__main__": 25 | hanoi = TowerOfHanoi(3) 26 | print(hanoi.solve('A', 'C', 'B')) # Output: Moves from rod A to C using B as auxiliary -------------------------------------------------------------------------------- /pysnippets/Scrubs/__init__.py: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/UTSAVS26/PySnippets/7d663efc569f46c1550a16fbba42fa8e6e815b7e/pysnippets/Scrubs/__init__.py -------------------------------------------------------------------------------- /pysnippets/Scrubs/backup.py: -------------------------------------------------------------------------------- 1 | import pandas as pd 2 | 3 | from compress import compress_numeric 4 | from utils import time_my_func 5 | 6 | @time_my_func 7 | def backup_df(df, path_clean): 8 | """ 9 | Writes a dataframe to disk after 10 | cleaning dates 11 | imputing categoricals 12 | compressing numerics 13 | """ 14 | print("Fixing dates...") 15 | date_cols = df.columns.map(lambda i: i if 'date' in i else None).dropna().tolist() 16 | if len(date_cols) >= 1: 17 | for COL in date_cols: 18 | df.loc[:, COL] = pd.to_datetime(df[COL]) 19 | 20 | print("Fixing categoricals...") 21 | # categoricals 22 | catg_cols = df.select_dtypes(include=object).columns.tolist() 23 | if len(catg_cols) >= 1: 24 | for COL in catg_cols: 25 | df.loc[:, COL] = df[COL].fillna('_missing_') 26 | 27 | print("Fixing numerics...") 28 | df = df.apply(compress_numeric) 29 | 30 | print("Saving cleaned file to {}".format(path_clean)) 31 | df.to_csv(path_clean) 32 | return None -------------------------------------------------------------------------------- /pysnippets/Scrubs/utils.py: -------------------------------------------------------------------------------- 1 | import time 2 | 3 | def time_my_func(my_func): 4 | def timed(*args, **kwargs): 5 | """ 6 | Decorates a function to print its execution time. 7 | """ 8 | message_top = "\nStarting {}".format(my_func.__name__) 9 | print(message_top) 10 | print("-" * len(message_top)) 11 | t0 = time.time() 12 | 13 | result = my_func(*args, **kwargs) 14 | 15 | message_bot = "\nCompleted in {:.2f} minutes.".format((time.time() - t0)/60) 16 | print(message_bot) 17 | print('-' * len(message_bot)) 18 | return result 19 | return timed -------------------------------------------------------------------------------- /pysnippets/Searching/__init__.py: -------------------------------------------------------------------------------- 1 | import logging 2 | from .Exponential_search import exponential_search 3 | from .Fibonacci_search import fibonacci_search 4 | from .Interpolation import interpolation_search 5 | from .iterative_binary_search import binary_search_iterative 6 | from .Jump_search import jump_search 7 | from .Linear_Search import linear_search 8 | from .recursive_binary_search import binary_search_recursive 9 | from .Ternary_search import ternary_search 10 | 11 | __all__ = [ 12 | "exponential_search", 13 | "fibonacci_search", 14 | "interpolation_search", 15 | "binary_search_iterative", 16 | "jump_search", 17 | "linear_search", 18 | "binary_search_recursive", 19 | "ternary_search", 20 | ] 21 | -------------------------------------------------------------------------------- /pysnippets/Sorting/__init__.py: -------------------------------------------------------------------------------- 1 | from .bubble_sort import bubble_sort 2 | from .insertion_sort import insertion_sort 3 | from .merge_sort import merge_sort 4 | from .quick_sort import quick_sort 5 | from .cocktail_sort import cocktail_sort 6 | from .sort_dict_list import sort_dict_list 7 | from .heap_sort import heap_sort 8 | from .counting_sort import counting_sort 9 | 10 | __all__ = [ 11 | "bubble_sort", 12 | "insertion_sort", 13 | "merge_sort", 14 | "quick_sort", 15 | "cocktail_sort", 16 | "sort_dict_list", 17 | "heap_sort", 18 | "counting_sort", 19 | ] 20 | -------------------------------------------------------------------------------- /pysnippets/Sorting/selection_sort.py: -------------------------------------------------------------------------------- 1 | def selection_sort(arr): 2 | n = len(arr) 3 | for i in range(n): 4 | min_idx = i 5 | for j in range(i + 1, n): 6 | if arr[j] < arr[min_idx]: 7 | min_idx = j 8 | arr[i], arr[min_idx] = arr[min_idx], arr[i] 9 | return arr 10 | 11 | if __name__ == "__main__": 12 | # Input: space-separated integers 13 | input_data = input("Enter numbers to sort, separated by spaces: ") 14 | arr = list(map(int, input_data.split())) 15 | 16 | sorted_arr = selection_sort(arr) 17 | print("Sorted array:", sorted_arr) 18 | -------------------------------------------------------------------------------- /pysnippets/SpecialNumbers/__init__.py: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/UTSAVS26/PySnippets/7d663efc569f46c1550a16fbba42fa8e6e815b7e/pysnippets/SpecialNumbers/__init__.py -------------------------------------------------------------------------------- /pysnippets/SpecialNumbers/logging_config.py: -------------------------------------------------------------------------------- 1 | import logging 2 | 3 | logging.basicConfig( 4 | level=logging.INFO, 5 | format="%(asctime)s - %(levelname)s - %(message)s" 6 | ) -------------------------------------------------------------------------------- /pysnippets/Strings/__init__.py: -------------------------------------------------------------------------------- 1 | # __init__.py 2 | 3 | # This file allows the snippets folder to be treated as a package. 4 | # It can be empty or used to expose certain functions for easy imports. 5 | -------------------------------------------------------------------------------- /pysnippets/Strings/anagram_detector.py: -------------------------------------------------------------------------------- 1 | def are_anagrams(s1: str, s2: str) -> bool: 2 | if not isinstance(s1, str) or not isinstance(s2, str): 3 | raise ValueError("Both inputs must be strings.") 4 | return sorted(s1.replace(" ", "").lower()) == sorted(s2.replace(" ", "").lower()) 5 | 6 | if __name__ == "__main__": 7 | string1 = "Listen" 8 | string2 = "Silent" 9 | result = are_anagrams(string1, string2) 10 | print(f"Are '{string1}' and '{string2}' anagrams? {result}") 11 | # Output: Are 'Listen' and 'Silent' anagrams? True -------------------------------------------------------------------------------- /pysnippets/Strings/basic_conversion.py: -------------------------------------------------------------------------------- 1 | def number_to_words_basic(num_str: str) -> str: 2 | if not isinstance(num_str, str) or not num_str.isdigit(): 3 | raise ValueError("Input must be a string of digits.") 4 | num_map = { 5 | '0': 'zero', '1': 'one', '2': 'two', '3': 'three', '4': 'four', 6 | '5': 'five', '6': 'six', '7': 'seven', '8': 'eight', '9': 'nine' 7 | } 8 | return ' '.join(num_map.get(digit, digit) for digit in num_str) 9 | 10 | def words_to_number_basic(words_str: str) -> str: 11 | if not isinstance(words_str, str): 12 | raise ValueError("Input must be a string.") 13 | word_map = { 14 | 'zero': '0', 'one': '1', 'two': '2', 'three': '3', 'four': '4', 15 | 'five': '5', 'six': '6', 'seven': '7', 'eight': '8', 'nine': '9' 16 | } 17 | return ''.join(word_map.get(word, word) for word in words_str.split()) 18 | -------------------------------------------------------------------------------- /pysnippets/Strings/levenshtein_distance.py: -------------------------------------------------------------------------------- 1 | def levenshtein_distance(s1: str, s2: str) -> int: 2 | if not isinstance(s1, str) or not isinstance(s2, str): 3 | raise ValueError("Both inputs must be strings.") 4 | if len(s1) < len(s2): 5 | return levenshtein_distance(s2, s1) 6 | 7 | previous_row = list(range(len(s2) + 1)) 8 | for i, c1 in enumerate(s1, 1): 9 | current_row = [i] 10 | for j, c2 in enumerate(s2, 1): 11 | insertions = previous_row[j] + 1 12 | deletions = current_row[j - 1] + 1 13 | substitutions = previous_row[j - 1] + (c1 != c2) 14 | current_row.append(min(insertions, deletions, substitutions)) 15 | previous_row = current_row 16 | return previous_row[-1] 17 | 18 | if __name__ == "__main__": 19 | string1 = "kitten" 20 | string2 = "sitting" 21 | distance = levenshtein_distance(string1, string2) 22 | print(f"Levenshtein distance between '{string1}' and '{string2}': {distance}") 23 | # Output: Levenshtein distance between 'kitten' and 'sitting': 3 -------------------------------------------------------------------------------- /pysnippets/Strings/list_to_comma_string.py: -------------------------------------------------------------------------------- 1 | # list_to_comma_string.py 2 | 3 | from typing import List 4 | 5 | def list_to_comma_string(items: List[str]) -> str: 6 | """ 7 | Convert a list of strings into a comma-separated string. 8 | 9 | Args: 10 | items (list of str): List of strings to convert. 11 | 12 | Returns: 13 | str: A single comma-separated string. 14 | 15 | Raises: 16 | ValueError: If any element in the list is not a string. 17 | 18 | Example: 19 | >>> list_to_comma_string(['apple', 'banana', 'cherry']) 20 | 'apple, banana, cherry' 21 | """ 22 | if not all(isinstance(item, str) for item in items): 23 | invalid_items = [item for item in items if not isinstance(item, str)] 24 | raise ValueError(f"All elements of the list must be strings. Invalid items: {invalid_items}") 25 | 26 | return ", ".join(items) 27 | 28 | 29 | # Example usage 30 | if __name__ == "__main__": 31 | my_list = ["apple", "banana", "cherry"] 32 | result = list_to_comma_string(my_list) 33 | print(result) 34 | -------------------------------------------------------------------------------- /pysnippets/Strings/regex.py: -------------------------------------------------------------------------------- 1 | import re 2 | 3 | def number_to_words_regex(text: str) -> str: 4 | if not isinstance(text, str): 5 | raise ValueError("Input must be a string.") 6 | num_map = { 7 | '0': 'zero', '1': 'one', '2': 'two', '3': 'three', '4': 'four', 8 | '5': 'five', '6': 'six', '7': 'seven', '8': 'eight', '9': 'nine' 9 | } 10 | return re.sub(r'\d', lambda x: num_map[x.group()], text) 11 | 12 | def words_to_number_regex(text: str) -> str: 13 | if not isinstance(text, str): 14 | raise ValueError("Input must be a string.") 15 | word_map = { 16 | 'zero': '0', 'one': '1', 'two': '2', 'three': '3', 'four': '4', 17 | 'five': '5', 'six': '6', 'seven': '7', 'eight': '8', 'nine': '9' 18 | } 19 | return re.sub(r'\b(' + '|'.join(word_map.keys()) + r')\b', 20 | lambda x: word_map[x.group()], text) 21 | -------------------------------------------------------------------------------- /pysnippets/Strings/snake_to_camel.py: -------------------------------------------------------------------------------- 1 | def snake_to_camel(snake_str: str) -> str: 2 | if not isinstance(snake_str, str): 3 | raise ValueError("Input must be a string.") 4 | components = snake_str.split('_') 5 | return components[0] + ''.join(x.title() for x in components[1:]) 6 | 7 | if __name__ == "__main__": 8 | snake = "convert_snake_case_to_camelCase" 9 | camel = snake_to_camel(snake) 10 | print(camel) 11 | # Output: convertSnakeCaseToCamelCase -------------------------------------------------------------------------------- /pysnippets/Strings/string_normalizer.py: -------------------------------------------------------------------------------- 1 | import unicodedata 2 | 3 | def normalize_string(s: str) -> str: 4 | if not isinstance(s, str): 5 | raise ValueError("Input must be a string.") 6 | normalized = unicodedata.normalize('NFKD', s) 7 | return ''.join(c for c in normalized if not unicodedata.combining(c)) 8 | 9 | if __name__ == "__main__": 10 | original = "Café Münchner Kindl" 11 | normalized = normalize_string(original) 12 | print(normalized) 13 | # Output: Cafe Munchner Kindl -------------------------------------------------------------------------------- /pysnippets/Strings/template_engine.py: -------------------------------------------------------------------------------- 1 | import re 2 | from typing import Dict 3 | 4 | def substitute_template(template: str, substitutions: Dict[str, str]) -> str: 5 | pattern = re.compile(r'{(\w+)}') 6 | return pattern.sub(lambda match: substitutions.get(match.group(1), match.group(0)), template) 7 | 8 | if __name__ == "__main__": 9 | template = "Hello, {name}! Welcome to {place}." 10 | substitutions = {"name": "Alice", "place": "Wonderland"} 11 | result = substitute_template(template, substitutions) 12 | print(result) 13 | # Output: Hello, Alice! Welcome to Wonderland. -------------------------------------------------------------------------------- /pysnippets/Strings/test_anagram_detector.py: -------------------------------------------------------------------------------- 1 | import unittest 2 | from anagram_detector import are_anagrams 3 | 4 | class TestAnagramDetector(unittest.TestCase): 5 | def test_anagrams(self): 6 | self.assertTrue(are_anagrams("Listen", "Silent")) 7 | 8 | def test_not_anagrams(self): 9 | self.assertFalse(are_anagrams("Hello", "World")) 10 | 11 | def test_different_lengths(self): 12 | self.assertFalse(are_anagrams("test", "testing")) 13 | 14 | def test_with_spaces(self): 15 | self.assertTrue(are_anagrams("conversation", "voices rant on")) 16 | 17 | def test_case_insensitivity(self): 18 | self.assertTrue(are_anagrams("Dormitory", "Dirty room")) 19 | 20 | def test_special_characters(self): 21 | self.assertTrue(are_anagrams("A gentleman", "Elegant man")) 22 | self.assertFalse(are_anagrams("Clint Eastwood", "Old West Action!")) 23 | 24 | if __name__ == "__main__": 25 | unittest.main() -------------------------------------------------------------------------------- /pysnippets/Strings/test_levenshtein_distance.py: -------------------------------------------------------------------------------- 1 | import unittest 2 | from levenshtein_distance import levenshtein_distance 3 | 4 | class TestLevenshteinDistance(unittest.TestCase): 5 | def test_identical_strings(self): 6 | self.assertEqual(levenshtein_distance("test", "test"), 0) 7 | 8 | def test_empty_strings(self): 9 | self.assertEqual(levenshtein_distance("", ""), 0) 10 | self.assertEqual(levenshtein_distance("a", ""), 1) 11 | self.assertEqual(levenshtein_distance("", "a"), 1) 12 | 13 | def test_different_lengths(self): 14 | self.assertEqual(levenshtein_distance("short", "longer"), 3) 15 | 16 | def test_case_sensitivity(self): 17 | self.assertEqual(levenshtein_distance("Kitten", "kitten"), 1) 18 | 19 | def test_non_alphabetic_characters(self): 20 | self.assertEqual(levenshtein_distance("hello!", "hello"), 1) 21 | 22 | if __name__ == "__main__": 23 | unittest.main() -------------------------------------------------------------------------------- /pysnippets/Strings/test_snake_to_camel.py: -------------------------------------------------------------------------------- 1 | import unittest 2 | from snake_to_camel import snake_to_camel 3 | 4 | class TestSnakeToCamel(unittest.TestCase): 5 | def test_standard_case(self): 6 | self.assertEqual(snake_to_camel("snake_case"), "snakeCase") 7 | 8 | def test_multiple_words(self): 9 | self.assertEqual(snake_to_camel("convert_snake_case_to_camel"), "convertSnakeCaseToCamel") 10 | 11 | def test_no_underscore(self): 12 | self.assertEqual(snake_to_camel("snakecase"), "snakecase") 13 | 14 | def test_leading_trailing_underscores(self): 15 | self.assertEqual(snake_to_camel("_snake_case_"), "snakeCase") 16 | 17 | def test_multiple_consecutive_underscores(self): 18 | self.assertEqual(snake_to_camel("snake__case"), "snakeCase") 19 | 20 | if __name__ == "__main__": 21 | unittest.main() -------------------------------------------------------------------------------- /pysnippets/Strings/test_string_normalizer.py: -------------------------------------------------------------------------------- 1 | import unittest 2 | from string_normalizer import normalize_string 3 | 4 | class TestStringNormalizer(unittest.TestCase): 5 | def test_with_accents(self): 6 | self.assertEqual(normalize_string("Café"), "Cafe") 7 | 8 | def test_no_accents(self): 9 | self.assertEqual(normalize_string("Cafe"), "Cafe") 10 | 11 | def test_empty_string(self): 12 | self.assertEqual(normalize_string(""), "") 13 | 14 | def test_only_accents(self): 15 | self.assertEqual(normalize_string("àéîõü"), "aeiou") 16 | 17 | def test_mixed_characters(self): 18 | self.assertEqual(normalize_string("München"), "Munchen") 19 | 20 | if __name__ == "__main__": 21 | unittest.main() -------------------------------------------------------------------------------- /pysnippets/Traversal/__init__.py: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/UTSAVS26/PySnippets/7d663efc569f46c1550a16fbba42fa8e6e815b7e/pysnippets/Traversal/__init__.py -------------------------------------------------------------------------------- /pysnippets/Traversal/parallel_bfs.py: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /pysnippets/Tries/__init__.py: -------------------------------------------------------------------------------- 1 | # __init__.py 2 | 3 | # This file allows the snippets folder to be treated as a package. 4 | # It can be empty or used to expose certain functions for easy imports. 5 | -------------------------------------------------------------------------------- /pysnippets/Visualization/Annonated_Heatmap.py: -------------------------------------------------------------------------------- 1 | import seaborn as sns 2 | import numpy as np 3 | import matplotlib.pyplot as plt 4 | 5 | def advanced_heatmap(data, cmap='coolwarm', annot=True, fmt=".2f", figsize=(10, 8), title="Heatmap"): 6 | plt.figure(figsize=figsize) 7 | sns.heatmap(data, cmap=cmap, annot=annot, fmt=fmt, linewidths=.5) 8 | plt.title(title) 9 | plt.show() 10 | 11 | # Test case 12 | data = np.random.rand(10, 12) 13 | advanced_heatmap(data) 14 | -------------------------------------------------------------------------------- /pysnippets/Visualization/Boxplot_with_notches.py: -------------------------------------------------------------------------------- 1 | import seaborn as sns 2 | import matplotlib.pyplot as plt 3 | 4 | def notched_boxplot(data, x_col, y_col, palette='muted', notch=True, title="Notched Box Plot"): 5 | plt.figure(figsize=(10, 6)) 6 | sns.boxplot(data=data, x=x_col, y=y_col, palette=palette, notch=notch) 7 | plt.title(title) 8 | plt.show() 9 | 10 | # Test case 11 | data = sns.load_dataset("tips") 12 | notched_boxplot(data, x_col='day', y_col='total_bill') 13 | 14 | 15 | -------------------------------------------------------------------------------- /pysnippets/Visualization/Circular_bar.py: -------------------------------------------------------------------------------- 1 | import matplotlib.pyplot as plt 2 | import numpy as np 3 | 4 | def circular_bar_plot(labels, values, title="Circular Bar Plot", color="skyblue"): 5 | N = len(labels) 6 | theta = np.linspace(0, 2 * np.pi, N, endpoint=False) 7 | values = np.concatenate((values,[values[0]])) # Closing the circle 8 | theta = np.concatenate((theta,[theta[0]])) 9 | 10 | plt.figure(figsize=(8, 8)) 11 | ax = plt.subplot(111, polar=True) 12 | ax.fill(theta, values, color=color, alpha=0.3) 13 | ax.plot(theta, values, color=color) 14 | plt.title(title) 15 | plt.show() 16 | 17 | # Test case 18 | labels = ['A', 'B', 'C', 'D', 'E'] 19 | values = [4, 6, 5, 7, 3] 20 | circular_bar_plot(labels, values) 21 | -------------------------------------------------------------------------------- /pysnippets/Visualization/Density_Shade.py: -------------------------------------------------------------------------------- 1 | import seaborn as sns 2 | import matplotlib.pyplot as plt 3 | 4 | def density_plot(data, col, title="Density Plot with Shade"): 5 | plt.figure(figsize=(10, 6)) 6 | sns.kdeplot(data=data, x=col, shade=True) 7 | plt.title(title) 8 | plt.show() 9 | 10 | # Test case 11 | data = sns.load_dataset("iris") 12 | density_plot(data, col="sepal_length") 13 | -------------------------------------------------------------------------------- /pysnippets/Visualization/Dual_axis_line.py: -------------------------------------------------------------------------------- 1 | import matplotlib.pyplot as plt 2 | import numpy as np 3 | 4 | def dual_axis_line_plot(x, y1, y2, color1='blue', color2='green', title="Dual Axis Line Plot"): 5 | fig, ax1 = plt.subplots(figsize=(10, 6)) 6 | ax2 = ax1.twinx() # instantiate a second y-axis 7 | 8 | ax1.plot(x, y1, color=color1, linewidth=2, label='y1') 9 | ax2.plot(x, y2, color=color2, linewidth=2, linestyle='--', label='y2') 10 | 11 | ax1.set_xlabel("X Axis") 12 | ax1.set_ylabel("Y1 Axis", color=color1) 13 | ax2.set_ylabel("Y2 Axis", color=color2) 14 | plt.title(title) 15 | plt.show() 16 | 17 | # Test case 18 | x = np.linspace(0, 10, 100) 19 | y1 = np.sin(x) 20 | y2 = np.cos(x) 21 | dual_axis_line_plot(x, y1, y2) 22 | -------------------------------------------------------------------------------- /pysnippets/Visualization/Filled_area.py: -------------------------------------------------------------------------------- 1 | import matplotlib.pyplot as plt 2 | import numpy as np 3 | 4 | def filled_area_plot(x, y, title="Filled Area Plot", color="skyblue", alpha=0.3): 5 | plt.figure(figsize=(10, 6)) 6 | plt.fill_between(x, y, color=color, alpha=alpha) 7 | plt.plot(x, y, color="blue") 8 | plt.title(title) 9 | plt.show() 10 | 11 | # Test case 12 | x = np.linspace(0, 10, 100) 13 | y = np.sin(x) 14 | filled_area_plot(x, y) 15 | -------------------------------------------------------------------------------- /pysnippets/Visualization/Heatmap_cluster.py: -------------------------------------------------------------------------------- 1 | import seaborn as sns 2 | import matplotlib.pyplot as plt 3 | import numpy as np 4 | 5 | def clustered_heatmap(data, cmap="coolwarm", title="Clustered Heatmap"): 6 | sns.clustermap(data, cmap=cmap, figsize=(10, 8)) 7 | plt.title(title) 8 | plt.show() 9 | 10 | # Test case 11 | data = np.random.rand(10, 10) 12 | clustered_heatmap(data) 13 | -------------------------------------------------------------------------------- /pysnippets/Visualization/Scatter_regression.py: -------------------------------------------------------------------------------- 1 | import seaborn as sns 2 | import matplotlib.pyplot as plt 3 | 4 | def scatter_with_regression(data, x, y, title="Scatter Plot with Regression Line"): 5 | plt.figure(figsize=(10, 6)) 6 | sns.regplot(data=data, x=x, y=y, scatter_kws={"s": 50, "color": "blue"}, line_kws={"color": "red"}) 7 | plt.title(title) 8 | plt.show() 9 | 10 | # Test case 11 | data = sns.load_dataset("tips") 12 | scatter_with_regression(data, x="total_bill", y="tip") 13 | -------------------------------------------------------------------------------- /pysnippets/Visualization/Stacked_Bar_Chart.py: -------------------------------------------------------------------------------- 1 | import matplotlib.pyplot as plt 2 | 3 | def stacked_bar_chart(categories, values1, values2, title="Stacked Bar Chart", colors=("skyblue", "lightgreen")): 4 | plt.figure(figsize=(10, 6)) 5 | bar_width = 0.5 6 | plt.bar(categories, values1, color=colors[0], label="Value 1", width=bar_width) 7 | plt.bar(categories, values2, bottom=values1, color=colors[1], label="Value 2", width=bar_width) 8 | plt.legend() 9 | plt.title(title) 10 | plt.show() 11 | 12 | # Test case 13 | categories = ['A', 'B', 'C', 'D'] 14 | values1 = [3, 6, 9, 12] 15 | values2 = [5, 4, 2, 8] 16 | stacked_bar_chart(categories, values1, values2) 17 | -------------------------------------------------------------------------------- /pysnippets/Visualization/ThreeD_surface.py: -------------------------------------------------------------------------------- 1 | import matplotlib.pyplot as plt 2 | import numpy as np 3 | 4 | def surface_plot(x, y, z_func, title="3D Surface Plot"): 5 | X, Y = np.meshgrid(x, y) 6 | Z = z_func(X, Y) 7 | 8 | fig = plt.figure(figsize=(10, 8)) 9 | ax = fig.add_subplot(111, projection='3d') 10 | ax.plot_surface(X, Y, Z, cmap='viridis') 11 | ax.set_title(title) 12 | plt.show() 13 | 14 | # Test case 15 | x = np.linspace(-5, 5, 100) 16 | y = np.linspace(-5, 5, 100) 17 | surface_plot(x, y, lambda x, y: np.sin(np.sqrt(x**2 + y**2))) 18 | -------------------------------------------------------------------------------- /pysnippets/Visualization/Violin_split.py: -------------------------------------------------------------------------------- 1 | import seaborn as sns 2 | import matplotlib.pyplot as plt 3 | 4 | def split_violin_plot(data, x, y, hue, split=True, title="Split Violin Plot", palette="Set2"): 5 | plt.figure(figsize=(10, 6)) 6 | sns.violinplot(data=data, x=x, y=y, hue=hue, split=split, palette=palette) 7 | plt.title(title) 8 | plt.show() 9 | 10 | # Test case 11 | data = sns.load_dataset("tips") 12 | split_violin_plot(data, x="day", y="total_bill", hue="sex") 13 | -------------------------------------------------------------------------------- /pysnippets/Visualization/__init__.py: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/UTSAVS26/PySnippets/7d663efc569f46c1550a16fbba42fa8e6e815b7e/pysnippets/Visualization/__init__.py -------------------------------------------------------------------------------- /pysnippets/Web/__init__.py: -------------------------------------------------------------------------------- 1 | pass -------------------------------------------------------------------------------- /pysnippets/Web/get_html.py: -------------------------------------------------------------------------------- 1 | #get_html.py 2 | 3 | import requests 4 | 5 | def get_html(url: str) -> str: 6 | """ 7 | Fetches the HTML content from the specified URL. 8 | 9 | Args: 10 | url (str): The URL from which to fetch the HTML content. 11 | 12 | Returns: 13 | str: The HTML content of the page if the request is successful. 14 | Returns None if there is an error fetching the URL. 15 | 16 | Example usage: 17 | get_html("https://www.example.com") -> "... (HTML content)" 18 | """ 19 | try: 20 | response = requests.get(url) 21 | response.raise_for_status() # Raise an error for bad responses 22 | return response.text # Return the HTML content 23 | except requests.exceptions.RequestException as e: 24 | print(f"Error fetching the URL: {e}") 25 | return None 26 | 27 | if __name__ == "__main__": 28 | # Example usage 29 | url = "https://www.example.com" # Replace with your desired URL 30 | html_content = get_html(url) 31 | if html_content: 32 | print(html_content) # Print the HTML content 33 | -------------------------------------------------------------------------------- /pysnippets/Web/get_image.py: -------------------------------------------------------------------------------- 1 | # get_image.py 2 | 3 | import requests 4 | 5 | def get_image(url: str, file_path: str) -> bool: 6 | """ 7 | Downloads an image from the specified URL and saves it to the specified file path. 8 | 9 | Args: 10 | url (str): The URL of the image to download. 11 | file_path (str): The file path where the image should be saved. 12 | 13 | Returns: 14 | bool: True if the image was successfully downloaded, False otherwise. 15 | """ 16 | try: 17 | response = requests.get(url) 18 | response.raise_for_status() # Raise an error for bad responses 19 | with open(file_path, 'wb') as file: 20 | file.write(response.content) 21 | return True 22 | except requests.exceptions.RequestException as e: 23 | print(f"Error downloading the image: {e}") 24 | return False 25 | 26 | -------------------------------------------------------------------------------- /pysnippets/__init__.py: -------------------------------------------------------------------------------- 1 | pass 2 | # __init__.py 3 | 4 | # This file allows the snippets folder to be treated as a package. 5 | # It can be empty or used to expose certain functions for easy imports. 6 | -------------------------------------------------------------------------------- /pysnippets/algorithms/__init__.py: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/UTSAVS26/PySnippets/7d663efc569f46c1550a16fbba42fa8e6e815b7e/pysnippets/algorithms/__init__.py -------------------------------------------------------------------------------- /pysnippets/algorithms/bfs.py: -------------------------------------------------------------------------------- 1 | from collections import deque 2 | from typing import Dict, List 3 | 4 | def bfs(graph: Dict[str, List[str]], start: str) -> List[str]: 5 | visited = set() 6 | queue = deque([start]) 7 | visited.add(start) 8 | order_of_visit = [] # To store the order of visited nodes 9 | 10 | while queue: 11 | vertex = queue.popleft() 12 | order_of_visit.append(vertex) 13 | 14 | for neighbor in graph[vertex]: 15 | if neighbor not in visited: 16 | visited.add(neighbor) 17 | queue.append(neighbor) 18 | 19 | return order_of_visit 20 | 21 | # Example usage: 22 | if __name__ == "__main__": 23 | graph = { 24 | 'A': ['B', 'C'], 25 | 'B': ['D', 'E'], 26 | 'C': ['F'], 27 | 'D': [], 28 | 'E': ['F'], 29 | 'F': [] 30 | } 31 | order = bfs(graph, 'A') 32 | print("Order of visit:", order) -------------------------------------------------------------------------------- /pysnippets/algorithms/binary_search.py: -------------------------------------------------------------------------------- 1 | from typing import List, Union 2 | 3 | def binary_search(arr: List[Union[int, float]], target: Union[int, float]) -> int: 4 | """ 5 | Performs binary search on a sorted array to find the target element. 6 | 7 | Args: 8 | arr (List[Union[int, float]]): A sorted list of elements to search through. 9 | target (Union[int, float]): The element to search for in the array. 10 | 11 | Returns: 12 | int: The index of the target if found, -1 if not found. 13 | 14 | Time Complexity: 15 | O(log n), where n is the number of elements in the array. 16 | 17 | Example: 18 | >>> binary_search([1, 2, 3, 4, 5], 3) 19 | 2 20 | """ 21 | low, high = 0, len(arr) - 1 22 | 23 | while low <= high: 24 | mid = low + (high - low) // 2 # Safe calculation of mid 25 | if arr[mid] == target: 26 | return mid 27 | elif arr[mid] < target: 28 | low = mid + 1 29 | else: 30 | high = mid - 1 31 | 32 | return -1 33 | 34 | # Example usage 35 | if __name__ == "__main__": 36 | result = binary_search([1, 2, 3, 4, 5], 3) 37 | print(result) # Output: 2 -------------------------------------------------------------------------------- /pysnippets/algorithms/dijkstras.py: -------------------------------------------------------------------------------- 1 | import sys 2 | 3 | def minimum(a, b): 4 | return a if a < b else b 5 | 6 | def dijkstra(cost, src, n): 7 | d = [sys.maxsize] * n 8 | s = [False] * n 9 | d[src] = 0 10 | 11 | for _ in range(n - 1): 12 | min_distance = sys.maxsize 13 | w = -1 14 | for j in range(n): 15 | if not s[j] and d[j] < min_distance: 16 | min_distance = d[j] 17 | w = j 18 | s[w] = True 19 | 20 | for v in range(n): 21 | if not s[v] and cost[w][v] != sys.maxsize: 22 | d[v] = minimum(d[v], d[w] + cost[w][v]) 23 | 24 | return d 25 | 26 | def main(): 27 | n = int(input("Enter number of vertices: ")) 28 | cost = [] 29 | print("Enter cost matrix:") 30 | for i in range(n): 31 | row = list(map(int, input().split())) 32 | cost.append(row) 33 | 34 | src = int(input("Enter source vertex: ")) 35 | shortest_distances = dijkstra(cost, src, n) 36 | print("Shortest distances from the source:") 37 | print(" ".join(map(str, shortest_distances))) 38 | 39 | if __name__ == "__main__": 40 | main() -------------------------------------------------------------------------------- /pysnippets/analysis/__init__.py: -------------------------------------------------------------------------------- 1 | # __init__.py 2 | 3 | # This file allows the snippets folder to be treated as a package. 4 | # It can be empty or used to expose certain functions for easy imports. 5 | -------------------------------------------------------------------------------- /pysnippets/clipboard_online/__init__.py: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/UTSAVS26/PySnippets/7d663efc569f46c1550a16fbba42fa8e6e815b7e/pysnippets/clipboard_online/__init__.py -------------------------------------------------------------------------------- /pysnippets/clipboard_online/package/__init__.py: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/UTSAVS26/PySnippets/7d663efc569f46c1550a16fbba42fa8e6e815b7e/pysnippets/clipboard_online/package/__init__.py -------------------------------------------------------------------------------- /pysnippets/clipboard_online/package/display.py: -------------------------------------------------------------------------------- 1 | from package.show import display 2 | from package.write import plot 3 | 4 | 5 | def write(snippet_name, password): 6 | return plot(snippet_name, password) 7 | 8 | 9 | def show(snippet_name, password, clipboard=None): 10 | return display(snippet_name, password, clipboard=None) 11 | -------------------------------------------------------------------------------- /pysnippets/clipboard_online/package/password.py: -------------------------------------------------------------------------------- 1 | from datetime import datetime 2 | 3 | 4 | def valid_password(password: int) -> bool: 5 | current_time = int(datetime.now().strftime("%H%M")) 6 | return password == current_time 7 | -------------------------------------------------------------------------------- /pysnippets/clipboard_online/package/stash/__init__.py: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/UTSAVS26/PySnippets/7d663efc569f46c1550a16fbba42fa8e6e815b7e/pysnippets/clipboard_online/package/stash/__init__.py -------------------------------------------------------------------------------- /pysnippets/clipboard_online/package/stash/test.py: -------------------------------------------------------------------------------- 1 | print("If it's visible, then it's good to go!") 2 | -------------------------------------------------------------------------------- /pysnippets/clipboard_online/package/test.py: -------------------------------------------------------------------------------- 1 | from scrap.grab import write, show, clip 2 | 3 | write("fghd", "text.txt") 4 | show("fghd") 5 | clip("fghd") 6 | -------------------------------------------------------------------------------- /pysnippets/clipboard_online/test_clip.py: -------------------------------------------------------------------------------- 1 | import pytest 2 | from package.clip import display 3 | from datetime import datetime 4 | import subprocess 5 | from package.clip import copy_to_clipboard 6 | 7 | 8 | def test_display_right_password(): 9 | current_time = datetime.now().strftime("%H%M") 10 | assert display("test", current_time) is None 11 | 12 | 13 | def test_display_wrong_password(): 14 | with pytest.raises(ValueError, match="Invalid password"): 15 | display("test", 1111) 16 | 17 | 18 | def test_copy_to_clipboard(monkeypatch): 19 | def mock_run(*args, **kwargs): 20 | pass 21 | 22 | monkeypatch.setattr(subprocess, "run", mock_run) 23 | 24 | try: 25 | copy_to_clipboard("Whatever test") 26 | except Exception: 27 | pytest.fail("Unexpected error raised: {e}") 28 | -------------------------------------------------------------------------------- /pysnippets/database/__init__.py: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/UTSAVS26/PySnippets/7d663efc569f46c1550a16fbba42fa8e6e815b7e/pysnippets/database/__init__.py -------------------------------------------------------------------------------- /pysnippets/database/mongodb/__init__.py: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/UTSAVS26/PySnippets/7d663efc569f46c1550a16fbba42fa8e6e815b7e/pysnippets/database/mongodb/__init__.py -------------------------------------------------------------------------------- /pysnippets/database/mongodb/mongo_connection_manager.py: -------------------------------------------------------------------------------- 1 | from pymongo import MongoClient 2 | 3 | def connect_to_mongodb(uri): 4 | """ 5 | Connects to a MongoDB instance. 6 | 7 | Args: 8 | uri (str): MongoDB URI string. 9 | 10 | Returns: 11 | pymongo.MongoClient: MongoDB connection object. 12 | """ 13 | client = MongoClient(uri) 14 | return client 15 | -------------------------------------------------------------------------------- /pysnippets/database/mongodb/mongo_document_insertion.py: -------------------------------------------------------------------------------- 1 | def insert_document(collection, document): 2 | """ 3 | Inserts a document into a MongoDB collection. 4 | 5 | Args: 6 | collection: The MongoDB collection object. 7 | document (dict): The document to insert. 8 | 9 | Returns: 10 | ObjectId: The ID of the inserted document. 11 | """ 12 | result = collection.insert_one(document) 13 | return result.inserted_id 14 | -------------------------------------------------------------------------------- /pysnippets/database/mongodb/mongo_document_query.py: -------------------------------------------------------------------------------- 1 | def query_documents(collection, filter_criteria=None, projection=None): 2 | """ 3 | Queries documents from a MongoDB collection based on filters and projections. 4 | 5 | Args: 6 | collection: The MongoDB collection object. 7 | filter_criteria (dict, optional): The query filter. 8 | projection (dict, optional): The fields to include or exclude. 9 | 10 | Returns: 11 | list: List of documents matching the filter. 12 | """ 13 | filter_criteria = filter_criteria or {} 14 | projection = projection or {} 15 | documents = collection.find(filter_criteria, projection) 16 | return list(documents) 17 | -------------------------------------------------------------------------------- /pysnippets/database/mongodb/mongo_document_update.py: -------------------------------------------------------------------------------- 1 | def update_document(collection, filter_criteria, update_data, multiple=False): 2 | """ 3 | Updates one or more documents in a MongoDB collection. 4 | 5 | Args: 6 | collection: The MongoDB collection object. 7 | filter_criteria (dict): The query filter to match documents. 8 | update_data (dict): The update data. 9 | multiple (bool, optional): If True, updates all matching documents. 10 | 11 | Returns: 12 | dict: The update result details. 13 | """ 14 | if multiple: 15 | result = collection.update_many(filter_criteria, {'$set': update_data}) 16 | else: 17 | result = collection.update_one(filter_criteria, {'$set': update_data}) 18 | return result.raw_result 19 | -------------------------------------------------------------------------------- /pysnippets/database/mongodb/mongo_index_management.py: -------------------------------------------------------------------------------- 1 | def create_index(collection, field, unique=False): 2 | """ 3 | Creates an index on a specified field in a MongoDB collection. 4 | 5 | Args: 6 | collection: The MongoDB collection object. 7 | field (str): The field to create the index on. 8 | unique (bool, optional): If True, creates a unique index. 9 | 10 | Returns: 11 | str: The name of the created index. 12 | """ 13 | index_name = collection.create_index([(field, 1)], unique=unique) 14 | return index_name 15 | 16 | def drop_index(collection, index_name): 17 | """ 18 | Drops a specific index from a MongoDB collection. 19 | 20 | Args: 21 | collection: The MongoDB collection object. 22 | index_name (str): The name of the index to drop. 23 | 24 | Returns: 25 | None 26 | """ 27 | collection.drop_index(index_name) 28 | -------------------------------------------------------------------------------- /pysnippets/database/mysql/__init__.py: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/UTSAVS26/PySnippets/7d663efc569f46c1550a16fbba42fa8e6e815b7e/pysnippets/database/mysql/__init__.py -------------------------------------------------------------------------------- /pysnippets/database/mysql/sql_data_insertion.py: -------------------------------------------------------------------------------- 1 | def bulk_insert(connection, table, data): 2 | """ 3 | Inserts multiple rows into an SQL table. 4 | 5 | Args: 6 | connection: The database connection object. 7 | table (str): The name of the table to insert data into. 8 | data (list of tuple): A list of tuples representing the rows to insert. 9 | 10 | Returns: 11 | None 12 | """ 13 | cursor = connection.cursor() 14 | placeholders = ', '.join(['%s'] * len(data[0])) 15 | query = f"INSERT INTO {table} VALUES ({placeholders})" 16 | cursor.executemany(query, data) 17 | connection.commit() 18 | cursor.close() 19 | -------------------------------------------------------------------------------- /pysnippets/database/mysql/sql_execute_query.py: -------------------------------------------------------------------------------- 1 | def execute_query(connection, query, params=None): 2 | """ 3 | Executes a SQL query (SELECT, INSERT, UPDATE, DELETE). 4 | 5 | Args: 6 | connection: The database connection object. 7 | query (str): The SQL query to execute. 8 | params (tuple, optional): The parameters for the query. 9 | 10 | Returns: 11 | list: The result of a SELECT query, or None for other queries. 12 | """ 13 | cursor = connection.cursor() 14 | cursor.execute(query, params) 15 | 16 | if query.strip().upper().startswith('SELECT'): 17 | result = cursor.fetchall() 18 | else: 19 | connection.commit() 20 | result = None 21 | 22 | cursor.close() 23 | return result 24 | -------------------------------------------------------------------------------- /pysnippets/database/mysql/sql_schema_creation.py: -------------------------------------------------------------------------------- 1 | def create_table(connection, create_table_query): 2 | """ 3 | Creates a table with the given SQL query. 4 | 5 | Args: 6 | connection: The database connection object. 7 | create_table_query (str): SQL query to create a table. 8 | 9 | Returns: 10 | None 11 | """ 12 | cursor = connection.cursor() 13 | cursor.execute(create_table_query) 14 | connection.commit() 15 | cursor.close() 16 | -------------------------------------------------------------------------------- /pysnippets/database/mysql/sql_transaction_handling.py: -------------------------------------------------------------------------------- 1 | def execute_transaction(connection, queries): 2 | """ 3 | Executes multiple SQL queries in a transaction with commit and rollback. 4 | 5 | Args: 6 | connection: The database connection object. 7 | queries (list): A list of SQL queries to execute. 8 | 9 | Returns: 10 | bool: True if transaction was committed, False if rolled back. 11 | """ 12 | cursor = connection.cursor() 13 | try: 14 | for query in queries: 15 | cursor.execute(query) 16 | connection.commit() 17 | return True 18 | except Exception as e: 19 | connection.rollback() 20 | print(f"Transaction failed: {e}") 21 | return False 22 | finally: 23 | cursor.close() 24 | -------------------------------------------------------------------------------- /pysnippets/date_utils/__init__.py: -------------------------------------------------------------------------------- 1 | # date_utils/__init__.py 2 | 3 | """ 4 | date_utils package. 5 | 6 | This package contains utilities for date manipulation, including 7 | functions to convert dates to ISO-8601 format. 8 | """ 9 | 10 | from .date_utils import convert_to_iso8601 # Import your function here 11 | -------------------------------------------------------------------------------- /pysnippets/date_utils/date_utils.py: -------------------------------------------------------------------------------- 1 | from datetime import datetime 2 | 3 | def convert_to_iso8601(date_string): 4 | """ 5 | Convert a date string to ISO-8601 format. 6 | 7 | Args: 8 | date_string (str): A date string in the format 'YYYY-MM-DD' or 'MM/DD/YYYY'. 9 | 10 | Returns: 11 | str: Date in ISO-8601 format (YYYY-MM-DD). 12 | """ 13 | try: 14 | # Try parsing the date in different formats 15 | if '-' in date_string: 16 | date_obj = datetime.strptime(date_string, '%Y-%m-%d') 17 | else: 18 | date_obj = datetime.strptime(date_string, '%m/%d/%Y') 19 | 20 | return date_obj.isoformat() 21 | except ValueError as e: 22 | return f"Error: {e}" 23 | 24 | # Example usage 25 | if __name__ == "__main__": 26 | print(convert_to_iso8601("2024-10-06")) # Outputs: 2024-10-06T00:00:00 27 | print(convert_to_iso8601("10/06/2024")) # Outputs: 2024-10-06T00:00:00 28 | -------------------------------------------------------------------------------- /pysnippets/dictionary/__init__.py: -------------------------------------------------------------------------------- 1 | # __init__.py 2 | 3 | # This file allows the snippets folder to be treated as a package. 4 | # It can be empty or used to expose certain functions for easy imports. 5 | -------------------------------------------------------------------------------- /pysnippets/dictionary/dictionarywithindices.md: -------------------------------------------------------------------------------- 1 | 2 | # Convert List to a Dictionary with Indices 3 | 4 | ## Overview 5 | 6 | This project provides a function to convert a list into a dictionary, where each list element maps to its index. This is useful in cases where you need to map unique items in a list to their respective positions. 7 | 8 | ## Files 9 | 10 | - **dictionarywithindices.py**: Contains the `convert_list_to_dict_with_indices` function, which performs the list-to-dictionary conversion. 11 | 12 | - **test_dictionarywithindices.py**: Contains unit tests for `convert_list_to_dict_with_indices`, verifying the correct functionality of the conversion. 13 | 14 | ## Example 15 | 16 | Given a list like `['a', 'b', 'c']`, the function will return `{'a': 0, 'b': 1, 'c': 2}`. 17 | 18 | ## How to Run Tests 19 | 20 | To run the unit tests, execute: 21 | 22 | ```bash 23 | python -m unittest test_dictionarywithindices.py 24 | ``` 25 | 26 | This will validate that the function works correctly. 27 | -------------------------------------------------------------------------------- /pysnippets/dictionary/dictionarywithindices.py: -------------------------------------------------------------------------------- 1 | 2 | def convert_list_to_dict_with_indices(lst): 3 | """ 4 | Converts a list to a dictionary with list values as keys and their indices as values. 5 | Example: 6 | Input: ['a', 'b', 'c'] 7 | Output: {'a': 0, 'b': 1, 'c': 2} 8 | """ 9 | return {value: index for index, value in enumerate(lst)} 10 | -------------------------------------------------------------------------------- /pysnippets/email_utils/__init__.py: -------------------------------------------------------------------------------- 1 | from .client import EmailClient, AsyncEmailClient 2 | from .bulk import BulkEmailSender 3 | from .exceptions import EmailError, SMTPConnectionError, AttachmentError, TemplateError 4 | 5 | __all__ = [ 6 | 'EmailClient', 7 | 'AsyncEmailClient', 8 | 'BulkEmailSender', 9 | 'EmailError', 10 | 'SMTPConnectionError', 11 | 'AttachmentError', 12 | 'TemplateError' 13 | ] -------------------------------------------------------------------------------- /pysnippets/email_utils/exceptions.py: -------------------------------------------------------------------------------- 1 | class EmailError(Exception): 2 | """Base exception for email operations.""" 3 | pass 4 | 5 | class SMTPConnectionError(EmailError): 6 | """Raised when SMTP connection fails.""" 7 | pass 8 | 9 | class AttachmentError(EmailError): 10 | """Raised when handling attachments fails.""" 11 | pass 12 | 13 | class TemplateError(EmailError): 14 | """Raised when template processing fails.""" 15 | pass -------------------------------------------------------------------------------- /pysnippets/email_utils/requirements.txt: -------------------------------------------------------------------------------- 1 | aiosmtplib>=2.0.0 # For async email support 2 | python-dotenv>=0.19.0 # For environment variable management -------------------------------------------------------------------------------- /pysnippets/encryption/__init__.py: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/UTSAVS26/PySnippets/7d663efc569f46c1550a16fbba42fa8e6e815b7e/pysnippets/encryption/__init__.py -------------------------------------------------------------------------------- /pysnippets/encryption/test.txt: -------------------------------------------------------------------------------- 1 | nMV8eW4+DYPuS30sd0I48b8yf0rDeZvvkwzVNC4hbpWMPGfzMFLy+el7VWLuIj2m -------------------------------------------------------------------------------- /pysnippets/encryption/test_encryption.py: -------------------------------------------------------------------------------- 1 | import unittest 2 | from Crypto.Random import get_random_bytes 3 | from encryption import AESCipher 4 | 5 | class TestAESCipher(unittest.TestCase): 6 | def setUp(self): 7 | self.passphrase = "test_passphrase" 8 | self.salt = get_random_bytes(16) 9 | self.key = AESCipher.generate_key(self.passphrase, self.salt) 10 | self.cipher = AESCipher(self.key) 11 | 12 | def test_encryption_decryption(self): 13 | original_data = b"Hello, World!" 14 | encrypted_data = self.cipher.encrypt(original_data) 15 | decrypted_data = self.cipher.decrypt(encrypted_data) 16 | self.assertEqual(original_data.decode(), decrypted_data) 17 | 18 | def test_padding_unpadding(self): 19 | data = b"Hello" 20 | padded_data = self.cipher.pad(data) 21 | unpadded_data = self.cipher.unpad(padded_data) 22 | self.assertEqual(data, unpadded_data) 23 | 24 | if __name__ == "__main__": 25 | unittest.main() -------------------------------------------------------------------------------- /pysnippets/graphing/__init__.py: -------------------------------------------------------------------------------- 1 | __all__ = [] 2 | -------------------------------------------------------------------------------- /pysnippets/list/__init__.py: -------------------------------------------------------------------------------- 1 | # __init__.py 2 | 3 | # This file allows the snippets folder to be treated as a package. 4 | # It can be empty or used to expose certain functions for easy imports. 5 | -------------------------------------------------------------------------------- /pysnippets/models/CV_means.py: -------------------------------------------------------------------------------- 1 | import numpy as np 2 | from sklearn.model_selection import cross_val_score 3 | from sklearn.linear_model import LinearRegression 4 | import logging 5 | 6 | class CVMeansModel: 7 | """Model to compute cross-validation mean score for Linear Regression.""" 8 | 9 | def __init__(self): 10 | self.model = LinearRegression() 11 | self.logger = logging.getLogger(__name__) 12 | self.logger.info("Initialized LinearRegression model.") 13 | 14 | def cross_val_mean(self, X: np.ndarray, y: np.ndarray, cv: int = 5) -> float: 15 | """Compute the mean cross-validation score.""" 16 | try: 17 | return np.mean(cross_val_score(self.model, X, y, cv=cv)) 18 | except Exception as e: 19 | self.logger.error(f"Error during cross-validation: {e}") 20 | raise 21 | 22 | -------------------------------------------------------------------------------- /pysnippets/models/__init__.py: -------------------------------------------------------------------------------- 1 | from .Catboost import CatBoostModel 2 | from .CV_means import CVMeansModel 3 | from .Ensemble import EnsembleModel 4 | from .Grid_search import GridSearchModel 5 | from .KMeans import KMeansModel 6 | from .LightGBM import LightGBMModel 7 | from .Linear_regression import LinearModel 8 | from .Logistic_regression import LogisticModel 9 | from .XGB import XGBModel -------------------------------------------------------------------------------- /pysnippets/password_generator/__init__.py: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/UTSAVS26/PySnippets/7d663efc569f46c1550a16fbba42fa8e6e815b7e/pysnippets/password_generator/__init__.py -------------------------------------------------------------------------------- /pysnippets/password_generator/data_classes.py: -------------------------------------------------------------------------------- 1 | from dataclasses import dataclass 2 | 3 | @dataclass 4 | class PasswordConfig: 5 | length: int = 12 6 | use_upper: bool = True 7 | use_lower: bool = True 8 | use_digits: bool = True 9 | use_symbols: bool = True 10 | min_length: int = 8 11 | max_length: int = 64 12 | require_upper: bool = True 13 | require_lower: bool = True 14 | require_digits: bool = True 15 | require_symbols: bool = True -------------------------------------------------------------------------------- /pysnippets/password_generator/hasher.py: -------------------------------------------------------------------------------- 1 | import bcrypt 2 | from logging_config import logger 3 | 4 | class Hasher: 5 | def hash_password(self, password): 6 | try: 7 | salt = bcrypt.gensalt() 8 | hashed = bcrypt.hashpw(password.encode('utf-8'), salt) 9 | return hashed.decode('utf-8') 10 | except Exception as e: 11 | logger.error("Error hashing password: %s", str(e)) 12 | raise 13 | 14 | def verify_password(self, password, hashed): 15 | try: 16 | return bcrypt.checkpw(password.encode('utf-8'), hashed.encode('utf-8')) 17 | except Exception as e: 18 | logger.error("Error verifying password: %s", str(e)) 19 | raise -------------------------------------------------------------------------------- /pysnippets/password_generator/logging_config.py: -------------------------------------------------------------------------------- 1 | import logging 2 | 3 | logger = logging.getLogger('password_generator') 4 | logger.setLevel(logging.INFO) 5 | handler = logging.StreamHandler() 6 | formatter = logging.Formatter('%(asctime)s - %(name)s - %(levelname)s - %(message)s') 7 | handler.setFormatter(formatter) 8 | logger.addHandler(handler) 9 | 10 | def setup_logging(): 11 | return logger -------------------------------------------------------------------------------- /pysnippets/password_generator/test_hasher.py: -------------------------------------------------------------------------------- 1 | import unittest 2 | from hasher import Hasher 3 | 4 | class TestHasher(unittest.TestCase): 5 | def setUp(self): 6 | self.hasher = Hasher() 7 | 8 | def test_hash_and_verify_password(self): 9 | password = "TestP@ssw0rd!" 10 | hashed = self.hasher.hash_password(password) 11 | self.assertTrue(self.hasher.verify_password(password, hashed)) 12 | 13 | def test_verify_wrong_password(self): 14 | password = "TestP@ssw0rd!" 15 | wrong_password = "WrongP@ssw0rd!" 16 | hashed = self.hasher.hash_password(password) 17 | self.assertFalse(self.hasher.verify_password(wrong_password, hashed)) 18 | 19 | def test_hash_password_error(self): 20 | with self.assertRaises(Exception): 21 | self.hasher.hash_password(None) 22 | 23 | def test_verify_password_error(self): 24 | with self.assertRaises(Exception): 25 | self.hasher.verify_password("password", None) 26 | 27 | if __name__ == '__main__': 28 | unittest.main() -------------------------------------------------------------------------------- /pysnippets/password_generator/test_validators.py: -------------------------------------------------------------------------------- 1 | import unittest 2 | from validators import PasswordValidator 3 | 4 | class TestPasswordValidator(unittest.TestCase): 5 | def setUp(self): 6 | self.validator = PasswordValidator() 7 | 8 | def test_validate_success(self): 9 | self.assertTrue(self.validator.validate("ValidP@ssw0rd")) 10 | 11 | def test_validate_length_failure(self): 12 | self.assertFalse(self.validator.validate("Short1!")) 13 | 14 | def test_validate_upper_failure(self): 15 | self.assertFalse(self.validator.validate("lowercase1!")) 16 | 17 | def test_validate_lower_failure(self): 18 | self.assertFalse("UPPERCASE1!") 19 | 20 | def test_validate_digits_failure(self): 21 | self.assertFalse(self.validator.validate("NoDigits!@#")) 22 | 23 | def test_validate_symbols_failure(self): 24 | self.assertFalse(self.validator.validate("NoSymbols123")) 25 | 26 | if __name__ == '__main__': 27 | unittest.main() -------------------------------------------------------------------------------- /pysnippets/password_generator/validators.py: -------------------------------------------------------------------------------- 1 | import re 2 | 3 | class PasswordValidator: 4 | def __init__(self, min_length=8, max_length=64, require_upper=True, require_lower=True, require_digits=True, require_symbols=True): 5 | self.min_length = min_length 6 | self.max_length = max_length 7 | self.require_upper = require_upper 8 | self.require_lower = require_lower 9 | self.require_digits = require_digits 10 | self.require_symbols = require_symbols 11 | 12 | def validate(self, password): 13 | if not (self.min_length <= len(password) <= self.max_length): 14 | return False 15 | if self.require_upper and not re.search(r'[A-Z]', password): 16 | return False 17 | if self.require_lower and not re.search(r'[a-z]', password): 18 | return False 19 | if self.require_digits and not re.search(r'\d', password): 20 | return False 21 | if self.require_symbols and not re.search(r'[!@#$%^&*(),.?":{}|<>]', password): 22 | return False 23 | return True -------------------------------------------------------------------------------- /pysnippets/qrcode/__init__.py: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/UTSAVS26/PySnippets/7d663efc569f46c1550a16fbba42fa8e6e815b7e/pysnippets/qrcode/__init__.py -------------------------------------------------------------------------------- /pysnippets/stats/__init__.py: -------------------------------------------------------------------------------- 1 | from .coefficient_of_variation import coefficient_of_variation 2 | from .correlation import correlation 3 | from .iqr import iqr 4 | from .kurtosis import kurtosis 5 | from .mean_median_mode import mean, median, mode 6 | from .quantile import quantile 7 | from .skewness import skewness 8 | from .standard_deviation import standard_deviation 9 | from .variance import variance 10 | from .z_score_normalization import z_score_normalization 11 | 12 | __all__ = [ 13 | 'coefficient_of_variation', 14 | 'correlation', 15 | 'iqr', 16 | 'kurtosis', 17 | 'mean', 18 | 'median', 19 | 'mode', 20 | 'quantile', 21 | 'skewness', 22 | 'standard_deviation', 23 | 'variance', 24 | 'z_score_normalization' 25 | ] 26 | -------------------------------------------------------------------------------- /pysnippets/system/__init__.py: -------------------------------------------------------------------------------- 1 | # __init__.py 2 | 3 | # This file allows the snippets folder to be treated as a package. 4 | # It can be empty or used to expose certain functions for easy imports. 5 | -------------------------------------------------------------------------------- /pysnippets/system/test_disk_space_checker.py: -------------------------------------------------------------------------------- 1 | import unittest 2 | from unittest.mock import patch 3 | from disk_space_checker import check_disk_space 4 | 5 | class TestDiskSpaceChecker(unittest.TestCase): 6 | def test_disk_space_checker(self): 7 | # Test with default path 8 | result = check_disk_space('/') 9 | self.assertIsInstance(result.total_space_gb, float) 10 | self.assertIsInstance(result.used_space_gb, float) 11 | self.assertIsInstance(result.free_space_gb, float) 12 | self.assertIsInstance(result.used_percent, float) 13 | self.assertIsInstance(result.free_percent, float) 14 | 15 | def test_invalid_path(self): 16 | with self.assertRaises(FileNotFoundError): 17 | check_disk_space('/invalid/path') 18 | 19 | @patch('shutil.disk_usage') 20 | def test_permission_error(self, mock_disk_usage): 21 | mock_disk_usage.side_effect = PermissionError("Permission denied for path '/root'") 22 | with self.assertRaises(PermissionError): 23 | check_disk_space('/root') 24 | 25 | if __name__ == '__main__': 26 | unittest.main() -------------------------------------------------------------------------------- /pysnippets/testcase2.py: -------------------------------------------------------------------------------- 1 | class TreeNode: 2 | def __init__(self, value=0, left=None, right=None): 3 | self.value = value 4 | self.left = left 5 | self.right = right 6 | 7 | def is_balanced(root): 8 | def check_balance(node): 9 | if not node: 10 | return 0 11 | left_height = check_balance(node.left) 12 | if left_height == -1: 13 | return -1 14 | right_height = check_balance(node.right) 15 | if right_height == -1 or abs(left_height - right_height) > 1: 16 | return -1 17 | return 1 + max(left_height, right_height) 18 | return check_balance(root) != -1 19 | -------------------------------------------------------------------------------- /pysnippets/testcase3.py: -------------------------------------------------------------------------------- 1 | class TreeNode: 2 | def __init__(self, value=0, left=None, right=None): 3 | self.value = value 4 | self.left = left 5 | self.right = right 6 | 7 | def lowest_common_ancestor(root, p, q): 8 | if not root or root == p or root == q: 9 | return root 10 | left = lowest_common_ancestor(root.left, p, q) 11 | right = lowest_common_ancestor(root.right, p, q) 12 | return root if left and right else left or right 13 | -------------------------------------------------------------------------------- /pysnippets/testcase4.py: -------------------------------------------------------------------------------- 1 | class TreeNode: 2 | def __init__(self, value=0, left=None, right=None): 3 | self.value = value 4 | self.left = left 5 | self.right = right 6 | 7 | def is_bst(root, min_val=float('-inf'), max_val=float('inf')): 8 | if not root: 9 | return True 10 | if not (min_val < root.value < max_val): 11 | return False 12 | return is_bst(root.left, min_val, root.value) and is_bst(root.right, root.value, max_val) 13 | -------------------------------------------------------------------------------- /pysnippets/testcase5.py: -------------------------------------------------------------------------------- 1 | class TreeNode: 2 | def __init__(self, value=0, left=None, right=None): 3 | self.value = value 4 | self.left = left 5 | self.right = right 6 | 7 | def tree_diameter(root): 8 | diameter = 0 9 | 10 | def depth(node): 11 | nonlocal diameter 12 | if not node: 13 | return 0 14 | left_depth = depth(node.left) 15 | right_depth = depth(node.right) 16 | diameter = max(diameter, left_depth + right_depth) 17 | return 1 + max(left_depth, right_depth) 18 | 19 | depth(root) 20 | return diameter 21 | -------------------------------------------------------------------------------- /pysnippets/testcase6.py: -------------------------------------------------------------------------------- 1 | class TreeNode: 2 | def __init__(self, value=0, left=None, right=None): 3 | self.value = value 4 | self.left = left 5 | self.right = right 6 | 7 | def invert_tree(root): 8 | if root: 9 | root.left, root.right = invert_tree(root.right), invert_tree(root.left) 10 | return root 11 | -------------------------------------------------------------------------------- /pysnippets/testcase7.py: -------------------------------------------------------------------------------- 1 | from collections import deque 2 | 3 | class TreeNode: 4 | def __init__(self, value=0, left=None, right=None): 5 | self.value = value 6 | self.left = left 7 | self.right = right 8 | 9 | def serialize(root): 10 | data, queue = [], deque([root]) 11 | while queue: 12 | node = queue.popleft() 13 | if node: 14 | data.append(str(node.value)) 15 | queue.append(node.left) 16 | queue.append(node.right) 17 | else: 18 | data.append('#') 19 | return ' '.join(data) 20 | 21 | def deserialize(data): 22 | if data == '#': 23 | return None 24 | nodes = data.split() 25 | root = TreeNode(int(nodes[0])) 26 | queue = deque([root]) 27 | index = 1 28 | while queue: 29 | node = queue.popleft() 30 | if nodes[index] != '#': 31 | node.left = TreeNode(int(nodes[index])) 32 | queue.append(node.left) 33 | index += 1 34 | if nodes[index] != '#': 35 | node.right = TreeNode(int(nodes[index])) 36 | queue.append(node.right) 37 | index += 1 38 | return root 39 | -------------------------------------------------------------------------------- /pysnippets/testcase8.py: -------------------------------------------------------------------------------- 1 | class TreeNode: 2 | def __init__(self, value=0, left=None, right=None): 3 | self.value = value 4 | self.left = left 5 | self.right = right 6 | 7 | def build_tree(preorder, inorder): 8 | if not preorder or not inorder: 9 | return None 10 | root_value = preorder.pop(0) 11 | root = TreeNode(root_value) 12 | inorder_index = inorder.index(root_value) 13 | root.left = build_tree(preorder, inorder[:inorder_index]) 14 | root.right = build_tree(preorder, inorder[inorder_index + 1:]) 15 | return root 16 | -------------------------------------------------------------------------------- /pysnippets/tkinter/__init__.py: -------------------------------------------------------------------------------- 1 | import tkinter as tk 2 | from tkinter import messagebox 3 | 4 | class App: 5 | """ 6 | The App class sets up the main application window and its widgets. 7 | """ 8 | def __init__(self, root): 9 | self.root = root 10 | self.root.title("Tkinter Example App") 11 | self.root.geometry("300x200") 12 | 13 | # Create a label widget 14 | self.label = tk.Label(self.root, text="Hello, Tkinter!") 15 | self.label.pack(pady=10) 16 | 17 | # Create a button widget 18 | self.button = tk.Button(self.root, text="Click Me", command=self.on_button_click) 19 | self.button.pack(pady=10) 20 | 21 | def on_button_click(self): 22 | """ 23 | Callback function for button click event. 24 | Displays a message box when the button is clicked. 25 | """ 26 | messagebox.showinfo("Information", "Button was clicked!") 27 | -------------------------------------------------------------------------------- /pysnippets/tkinter/dialogs.py: -------------------------------------------------------------------------------- 1 | from tkinter import messagebox 2 | 3 | def show_confirmation(title: str, message: str) -> bool: 4 | """ 5 | Displays a confirmation dialog and returns True if the user confirms, False otherwise. 6 | 7 | Args: 8 | title (str): The title of the dialog window. 9 | message (str): The message displayed in the dialog. 10 | 11 | Returns: 12 | bool: True if user clicks 'Yes', False if 'No'. 13 | """ 14 | return messagebox.askyesno(title, message) 15 | 16 | def show_error(title: str, message: str): 17 | """ 18 | Displays an error message dialog. 19 | 20 | Args: 21 | title (str): The title of the error dialog. 22 | message (str): The error message to display. 23 | """ 24 | messagebox.showerror(title, message) 25 | 26 | def show_info(title: str, message: str): 27 | """ 28 | Displays an informational message dialog. 29 | 30 | Args: 31 | title (str): The title of the info dialog. 32 | message (str): The information message to display. 33 | """ 34 | messagebox.showinfo(title, message) -------------------------------------------------------------------------------- /pysnippets/tkinter/main.py: -------------------------------------------------------------------------------- 1 | import tkinter as tk 2 | from pysnippets.tkinter.widgets import CustomEntry 3 | from pysnippets.tkinter.dialogs import show_confirmation 4 | 5 | def main(): 6 | """ 7 | The main function initializes the Tkinter root window and starts the application. 8 | """ 9 | root = tk.Tk() 10 | root.title("Custom Entry Example") 11 | 12 | entry = CustomEntry(root, placeholder="Enter your name") 13 | entry.pack(pady=20, padx=20) 14 | 15 | def on_exit(): 16 | if show_confirmation("Exit", "Are you sure you want to exit?"): 17 | root.destroy() 18 | 19 | exit_button = tk.Button(root, text="Exit", command=on_exit) 20 | exit_button.pack(pady=10) 21 | 22 | root.mainloop() 23 | 24 | if __name__ == "__main__": 25 | main() 26 | -------------------------------------------------------------------------------- /pysnippets/tkinter/styles.py: -------------------------------------------------------------------------------- 1 | from tkinter import ttk 2 | 3 | def configure_styles(): 4 | """ 5 | Configures and applies custom styles to ttk widgets. 6 | """ 7 | style = ttk.Style() 8 | 9 | # Set the theme to 'clam' which is more customizable 10 | style.theme_use('clam') 11 | 12 | # Configure a style for TButton 13 | style.configure('Custom.TButton', 14 | foreground='white', 15 | background='#4CAF50', 16 | font=('Helvetica', 12, 'bold')) 17 | 18 | style.map('Custom.TButton', 19 | background=[('active', '#45a049')]) 20 | 21 | # Configure a style for TLabel 22 | style.configure('Custom.TLabel', 23 | foreground='#333333', 24 | font=('Helvetica', 10)) 25 | 26 | # Configure a style for TEntry 27 | style.configure('Custom.TEntry', 28 | foreground='#000000', 29 | font=('Helvetica', 10)) -------------------------------------------------------------------------------- /pysnippets/tkinter/widgets.py: -------------------------------------------------------------------------------- 1 | import tkinter as tk 2 | 3 | class CustomEntry(tk.Entry): 4 | """ 5 | A custom Entry widget with placeholder text functionality. 6 | """ 7 | def __init__(self, master=None, placeholder="Enter text here", color='grey', **kwargs): 8 | super().__init__(master, **kwargs) 9 | self.placeholder = placeholder 10 | self.placeholder_color = color 11 | self.default_fg_color = self['fg'] 12 | self.bind("", self._clear_placeholder) 13 | self.bind("", self._add_placeholder) 14 | self._add_placeholder() 15 | 16 | def _clear_placeholder(self, event): 17 | if self['fg'] == self.placeholder_color: 18 | self.delete(0, tk.END) 19 | self.config(fg=self.default_fg_color) 20 | 21 | def _add_placeholder(self, event=None): 22 | if not self.get(): 23 | self.insert(0, self.placeholder) 24 | self.config(fg=self.placeholder_color) -------------------------------------------------------------------------------- /pysnippets/utilities/__init__.py: -------------------------------------------------------------------------------- 1 | # __init__.py 2 | 3 | # This file allows the snippets folder to be treated as a package. 4 | # It can be empty or used to expose certain functions for easy imports. -------------------------------------------------------------------------------- /pysnippets/utilities/advanced_logger.py: -------------------------------------------------------------------------------- 1 | import logging 2 | from dataclasses import dataclass, field 3 | from typing import Optional 4 | 5 | 6 | @dataclass 7 | class LoggerConfig: 8 | name: str 9 | level: int = logging.INFO 10 | log_file: Optional[str] = None 11 | formatter: str = '%(asctime)s - %(name)s - %(levelname)s - %(message)s' 12 | console: bool = True 13 | file_mode: str = 'a' 14 | 15 | 16 | class AdvancedLogger: 17 | def __init__(self, config: LoggerConfig): 18 | self.logger = logging.getLogger(config.name) 19 | self.logger.setLevel(config.level) 20 | formatter = logging.Formatter(config.formatter) 21 | 22 | if config.console: 23 | console_handler = logging.StreamHandler() 24 | console_handler.setFormatter(formatter) 25 | self.logger.addHandler(console_handler) 26 | 27 | if config.log_file: 28 | file_handler = logging.FileHandler(config.log_file, mode=config.file_mode) 29 | file_handler.setFormatter(formatter) 30 | self.logger.addHandler(file_handler) 31 | 32 | def get_logger(self) -> logging.Logger: 33 | return self.logger -------------------------------------------------------------------------------- /pysnippets/utilities/caching.md: -------------------------------------------------------------------------------- 1 | (file is identical to original version) -------------------------------------------------------------------------------- /pysnippets/utilities/caching.py: -------------------------------------------------------------------------------- 1 | import functools 2 | 3 | def cache(func): 4 | cached_results = {} 5 | 6 | @functools.wraps(func) 7 | def wrapper(*args): 8 | if args not in cached_results: 9 | cached_results[args] = func(*args) 10 | return cached_results[args] 11 | 12 | return wrapper 13 | -------------------------------------------------------------------------------- /pysnippets/utilities/deep_copy.md: -------------------------------------------------------------------------------- 1 | (file is identical to original version) -------------------------------------------------------------------------------- /pysnippets/utilities/deep_copy.py: -------------------------------------------------------------------------------- 1 | import copy 2 | 3 | def deep_copy(obj): 4 | return copy.deepcopy(obj) 5 | -------------------------------------------------------------------------------- /pysnippets/utilities/flatten.py: -------------------------------------------------------------------------------- 1 | 2 | def flatten_list(nested_list): 3 | flat_list = [] 4 | 5 | for item in nested_list: 6 | if isinstance(item, list): 7 | flat_list.extend(flatten_list(item)) # Recursive call for nested lists 8 | else: 9 | flat_list.append(item) 10 | 11 | return flat_list 12 | -------------------------------------------------------------------------------- /pysnippets/utilities/flatten_nested_list.md: -------------------------------------------------------------------------------- 1 | (file is identical to original version) -------------------------------------------------------------------------------- /pysnippets/utilities/retry.py: -------------------------------------------------------------------------------- 1 | from typing import Callable 2 | 3 | 4 | def retry(retries: int = 3) -> Callable: 5 | def decorator(func: Callable) -> Callable: 6 | def wrapper(*args, **kwargs): 7 | last_exception = None 8 | for attempt in range(retries): # Allow retries minus one final attempt 9 | try: 10 | return func(*args, **kwargs) 11 | except Exception as e: 12 | last_exception = e 13 | # One last attempt without catching an exception 14 | return func(*args, **kwargs) 15 | 16 | return wrapper 17 | 18 | return decorator 19 | -------------------------------------------------------------------------------- /pysnippets/utilities/timer.py: -------------------------------------------------------------------------------- 1 | import time 2 | from typing import Callable 3 | 4 | 5 | def time_execution(func: Callable) -> Callable: 6 | def wrapper(*args, **kwargs): 7 | start_time = time.time() 8 | result = func(*args, **kwargs) 9 | end_time = time.time() 10 | print(f"Execution time: {end_time - start_time} seconds") 11 | return result 12 | 13 | return wrapper 14 | -------------------------------------------------------------------------------- /pysnippets/webscrape/__init__.py: -------------------------------------------------------------------------------- 1 | from .scraper import QuoteScraper, Quote 2 | -------------------------------------------------------------------------------- /stargazers/.eslintrc: -------------------------------------------------------------------------------- 1 | { 2 | "extends": "@remotion", 3 | } 4 | -------------------------------------------------------------------------------- /stargazers/.gitignore: -------------------------------------------------------------------------------- 1 | node_modules 2 | dist 3 | .DS_Store 4 | todo.md 5 | .env 6 | 7 | build 8 | -------------------------------------------------------------------------------- /stargazers/.prettierrc: -------------------------------------------------------------------------------- 1 | { 2 | "useTabs": false, 3 | "bracketSpacing": true, 4 | "tabWidth": 2 5 | } 6 | -------------------------------------------------------------------------------- /stargazers/out/main.mp4: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/UTSAVS26/PySnippets/7d663efc569f46c1550a16fbba42fa8e6e815b7e/stargazers/out/main.mp4 -------------------------------------------------------------------------------- /stargazers/package.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "template-stargazer", 3 | "version": "1.0.0", 4 | "scripts": { 5 | "dev": "remotion studio", 6 | "build": "remotion render main out/Main.mp4 --log verbose", 7 | "test": "eslint src --ext ts,tsx,js,jsx && tsc" 8 | }, 9 | "license": "UNLICENSED", 10 | "dependencies": { 11 | "@remotion/bundler": "^4.0.0", 12 | "@remotion/cli": "^4.0.0", 13 | "@remotion/renderer": "^4.0.0", 14 | "react": "18.3.1", 15 | "react-dom": "18.3.1", 16 | "remotion": "^4.0.0", 17 | "zod": "3.22.3" 18 | }, 19 | "devDependencies": { 20 | "@remotion/eslint-config": "^4.0.0", 21 | "@types/react": "18.3.1", 22 | "eslint": "8.56.0", 23 | "prettier": "3.3.3", 24 | "typescript": "5.5.4" 25 | }, 26 | "private": true 27 | } 28 | -------------------------------------------------------------------------------- /stargazers/remotion.config.ts: -------------------------------------------------------------------------------- 1 | import { Config } from "@remotion/cli/config"; 2 | 3 | /** 4 | * Note: When using the Node.JS APIs, the config file 5 | * doesn't apply. Instead, pass options directly to the APIs 6 | */ 7 | 8 | Config.setVideoImageFormat("jpeg"); 9 | Config.setDelayRenderTimeoutInMilliseconds(1200000); 10 | -------------------------------------------------------------------------------- /stargazers/src/Main.tsx: -------------------------------------------------------------------------------- 1 | import { useCurrentFrame, useVideoConfig } from "remotion"; 2 | import { z } from "zod"; 3 | import { Stargazer } from "./cache"; 4 | import { Content } from "./Content"; 5 | import { getProgress } from "./utils"; 6 | 7 | export const mainSchema = z.object({ 8 | repoOrg: z.string(), 9 | repoName: z.string(), 10 | starCount: z.number().step(1), 11 | duration: z.number().step(1), 12 | }); 13 | 14 | type SchemaProps = z.infer; 15 | 16 | export type MainProps = SchemaProps & { 17 | stargazers: Stargazer[] | null; 18 | }; 19 | 20 | export function Main({ repoOrg, repoName, stargazers }: MainProps) { 21 | const frame = useCurrentFrame(); 22 | const { fps, durationInFrames } = useVideoConfig(); 23 | 24 | const extraEnding = fps; 25 | 26 | if (!stargazers) { 27 | return null; 28 | } 29 | 30 | const progress = getProgress( 31 | frame, 32 | durationInFrames - extraEnding, 33 | stargazers.length, 34 | fps, 35 | ); 36 | 37 | return ( 38 | 44 | ); 45 | } 46 | -------------------------------------------------------------------------------- /stargazers/src/index.ts: -------------------------------------------------------------------------------- 1 | import { registerRoot } from "remotion"; 2 | import { RemotionRoot } from "./Root"; 3 | 4 | registerRoot(RemotionRoot); 5 | -------------------------------------------------------------------------------- /stargazers/src/wait-for-no-input.ts: -------------------------------------------------------------------------------- 1 | import { getRemotionEnvironment } from "remotion"; 2 | 3 | export const waitForNoInput = (signal: AbortSignal, ms: number) => { 4 | // Don't wait during rendering 5 | if (getRemotionEnvironment().isRendering) { 6 | return Promise.resolve(); 7 | } 8 | 9 | if (signal.aborted) { 10 | return Promise.reject(new Error("stale")); 11 | } 12 | 13 | return Promise.race([ 14 | new Promise((_, reject) => { 15 | signal.addEventListener("abort", () => { 16 | reject(new Error("stale")); 17 | }); 18 | }), 19 | new Promise((resolve) => { 20 | setTimeout(() => { 21 | resolve(); 22 | }, ms); 23 | }), 24 | ]); 25 | }; 26 | -------------------------------------------------------------------------------- /stargazers/tsconfig.json: -------------------------------------------------------------------------------- 1 | { 2 | "compilerOptions": { 3 | "target": "ES2018", 4 | "module": "commonjs", 5 | "jsx": "react-jsx", 6 | "strict": true, 7 | "noEmit": true, 8 | "lib": ["es2015", "DOM"], 9 | "esModuleInterop": true, 10 | "skipLibCheck": true, 11 | "forceConsistentCasingInFileNames": true, 12 | "strictNullChecks": true, 13 | "noUnusedLocals": true, 14 | "incremental": true 15 | }, 16 | "exclude": ["remotion.config.ts"] 17 | } 18 | --------------------------------------------------------------------------------