├── 0x10-python-network_0 ├── 6-peak.txt ├── 1-body.sh ├── 100-status_code.sh ├── 2-delete.sh ├── 3-methods.sh ├── 4-header.sh ├── 0-body_size.sh ├── 5-post_params.sh ├── 101-post_json.sh ├── 102-catch_me.sh └── 6-peak.py ├── 0x0C-python-almost_a_circle ├── models │ ├── __init__.py │ ├── rectangle.py │ ├── square.py │ └── base.py ├── tests │ ├── __init__.py │ ├── test_square.py │ ├── test_rectangle.py │ └── rectangle_unitest.py └── README.md ├── 0x09-python-everything_is_object ├── 1-answer.txt ├── 103-line1.txt ├── 103-line2.txt ├── 104-line1.txt ├── 104-line2.txt ├── 104-line3.txt ├── 104-line5.txt ├── 106-line1.txt ├── 106-line2.txt ├── 106-line3.txt ├── 106-line5.txt ├── 16-answer.txt ├── 2-answer.txt ├── 22-answer.txt ├── 27-answer.txt ├── 3-answer.txt ├── 4-answer.txt ├── 5-answer.txt ├── 0-answer.txt ├── 10-answer.txt ├── 104-line4.txt ├── 105-line1.txt ├── 106-line4.txt ├── 11-answer.txt ├── 12-answer.txt ├── 13-answer.txt ├── 20-answer.txt ├── 21-answer.txt ├── 23-answer.txt ├── 24-answer.txt ├── 25-answer.txt ├── 26-answer.txt ├── 28-answer.txt ├── 6-answer.txt ├── 7-answer.txt ├── 8-answer.txt ├── 9-answer.txt ├── python3 ├── 14-answer.txt ├── 15-answer.txt ├── 17-answer.txt ├── 18-answer.txt ├── README.md ├── 19-copy_list.py ├── 101-locked_class.py ├── 100-main.py ├── 100-magic_string.py~ └── 100-magic_string.py ├── 0x06-python-classes ├── READEME.md ├── README.md ├── 0-square.py ├── 1-square.py ├── 2-square.py ├── 3-square.py ├── 103-magic_class.py ├── 4-square.py ├── 6-square.py └── 5-square.py ├── 0x0E-SQL_more_queries ├── README.md ├── 3-force_name.sql ├── 4-never_empty.sql ├── 5-unique_id.sql ├── 0-privileges.sql ├── 1-create_user.sql ├── 9-cities_by_state_join.sql ├── 8-cities_of_california_subquery.sql ├── 10-genre_id_by_show.sql ├── 11-genre_id_all_shows.sql ├── 2-create_read_user.sql ├── 12-no_genre.sql ├── 13-count_shows_by_genre.sql ├── 14-my_genres.sql ├── 15-comedy_only.sql ├── 16-shows_by_genre.sql ├── 7-cities.sql ├── 101-not_a_comedy.sql ├── 100-not_my_genres.sql ├── 102-rating_shows.sql ├── 6-states.sql └── hbtn_0d_tvshows.sql ├── 0x11-python-network_1 ├── README.md ├── 1-hbtn_header.py ├── 5-hbtn_header.py ├── 4-hbtn_status.py ├── 6-post_email.py ├── 7-error_code.py ├── 2-post_email.py ├── 3-error_code.py ├── 10-my_github.py ├── 0-hbtn_status.py ├── 100-github_commits.py └── 8-json_api.py ├── 0x0A-python-inheritance ├── README.md ├── 6-base_geometry.py ├── 5-base_geometry.py ├── 0-lookup.py ├── 101-add_attribute.py ├── 2-is_same_class.py ├── 100-my_int.py ├── 1-my_list.py ├── 3-is_kind_of_class.py ├── 4-inherits_from.py ├── 7-base_geometry.py ├── 10-square.py ├── 11-square.py ├── 8-rectangle.py ├── 9-rectangle.py └── tests │ └── 1-my_list.txt ├── 0x0B-python-input_output ├── README.md ├── 4-append_write.py ├── 10-class_to_json.py ├── 5-to_json_string.py ├── 0-read_file.py ├── 3-write_file.py ├── 6-from_json_string.py ├── 8-load_from_json_file.py ├── 12-student.py ├── 7-save_to_json_file.py ├── 1-number_of_lines.py ├── 11-student.py ├── 100-append_after.py ├── 9-add_item.py └── 2-read_lines.py ├── 0x00-python-hello_world ├── 0-run ├── 9-easter_egg.py ├── 1-run_inline ├── main.py ├── q ├── 2-print.py ├── 102-magic_calculation.py ├── 3-print_number.py ├── 4-print_float.py ├── 5-print_string.py ├── 101-compile ├── 6-concat.py ├── 100-write.py ├── 8-concat_edges.py ├── README.md └── 7-edges.py ├── 0x08-python-more_classes ├── README.md ├── 0-rectangle.py ├── 101-nqueens.py ├── 1-rectangle.py ├── 3-rectangle.py ├── 2-rectangle.py ├── 4-rectangle.py ├── 6-rectangle.py ├── 5-rectangle.py ├── 7-rectangle.py └── 9-rectangle.py ├── 0x0D-SQL_introduction ├── README.md ├── 0-list_databases.sql ├── 6-list_values.sql ├── 2-remove_database.sql ├── 1-create_database_if_missing.sql ├── 13-change_class.sql ├── 12-no_cheating.sql ├── 14-average.sql ├── 10-top_score.sql ├── 8-count_89.sql ├── 5-full_table.sql ├── 16-no_link.sql ├── 11-best_score.sql ├── 7-insert_value.sql ├── 4-first_table.sql ├── 15-groups.sql └── 9-full_creation.sql ├── 0x15-javascript-web_jquery ├── README.md ├── 1-script.js ├── 5-script.js ├── 3-script.js ├── 100-script.js ├── 4-script.js ├── 6-script.js ├── 0-script.js ├── 2-script.js ├── 9-script.js ├── 7-script.js ├── 8-script.js └── 8-main.html ├── 0x03-python-data_structures ├── README.md ├── 12-switch.py ├── 1-element_at.py ├── 0-print_list_integer.py ├── .13-is_palindrome.c.swp ├── 11-delete_at.py ├── 6-print_matrix_integer.py ├── 0-main.py ├── 2-replace_in_list.py ├── 7-add_tuple.py ├── __pycache__ │ └── 0-print_list_integer.cpython-36.pyc ├── 3-print_reversed_list_integer.py ├── 8-multiple_returns.py ├── 4-new_in_list.py ├── 9-max_integer.py ├── 5-no_c.py ├── 13-is_palindrome.c ├── 10-divisible_by_2.py ├── lists.h ├── 100-print_python_list_info.py └── 100-print_python_list_info.c ├── 0x04-python-more_data_structures ├── 12-roman_to_int.py ├── README.md ├── 2-uniq_add.py ├── 5-number_keys.py ├── 3-common_elements.py ├── 4-only_diff_elements.py ├── 7-update_dictionary.py ├── 11-mutiply_list_map.py ├── 101-square_matrix_map.py ├── 8-simple_delete.py ├── 1-search_replace.py ├── 6-print_sorted_dictionary.py ├── 9-multiply_by_2.py ├── 0-square_matrix_simple.py ├── 10-best_score.py ├── 100-weight_average.py ├── 102-complex_delete.py ├── 103-python.py ├── 103-python.c └── 103-tests.py ├── 0x07-python-test_driven_development ├── README.md ├── 2-main.py ├── 102-python.c ├── 100-matrix_mul.py ├── 101-lazy_matrix_mul.py ├── 0-add_integer.py ├── 4-print_square.py ├── tests │ ├── 4-print_square.txt │ ├── 101-lazy_matrix_mul.txt │ ├── 0-add_integer.txt │ ├── 3-say_my_name.txt │ ├── 6-max_integer_test.py │ ├── 100-matrix_mul.txt │ └── 2-matrix_divided.txt ├── 3-say_my_name.py └── 2-matrix_divided.py ├── 0x12-javascript-warm_up ├── 100-let_me_const.js ├── README.md ├── 13-add.js ├── 0-javascript_is_amazing.js ├── 102-add_me_maybe.js ├── 101-call_me_moby.js ├── 12-object.js ├── 3-value_argument.js ├── 6-multi_languages_loop.js ├── 1-multi_languages.js ├── 2-arguments.js ├── 5-to_integer.js ├── 7-multi_c.js ├── 9-add.js ├── 8-square.js ├── 10-factorial.js ├── 11-second_biggest.js └── 4-concat.js ├── 0x01-python-if_else_loops_functions ├── README.md ├── 10-add.py ├── 11-pow.py ├── 4-print_hexa.py ├── 2-print_alphabet.py ├── 5-print_comb2.py ├── 10-main.py ├── 101-remove_char_at.py ├── 7-islower.py ├── 8-main.py ├── 102-magic_calculation.py ├── 11-main.py ├── __pycache__ │ ├── 7-islower.cpython-36.pyc │ └── 8-uppercase.cpython-36.pyc ├── 3-print_alphabt.py ├── 6-print_comb3.py~ ├── 8-uppercase.py ├── 6-print_comb3.py ├── 100-print_tebahpla.py ├── 0-positive_or_negative.py ├── 9-print_last_digit.py ├── 12-fizzbuzz.py ├── 7-main.py └── 1-last_digit.py ├── 0x02-python-import_modules ├── 101-easy_print.py ├── variable_load_5.py ├── 103-fast_alphabet.py ├── 0-add.py ├── 5-variable_load.py ├── README.md ├── add_0.py ├── 4-hidden_discovery.py ├── 102-magic_calculation.py ├── 1-calculation.py ├── 3-infinite_add.py ├── 2-args.py ├── 100-my_calculator.py └── calculator_1.py ├── 0x13-javascript_objects_scopes_closures ├── 100-data.js ├── 0-rectangle.js ├── README.md ├── 101-data.js ├── 9-logme.js ├── 10-converter.js ├── 1-rectangle.js ├── 2-rectangle.js ├── 7-occurrences.js ├── 8-esrever.js ├── 100-map.js ├── 102-concat.js ├── 5-square.js ├── 101-sorted.js ├── 3-rectangle.js ├── 6-square.js └── 4-rectangle.js ├── 0x05-python-exceptions ├── 5-raise_exception.py ├── README.md ├── 102-magic_calculation.py ├── 6-raise_exception_msg.py ├── 1-safe_print_integer.py ├── 101-safe_function.py ├── 3-safe_print_division.py ├── 0-safe_print_list.py ├── 100-safe_print_integer_err.py ├── 2-safe_print_list_integers.py ├── 103-python.c ├── 4-list_division.py └── 103-tests.py ├── 0x14-javascript-web_scraping ├── README.md ├── 5-request_store.js ├── 1-writeme.js ├── 0-readme.js ├── 2-statuscode.js ├── 3-starwars_title.js ├── 100-starwars_characters.js ├── 101-starwars_characters.js ├── 6-completed_tasks.js ├── 4-starwars_count.js └── 102-search_twitter.js ├── README.md ├── 0x0F-python-object_relational_mapping ├── README.md ├── model_city.py ├── 0-select_states.py ├── 1-filter_states.py ├── 3-my_safe_filter_states.py ├── 2-my_filter_states.py ├── 11-model_state_insert.py ├── 4-cities_by_state.py ├── 13-model_state_delete_a.py ├── 9-model_state_filter_a.py ├── model_state.py ├── 100-relationship_states_cities.py ├── 7-model_state_fetch_all.py ├── 5-filter_cities.py ├── 12-model_state_update_id_2.py ├── 101-relationship_states_cities_list.py ├── 8-model_state_fetch_first.py ├── 102-relationship_cities_states_list.py ├── 14-model_city_fetch_by_state.py ├── 10-model_state_my_get.py ├── relationship_state.py ├── relationship_city.py └── 14-model_city_fetch_by_state.sql └── #1-last_digit.py# /0x10-python-network_0/6-peak.txt: -------------------------------------------------------------------------------- 1 | O(log(n)) -------------------------------------------------------------------------------- /0x0C-python-almost_a_circle/models/__init__.py: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /0x0C-python-almost_a_circle/tests/__init__.py: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /0x09-python-everything_is_object/1-answer.txt: -------------------------------------------------------------------------------- 1 | id 2 | -------------------------------------------------------------------------------- /0x09-python-everything_is_object/103-line1.txt: -------------------------------------------------------------------------------- 1 | 0 2 | -------------------------------------------------------------------------------- /0x09-python-everything_is_object/103-line2.txt: -------------------------------------------------------------------------------- 1 | 0 2 | -------------------------------------------------------------------------------- /0x09-python-everything_is_object/104-line1.txt: -------------------------------------------------------------------------------- 1 | 0 2 | -------------------------------------------------------------------------------- /0x09-python-everything_is_object/104-line2.txt: -------------------------------------------------------------------------------- 1 | 1 2 | -------------------------------------------------------------------------------- /0x09-python-everything_is_object/104-line3.txt: -------------------------------------------------------------------------------- 1 | No 2 | -------------------------------------------------------------------------------- /0x09-python-everything_is_object/104-line5.txt: -------------------------------------------------------------------------------- 1 | 1 2 | -------------------------------------------------------------------------------- /0x09-python-everything_is_object/106-line1.txt: -------------------------------------------------------------------------------- 1 | 1 2 | -------------------------------------------------------------------------------- /0x09-python-everything_is_object/106-line2.txt: -------------------------------------------------------------------------------- 1 | 0 2 | -------------------------------------------------------------------------------- /0x09-python-everything_is_object/106-line3.txt: -------------------------------------------------------------------------------- 1 | No 2 | -------------------------------------------------------------------------------- /0x09-python-everything_is_object/106-line5.txt: -------------------------------------------------------------------------------- 1 | 0 2 | -------------------------------------------------------------------------------- /0x09-python-everything_is_object/16-answer.txt: -------------------------------------------------------------------------------- 1 | 1 2 | -------------------------------------------------------------------------------- /0x09-python-everything_is_object/2-answer.txt: -------------------------------------------------------------------------------- 1 | No 2 | -------------------------------------------------------------------------------- /0x09-python-everything_is_object/22-answer.txt: -------------------------------------------------------------------------------- 1 | No 2 | -------------------------------------------------------------------------------- /0x09-python-everything_is_object/27-answer.txt: -------------------------------------------------------------------------------- 1 | No 2 | -------------------------------------------------------------------------------- /0x09-python-everything_is_object/3-answer.txt: -------------------------------------------------------------------------------- 1 | Yes 2 | -------------------------------------------------------------------------------- /0x09-python-everything_is_object/4-answer.txt: -------------------------------------------------------------------------------- 1 | Yes 2 | -------------------------------------------------------------------------------- /0x09-python-everything_is_object/5-answer.txt: -------------------------------------------------------------------------------- 1 | No 2 | -------------------------------------------------------------------------------- /0x06-python-classes/READEME.md: -------------------------------------------------------------------------------- 1 | Python - Classes and Objects -------------------------------------------------------------------------------- /0x06-python-classes/README.md: -------------------------------------------------------------------------------- 1 | Python - Classes and Objects -------------------------------------------------------------------------------- /0x09-python-everything_is_object/0-answer.txt: -------------------------------------------------------------------------------- 1 | type 2 | -------------------------------------------------------------------------------- /0x09-python-everything_is_object/10-answer.txt: -------------------------------------------------------------------------------- 1 | True 2 | -------------------------------------------------------------------------------- /0x09-python-everything_is_object/104-line4.txt: -------------------------------------------------------------------------------- 1 | Yes 2 | -------------------------------------------------------------------------------- /0x09-python-everything_is_object/105-line1.txt: -------------------------------------------------------------------------------- 1 | 262 2 | -------------------------------------------------------------------------------- /0x09-python-everything_is_object/106-line4.txt: -------------------------------------------------------------------------------- 1 | Yes 2 | -------------------------------------------------------------------------------- /0x09-python-everything_is_object/11-answer.txt: -------------------------------------------------------------------------------- 1 | False 2 | -------------------------------------------------------------------------------- /0x09-python-everything_is_object/12-answer.txt: -------------------------------------------------------------------------------- 1 | True 2 | -------------------------------------------------------------------------------- /0x09-python-everything_is_object/13-answer.txt: -------------------------------------------------------------------------------- 1 | True 2 | -------------------------------------------------------------------------------- /0x09-python-everything_is_object/20-answer.txt: -------------------------------------------------------------------------------- 1 | Yes 2 | -------------------------------------------------------------------------------- /0x09-python-everything_is_object/21-answer.txt: -------------------------------------------------------------------------------- 1 | Yes 2 | -------------------------------------------------------------------------------- /0x09-python-everything_is_object/23-answer.txt: -------------------------------------------------------------------------------- 1 | Yes 2 | -------------------------------------------------------------------------------- /0x09-python-everything_is_object/24-answer.txt: -------------------------------------------------------------------------------- 1 | True 2 | -------------------------------------------------------------------------------- /0x09-python-everything_is_object/25-answer.txt: -------------------------------------------------------------------------------- 1 | False 2 | -------------------------------------------------------------------------------- /0x09-python-everything_is_object/26-answer.txt: -------------------------------------------------------------------------------- 1 | True 2 | -------------------------------------------------------------------------------- /0x09-python-everything_is_object/28-answer.txt: -------------------------------------------------------------------------------- 1 | Yes 2 | -------------------------------------------------------------------------------- /0x09-python-everything_is_object/6-answer.txt: -------------------------------------------------------------------------------- 1 | True 2 | -------------------------------------------------------------------------------- /0x09-python-everything_is_object/7-answer.txt: -------------------------------------------------------------------------------- 1 | True 2 | -------------------------------------------------------------------------------- /0x09-python-everything_is_object/8-answer.txt: -------------------------------------------------------------------------------- 1 | True 2 | -------------------------------------------------------------------------------- /0x09-python-everything_is_object/9-answer.txt: -------------------------------------------------------------------------------- 1 | True 2 | -------------------------------------------------------------------------------- /0x09-python-everything_is_object/python3: -------------------------------------------------------------------------------- 1 | /usr/bin/python3 -------------------------------------------------------------------------------- /0x0E-SQL_more_queries/README.md: -------------------------------------------------------------------------------- 1 | 0x0E. SQL - More queries -------------------------------------------------------------------------------- /0x11-python-network_1/README.md: -------------------------------------------------------------------------------- 1 | 0x11. Python - Network #1 -------------------------------------------------------------------------------- /0x09-python-everything_is_object/14-answer.txt: -------------------------------------------------------------------------------- 1 | [1, 2, 3, 4] 2 | -------------------------------------------------------------------------------- /0x09-python-everything_is_object/15-answer.txt: -------------------------------------------------------------------------------- 1 | [1, 2, 3] 2 | -------------------------------------------------------------------------------- /0x09-python-everything_is_object/17-answer.txt: -------------------------------------------------------------------------------- 1 | [1, 2, 3, 4] 2 | -------------------------------------------------------------------------------- /0x09-python-everything_is_object/18-answer.txt: -------------------------------------------------------------------------------- 1 | [1, 2, 3] 2 | -------------------------------------------------------------------------------- /0x0A-python-inheritance/README.md: -------------------------------------------------------------------------------- 1 | 0x0A. Python - Inheritance -------------------------------------------------------------------------------- /0x0B-python-input_output/README.md: -------------------------------------------------------------------------------- 1 | 0x0B. Python - Input/Output -------------------------------------------------------------------------------- /0x00-python-hello_world/0-run: -------------------------------------------------------------------------------- 1 | #!/bin/bash 2 | python3 $PYFILE 3 | -------------------------------------------------------------------------------- /0x08-python-more_classes/README.md: -------------------------------------------------------------------------------- 1 | Python - More Classes and Objects -------------------------------------------------------------------------------- /0x0D-SQL_introduction/README.md: -------------------------------------------------------------------------------- 1 | # 0x0D. SQL - Introduction 2 | 3 | -------------------------------------------------------------------------------- /0x15-javascript-web_jquery/README.md: -------------------------------------------------------------------------------- 1 | 0x15. Javascript - Web JQuery -------------------------------------------------------------------------------- /0x09-python-everything_is_object/README.md: -------------------------------------------------------------------------------- 1 | Python - Everything is object -------------------------------------------------------------------------------- /0x00-python-hello_world/9-easter_egg.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python3 2 | import this 3 | -------------------------------------------------------------------------------- /0x03-python-data_structures/README.md: -------------------------------------------------------------------------------- 1 | Python - Data Structures: Lists, Tuples -------------------------------------------------------------------------------- /0x04-python-more_data_structures/12-roman_to_int.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python3 2 | -------------------------------------------------------------------------------- /0x07-python-test_driven_development/README.md: -------------------------------------------------------------------------------- 1 | Python - Test-driven development -------------------------------------------------------------------------------- /0x00-python-hello_world/1-run_inline: -------------------------------------------------------------------------------- 1 | #!/bin/bash 2 | echo $PYCODE | python3 3 | -------------------------------------------------------------------------------- /0x12-javascript-warm_up/100-let_me_const.js: -------------------------------------------------------------------------------- 1 | #!/usr/bin/node 2 | myVar = 333; 3 | -------------------------------------------------------------------------------- /0x00-python-hello_world/main.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python3 2 | print("Holberton School") 3 | -------------------------------------------------------------------------------- /0x00-python-hello_world/q: -------------------------------------------------------------------------------- 1 | and that piece of art is useful - Dora Korpar, 2015-10-19 2 | -------------------------------------------------------------------------------- /0x01-python-if_else_loops_functions/README.md: -------------------------------------------------------------------------------- 1 | x01. Python - if/else, loops, functions -------------------------------------------------------------------------------- /0x02-python-import_modules/101-easy_print.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python3 2 | import py_print 3 | -------------------------------------------------------------------------------- /0x04-python-more_data_structures/README.md: -------------------------------------------------------------------------------- 1 | Python - More Data Structures: Set, Dictionary -------------------------------------------------------------------------------- /0x01-python-if_else_loops_functions/10-add.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python3 2 | def add(a, b): 3 | return a + b 4 | -------------------------------------------------------------------------------- /0x13-javascript_objects_scopes_closures/100-data.js: -------------------------------------------------------------------------------- 1 | #!/usr/bin/node 2 | exports.list = [1, 2, 3, 4, 5]; 3 | -------------------------------------------------------------------------------- /0x01-python-if_else_loops_functions/11-pow.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python3 2 | def pow(a, b): 3 | return a ** b 4 | -------------------------------------------------------------------------------- /0x02-python-import_modules/variable_load_5.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python3 2 | a = 98 3 | """Simple variable 4 | """ 5 | -------------------------------------------------------------------------------- /0x09-python-everything_is_object/19-copy_list.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python3 2 | def copy_list(l): 3 | return l[:] 4 | -------------------------------------------------------------------------------- /0x12-javascript-warm_up/README.md: -------------------------------------------------------------------------------- 1 | vascript - Warm up 2 | Foundations - Higher-level programming Javascript 3 | -------------------------------------------------------------------------------- /0x05-python-exceptions/5-raise_exception.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python3 2 | def raise_exception(): 3 | raise TypeError 4 | -------------------------------------------------------------------------------- /0x05-python-exceptions/README.md: -------------------------------------------------------------------------------- 1 | 0x05. Python - Exceptions 2 | 3 | Foundations - Higher-level programming Python -------------------------------------------------------------------------------- /0x0D-SQL_introduction/0-list_databases.sql: -------------------------------------------------------------------------------- 1 | -- script for lists all databases in MySQL server 2 | SHOW DATABASES; 3 | -------------------------------------------------------------------------------- /0x12-javascript-warm_up/13-add.js: -------------------------------------------------------------------------------- 1 | #!/usr/bin/node 2 | exports.add = function (a, b) { 3 | return (a + b); 4 | }; 5 | -------------------------------------------------------------------------------- /0x00-python-hello_world/2-print.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python3 2 | print('"Programming is like building a multilingual puzzle') 3 | -------------------------------------------------------------------------------- /0x02-python-import_modules/103-fast_alphabet.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python3 2 | import string 3 | print(string.ascii_uppercase) 4 | -------------------------------------------------------------------------------- /0x13-javascript_objects_scopes_closures/0-rectangle.js: -------------------------------------------------------------------------------- 1 | #!/usr/bin/node 2 | 3 | module.exports = class Rectangle {}; 4 | -------------------------------------------------------------------------------- /0x00-python-hello_world/102-magic_calculation.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python3 2 | def magic_calculation(a, b): 3 | return (98 + a**b) 4 | -------------------------------------------------------------------------------- /0x00-python-hello_world/3-print_number.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python3 2 | number = 98 3 | print('{:d} Battery street'.format(number)) 4 | -------------------------------------------------------------------------------- /0x00-python-hello_world/4-print_float.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python3 2 | number = 3.14159 3 | print('Float: {:04.2f}'.format(number)) 4 | -------------------------------------------------------------------------------- /0x14-javascript-web_scraping/README.md: -------------------------------------------------------------------------------- 1 | 0x14. Javascript - Web scraping 2 | Foundations - Higher-level programming Javascript -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | 0x00. Python - Hello, World 2 | 3 | - Higher-level programming Python # holbertonschool-higher_level_programming 4 | -------------------------------------------------------------------------------- /0x00-python-hello_world/5-print_string.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python3 2 | str = "Holberton School" 3 | print(str * 3) 4 | print(str[:9]) 5 | -------------------------------------------------------------------------------- /0x04-python-more_data_structures/2-uniq_add.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python3 2 | def uniq_add(my_list=[]): 3 | return(sum(set(my_list))) 4 | -------------------------------------------------------------------------------- /0x04-python-more_data_structures/5-number_keys.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python3 2 | def number_keys(my_dict): 3 | return (len(my_dict)) 4 | -------------------------------------------------------------------------------- /0x06-python-classes/0-square.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python3 2 | 3 | 4 | class Square: 5 | '''Class Square 6 | ''' 7 | pass 8 | -------------------------------------------------------------------------------- /0x09-python-everything_is_object/101-locked_class.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python3 2 | class LockedClass: 3 | __slots__ = "first_name" 4 | -------------------------------------------------------------------------------- /0x10-python-network_0/1-body.sh: -------------------------------------------------------------------------------- 1 | #!/bin/bash 2 | # Script takes URL, sends GET request and displays body of response 3 | curl -sL "$1" 4 | -------------------------------------------------------------------------------- /0x12-javascript-warm_up/0-javascript_is_amazing.js: -------------------------------------------------------------------------------- 1 | #!/usr/bin/node 2 | const myVar = 'Javascript is amazing'; 3 | console.log(myVar); 4 | -------------------------------------------------------------------------------- /0x00-python-hello_world/101-compile: -------------------------------------------------------------------------------- 1 | #!/bin/bash 2 | python3 -m compileall $PYFILE; cp __pycache__/*.pyc "${PYFILE}c"; rm -rf ./__pycache__ 3 | -------------------------------------------------------------------------------- /0x03-python-data_structures/12-switch.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python3 2 | a = 89 3 | b = 10 4 | a, b = b, a 5 | print("a={:d} - b={:d}".format(a, b)) 6 | -------------------------------------------------------------------------------- /0x10-python-network_0/100-status_code.sh: -------------------------------------------------------------------------------- 1 | #!/bin/bash 2 | # Displays only the status code 3 | curl -sLw "%{http_code}" -o /dev/null "$1" 4 | -------------------------------------------------------------------------------- /0x01-python-if_else_loops_functions/4-print_hexa.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python3 2 | for i in range(0, 99): 3 | print("{:d} = 0x{:x}".format(i, i)) 4 | -------------------------------------------------------------------------------- /0x05-python-exceptions/102-magic_calculation.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python3 2 | def magic_calculation(a, b): 3 | result = 0 4 | return result 5 | -------------------------------------------------------------------------------- /0x05-python-exceptions/6-raise_exception_msg.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python3 2 | def raise_exception_msg(message=""): 3 | raise NameError(message) 4 | -------------------------------------------------------------------------------- /0x0D-SQL_introduction/6-list_values.sql: -------------------------------------------------------------------------------- 1 | -- script that lists all rows of the table first_table from the database 2 | SELECT * FROM first_table; 3 | -------------------------------------------------------------------------------- /0x10-python-network_0/2-delete.sh: -------------------------------------------------------------------------------- 1 | #!/bin/bash 2 | # Script sends a DELETE request to URL passed as first argument 3 | curl -sX "DELETE" "$1" 4 | -------------------------------------------------------------------------------- /0x0D-SQL_introduction/2-remove_database.sql: -------------------------------------------------------------------------------- 1 | -- script that deletes the database hbtn_0c_0 in your MySQL server 2 | DROP DATABASE IF EXISTS hbtn_0c_0; 3 | -------------------------------------------------------------------------------- /0x0F-python-object_relational_mapping/README.md: -------------------------------------------------------------------------------- 1 | # 0x0F. Python - Object-relational mapping 2 | 3 | ## Foundations - Higher-level programming ― Python -------------------------------------------------------------------------------- /0x13-javascript_objects_scopes_closures/README.md: -------------------------------------------------------------------------------- 1 | 0x13. Javascript - Objects, Scopes and Closures 2 | Foundations - Higher-level programming Javascript -------------------------------------------------------------------------------- /0x04-python-more_data_structures/3-common_elements.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python3 2 | def common_elements(set_1, set_2): 3 | return(set_1.intersection(set_2)) 4 | -------------------------------------------------------------------------------- /0x01-python-if_else_loops_functions/2-print_alphabet.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python3 2 | for i in range(ord('a'), ord('z') + 1): 3 | print("{:s}".format(chr(i)), end="") 4 | -------------------------------------------------------------------------------- /0x03-python-data_structures/1-element_at.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python3 2 | def element_at(my_list, idx): 3 | return(my_list[idx] if 0 <= idx < len(my_list) else "None") 4 | -------------------------------------------------------------------------------- /0x10-python-network_0/3-methods.sh: -------------------------------------------------------------------------------- 1 | #!/bin/bash 2 | # Script that displays all HTTP methods the server accepts 3 | curl -sI "$1" | grep "Allow" | cut -d " " -f2- 4 | -------------------------------------------------------------------------------- /0x12-javascript-warm_up/102-add_me_maybe.js: -------------------------------------------------------------------------------- 1 | #!/usr/bin/node 2 | exports.addMeMaybe = function (var1, callback) { 3 | var1 = var1 + 1; 4 | callback(var1); 5 | }; 6 | -------------------------------------------------------------------------------- /0x00-python-hello_world/6-concat.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python3 2 | str1 = "Holberton" 3 | str2 = "School" 4 | str1 = str1 + ' ' + str2 5 | print("Welcome to {}!".format(str1)) 6 | -------------------------------------------------------------------------------- /0x04-python-more_data_structures/4-only_diff_elements.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python3 2 | def only_diff_elements(set_1, set_2): 3 | return(set_1.symmetric_difference(set_2)) 4 | -------------------------------------------------------------------------------- /0x0D-SQL_introduction/1-create_database_if_missing.sql: -------------------------------------------------------------------------------- 1 | -- Script that creates the database hbtn_0c_0 in your MySQL server 2 | CREATE DATABASE IF NOT EXISTS hbtn_0c_0; 3 | -------------------------------------------------------------------------------- /0x0D-SQL_introduction/13-change_class.sql: -------------------------------------------------------------------------------- 1 | -- a script that removes all records with a score <= 5 in the table second_table 2 | DELETE FROM second_table WHERE score <= 5; 3 | -------------------------------------------------------------------------------- /0x01-python-if_else_loops_functions/5-print_comb2.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python3 2 | for i in range(0, 99): 3 | print("{0:02d}".format(i), end=", ") 4 | print("{:d}".format(99)) 5 | -------------------------------------------------------------------------------- /0x03-python-data_structures/0-print_list_integer.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python3 2 | def print_list_integer(my_list=[]): 3 | for i in my_list: 4 | print('{:d}'.format(i)) 5 | -------------------------------------------------------------------------------- /0x0D-SQL_introduction/12-no_cheating.sql: -------------------------------------------------------------------------------- 1 | -- a script that updates the score of Bob to 10 in the table second_table 2 | UPDATE second_table SET score = 10 WHERE name = 'Bob'; 3 | -------------------------------------------------------------------------------- /0x0D-SQL_introduction/14-average.sql: -------------------------------------------------------------------------------- 1 | -- a script that computes the score average of all records in the table second_table 2 | SELECT AVG(score) AS average FROM second_table; 3 | -------------------------------------------------------------------------------- /0x10-python-network_0/4-header.sh: -------------------------------------------------------------------------------- 1 | #!/bin/bash 2 | # Script that sends a GET request to URL and displays body of response 3 | curl -sH "X-HolbertonSchool-User-Id: 98" "$1" 4 | -------------------------------------------------------------------------------- /0x01-python-if_else_loops_functions/10-main.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python3 2 | add = __import__('10-add').add 3 | 4 | print(add(1, 2)) 5 | print(add(98, 0)) 6 | print(add(100, -2)) 7 | -------------------------------------------------------------------------------- /0x04-python-more_data_structures/7-update_dictionary.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python3 2 | def update_dictionary(my_dict, key, value): 3 | my_dict[key] = value 4 | return (my_dict) 5 | -------------------------------------------------------------------------------- /0x0D-SQL_introduction/10-top_score.sql: -------------------------------------------------------------------------------- 1 | -- script that lists all records of the table second_table ordered by score 2 | SELECT score, name FROM second_table ORDER BY score DESC; 3 | -------------------------------------------------------------------------------- /0x10-python-network_0/0-body_size.sh: -------------------------------------------------------------------------------- 1 | #!/bin/bash 2 | # Script that takes in a URL, sends a request and displays the size 3 | curl -sI "$1" | grep "Content-Length" | cut -d " " -f2 4 | -------------------------------------------------------------------------------- /0x10-python-network_0/5-post_params.sh: -------------------------------------------------------------------------------- 1 | #!/bin/bash 2 | # Script sends POST to URL 3 | curl -sX POST -d "email=hr@holbertonschool.com&subject=I will always be here for PLD" "$1" 4 | -------------------------------------------------------------------------------- /0x15-javascript-web_jquery/1-script.js: -------------------------------------------------------------------------------- 1 | // script that updates the text color of the HTML tag HEADER to red 2 | // with jQuery API 3 | 4 | $('header').css({ color: '#FF0000' }); 5 | -------------------------------------------------------------------------------- /0x15-javascript-web_jquery/5-script.js: -------------------------------------------------------------------------------- 1 | // Javascript script that adds a LI element 2 | 3 | $('#add_item').click(function () { 4 | $('ul').append('
  • Item
  • '); 5 | }); 6 | -------------------------------------------------------------------------------- /0x00-python-hello_world/100-write.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python3 2 | import sys 3 | str = "and that piece of art is useful - Dora Korpar, 2015-10-19\n" 4 | sys.stderr.write(str) 5 | sys.exit(1) 6 | -------------------------------------------------------------------------------- /0x03-python-data_structures/.13-is_palindrome.c.swp: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/afinesami/holbertonschool-higher_level_programming/HEAD/0x03-python-data_structures/.13-is_palindrome.c.swp -------------------------------------------------------------------------------- /0x04-python-more_data_structures/11-mutiply_list_map.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python3 2 | def mutiply_list_map(my_list=[], number=0): 3 | return (list(map(lambda x: x * number, my_list))) 4 | -------------------------------------------------------------------------------- /0x0A-python-inheritance/6-base_geometry.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python3 2 | 3 | 4 | class BaseGeometry: 5 | 6 | def area(self): 7 | raise Exception("area() is not implemented") 8 | -------------------------------------------------------------------------------- /0x01-python-if_else_loops_functions/101-remove_char_at.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python3 2 | def remove_char_at(str, n): 3 | if n >= 0: 4 | str = str[:n] + str[n + 1:] 5 | return str 6 | -------------------------------------------------------------------------------- /0x01-python-if_else_loops_functions/7-islower.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python3 2 | def islower(c): 3 | if ord(c) >= ord('a') and ord(c) <= ord('z'): 4 | return True 5 | return False 6 | -------------------------------------------------------------------------------- /0x04-python-more_data_structures/101-square_matrix_map.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python3 2 | def square_matrix_map(matrix=[]): 3 | return (list(map(lambda r: list(map(lambda x: x**2, r)), matrix))) 4 | -------------------------------------------------------------------------------- /0x09-python-everything_is_object/100-main.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python3 2 | magic_string = __import__('100-magic_string').magic_string 3 | 4 | for i in range(10): 5 | print(magic_string()) 6 | -------------------------------------------------------------------------------- /0x0D-SQL_introduction/8-count_89.sql: -------------------------------------------------------------------------------- 1 | -- script that displays the number of records with id = 89 in the table first_table of the database 2 | SELECT COUNT(id) FROM first_table WHERE id=89; 3 | -------------------------------------------------------------------------------- /0x03-python-data_structures/11-delete_at.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python3 2 | def delete_at(my_list=[], idx=0): 3 | if 0 <= idx < len(my_list): 4 | del(my_list[idx]) 5 | return(my_list) 6 | -------------------------------------------------------------------------------- /0x04-python-more_data_structures/8-simple_delete.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python3 2 | def simple_delete(my_dict, key=""): 3 | if key in my_dict: 4 | del my_dict[key] 5 | return (my_dict) 6 | -------------------------------------------------------------------------------- /0x0D-SQL_introduction/5-full_table.sql: -------------------------------------------------------------------------------- 1 | -- script that prints the full description of the table first_table from the database hbtn_0c_0 in your MySQL server 2 | SHOW CREATE TABLE first_table 3 | -------------------------------------------------------------------------------- /0x12-javascript-warm_up/101-call_me_moby.js: -------------------------------------------------------------------------------- 1 | #!/usr/bin/node 2 | exports.callMeMoby = function (var1, callback) { 3 | for (let i = 0; i < var1; i++) { 4 | callback(var1); 5 | } 6 | }; 7 | -------------------------------------------------------------------------------- /0x13-javascript_objects_scopes_closures/101-data.js: -------------------------------------------------------------------------------- 1 | #!/usr/bin/node 2 | exports.dict = { 3 | 89: 1, 4 | 90: 2, 5 | 91: 1, 6 | 92: 3, 7 | 93: 1, 8 | 94: 2 9 | }; 10 | -------------------------------------------------------------------------------- /0x13-javascript_objects_scopes_closures/9-logme.js: -------------------------------------------------------------------------------- 1 | #!/usr/bin/node 2 | let count = 0; 3 | 4 | exports.logMe = function (item) { 5 | console.log(count + ': ' + item); 6 | count++; 7 | }; 8 | -------------------------------------------------------------------------------- /0x03-python-data_structures/6-print_matrix_integer.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python3 2 | def print_matrix_integer(matrix=[[]]): 3 | for i in matrix: 4 | print(' '.join('{:d}'.format(j)for j in i)) 5 | -------------------------------------------------------------------------------- /0x04-python-more_data_structures/1-search_replace.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python3 2 | def search_replace(my_list, search, replace): 3 | return (list(map(lambda x: replace if x is search else x, my_list))) 4 | -------------------------------------------------------------------------------- /0x0D-SQL_introduction/16-no_link.sql: -------------------------------------------------------------------------------- 1 | -- Script lists all records of the table second_table if name is not null 2 | SELECT score, name FROM second_table WHERE name IS NOT NULL ORDER BY score DESC; 3 | -------------------------------------------------------------------------------- /0x0E-SQL_more_queries/3-force_name.sql: -------------------------------------------------------------------------------- 1 | -- script that creates the table force_name on your MySQL server. 2 | CREATE TABLE 3 | IF NOT EXISTS force_name 4 | (id INT, name VARCHAR 5 | (256) NOT NULL); 6 | -------------------------------------------------------------------------------- /0x12-javascript-warm_up/12-object.js: -------------------------------------------------------------------------------- 1 | #!/usr/bin/node 2 | const myObject = { 3 | type: 'object', 4 | value: 12 5 | }; 6 | console.log(myObject); 7 | myObject.value = 89; 8 | console.log(myObject); 9 | -------------------------------------------------------------------------------- /0x13-javascript_objects_scopes_closures/10-converter.js: -------------------------------------------------------------------------------- 1 | #!/usr/bin/node 2 | 3 | exports.converter = function (base) { 4 | return function (n) { 5 | return n.toString(base); 6 | }; 7 | }; 8 | -------------------------------------------------------------------------------- /0x15-javascript-web_jquery/3-script.js: -------------------------------------------------------------------------------- 1 | // script that adds the class red to the HTML tag HEADER to red 2 | 3 | $('DIV#red_header').click(function () { 4 | $('header').addClass('red'); 5 | }); 6 | -------------------------------------------------------------------------------- /0x01-python-if_else_loops_functions/8-main.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python3 2 | uppercase = __import__('8-uppercase').uppercase 3 | 4 | uppercase("holberton") 5 | uppercase("Holberton Scholl 98 Battery street") 6 | -------------------------------------------------------------------------------- /0x02-python-import_modules/0-add.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python3 2 | if __name__ == "__main__": 3 | from add_0 import add 4 | a = 1 5 | b = 2 6 | print("{:d} + {:d} = {:d}".format(a, b, add(a, b))) 7 | -------------------------------------------------------------------------------- /0x03-python-data_structures/0-main.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python3 2 | print_list_integer = __import__('0-print_list_integer').print_list_integer 3 | 4 | my_list = [1, 2, 3, 4, 5] 5 | print_list_integer(my_list) 6 | -------------------------------------------------------------------------------- /0x0C-python-almost_a_circle/tests/test_square.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python3 2 | """Unit test class Square""" 3 | import unittest 4 | from models.square import Square 5 | import sys 6 | from io import StringIO 7 | -------------------------------------------------------------------------------- /0x0D-SQL_introduction/11-best_score.sql: -------------------------------------------------------------------------------- 1 | -- a script that lists all records with a score >= 10 in the table order by score 2 | SELECT score, name FROM second_table WHERE score >= 10 ORDER BY score DESC; 3 | -------------------------------------------------------------------------------- /0x0D-SQL_introduction/7-insert_value.sql: -------------------------------------------------------------------------------- 1 | -- script that inserts a new row in the table first_table (database hbtn_0c_0) in your MySQL server. 2 | INSERT INTO first_table VALUES (89, 'Holberton School'); 3 | -------------------------------------------------------------------------------- /0x15-javascript-web_jquery/100-script.js: -------------------------------------------------------------------------------- 1 | (() => { 2 | document.addEventListener('DOMContentLoaded', () => { 3 | document.querySelector('header').style.color = '#FF0000'; 4 | }, false); 5 | })(); 6 | -------------------------------------------------------------------------------- /0x0D-SQL_introduction/4-first_table.sql: -------------------------------------------------------------------------------- 1 | -- a script that creates a table called first_table in the current database in your MySQL server. 2 | CREATE TABLE IF NOT EXISTS first_table (id INT, name VARCHAR(256)); 3 | -------------------------------------------------------------------------------- /0x0E-SQL_more_queries/4-never_empty.sql: -------------------------------------------------------------------------------- 1 | --script that creates the table id_not_null on your MySQL server. 2 | 3 | CREATE TABLE 4 | IF NOT EXISTS id_not_null 5 | (id INT DEFAULT 1, name VARCHAR 6 | (256)); 7 | -------------------------------------------------------------------------------- /0x14-javascript-web_scraping/5-request_store.js: -------------------------------------------------------------------------------- 1 | #!/usr/bin/node 2 | const fs = require('fs'); 3 | const request = require('request'); 4 | request(process.argv[2]).pipe(fs.createWriteStream(process.argv[3])); 5 | -------------------------------------------------------------------------------- /0x15-javascript-web_jquery/4-script.js: -------------------------------------------------------------------------------- 1 | // script that toggles the class of the HTML tag HEADER to red 2 | 3 | $('DIV#toggle_header').click(function () { 4 | $('header').toggleClass('red green'); 5 | }); 6 | -------------------------------------------------------------------------------- /0x15-javascript-web_jquery/6-script.js: -------------------------------------------------------------------------------- 1 | // Javascript script that updates the text of the HTML tag HEADER 2 | 3 | $('DIV#update_header').click(function () { 4 | $('header').html('New Header!!!'); 5 | }); 6 | -------------------------------------------------------------------------------- /0x03-python-data_structures/2-replace_in_list.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python3 2 | def replace_in_list(my_list, idx, element): 3 | if 0 <= idx < len(my_list): 4 | my_list[idx] = element 5 | return(my_list) 6 | -------------------------------------------------------------------------------- /0x0C-python-almost_a_circle/tests/test_rectangle.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python3 2 | """Unit test class Rectangle""" 3 | import unittest 4 | import json 5 | import sys 6 | import os 7 | from models.rectangle import Rectangle 8 | -------------------------------------------------------------------------------- /0x0E-SQL_more_queries/5-unique_id.sql: -------------------------------------------------------------------------------- 1 | -- Script that creates the table unique_id on your MySQL server 2 | 3 | CREATE TABLE 4 | IF NOT EXISTS unique_id (id INT UNSIGNED DEFAULT 1, name VARCHAR(256), UNIQUE(id)); 5 | -------------------------------------------------------------------------------- /0x10-python-network_0/101-post_json.sh: -------------------------------------------------------------------------------- 1 | #!/bin/bash 2 | # Script sends a JSON POST request to a URL first argument, displays the body of response 3 | curl -sX POST -d "@$2" -H "Content-Type: application/json" "$1" 4 | -------------------------------------------------------------------------------- /0x15-javascript-web_jquery/0-script.js: -------------------------------------------------------------------------------- 1 | // Javascript script that updates the text color of the HTML tag HEADER to red 2 | 3 | const colorH = document.querySelector('header'); 4 | colorH.style.color = '#FF0000'; 5 | -------------------------------------------------------------------------------- /0x15-javascript-web_jquery/2-script.js: -------------------------------------------------------------------------------- 1 | // script that updates the text color of the HTML tag HEADER to red 2 | 3 | $('DIV#red_header').click(function () { 4 | $('header').css({ color: '#FF0000' }); 5 | }); 6 | -------------------------------------------------------------------------------- /0x02-python-import_modules/5-variable_load.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python3 2 | from variable_load_5 import a 3 | 4 | 5 | def find_var(): 6 | print(a) 7 | 8 | 9 | if __name__ == "__main__": 10 | find_var() 11 | -------------------------------------------------------------------------------- /0x05-python-exceptions/1-safe_print_integer.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python3 2 | def safe_print_integer(value): 3 | try: 4 | print("{:d}".format(value)) 5 | return True 6 | except: 7 | return False 8 | -------------------------------------------------------------------------------- /0x0D-SQL_introduction/15-groups.sql: -------------------------------------------------------------------------------- 1 | -- a script lists the number of records with the same score in the table second_table 2 | SELECT score, COUNT(score) AS number FROM second_table GROUP BY score ORDER BY score DESC; 3 | -------------------------------------------------------------------------------- /0x10-python-network_0/102-catch_me.sh: -------------------------------------------------------------------------------- 1 | #!/bin/bash 2 | # Script that makes a request to 0.0.0.0:5000/catch_me and get the response 3 | curl -sX PUT -L -d "user_id=98" -H "Origin:HolbertonSchool" "0.0.0.0:5000/catch_me" 4 | -------------------------------------------------------------------------------- /0x12-javascript-warm_up/3-value_argument.js: -------------------------------------------------------------------------------- 1 | #!/usr/bin/node 2 | const array = process.argv.slice(2); 3 | if (array[0] === undefined) { 4 | console.log('No argument'); 5 | } else { 6 | console.log(array[0]); 7 | } 8 | -------------------------------------------------------------------------------- /0x12-javascript-warm_up/6-multi_languages_loop.js: -------------------------------------------------------------------------------- 1 | #!/usr/bin/node 2 | const strings = ['C is fun', 'Python is cool', 'Javascript is amazing']; 3 | let s; 4 | for (s in strings) { 5 | console.log(strings[s]); 6 | } 7 | -------------------------------------------------------------------------------- /0x01-python-if_else_loops_functions/102-magic_calculation.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python3 2 | def magic_calculation(a, b, c): 3 | if a < b: 4 | return c 5 | if b < c: 6 | return a + b 7 | return a * b - c 8 | -------------------------------------------------------------------------------- /0x01-python-if_else_loops_functions/11-main.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python3 2 | pow = __import__('11-pow').pow 3 | 4 | print(pow(2, 2)) 5 | print(pow(98, 2)) 6 | print(pow(98, 0)) 7 | print(pow(100, -2)) 8 | print(pow(-4, 5)) 9 | -------------------------------------------------------------------------------- /0x03-python-data_structures/7-add_tuple.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python3 2 | def add_tuple(tuple_a=(), tuple_b=()): 3 | tuple_a += (0, 0) 4 | tuple_b += (0, 0) 5 | return(tuple_a[0] + tuple_b[0], tuple_a[1] + tuple_b[1]) 6 | -------------------------------------------------------------------------------- /0x04-python-more_data_structures/6-print_sorted_dictionary.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python3 2 | def print_sorted_dictionary(my_dict): 3 | for keys in sorted(my_dict.keys()): 4 | print('{}: {}'.format(keys, my_dict[keys])) 5 | -------------------------------------------------------------------------------- /0x0A-python-inheritance/5-base_geometry.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python3 2 | """ 3 | This is an empty BaseGeometry class. 4 | """ 5 | 6 | 7 | class BaseGeometry: 8 | ''' Class: BaseGeometry 9 | ''' 10 | pass 11 | -------------------------------------------------------------------------------- /0x01-python-if_else_loops_functions/__pycache__/7-islower.cpython-36.pyc: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/afinesami/holbertonschool-higher_level_programming/HEAD/0x01-python-if_else_loops_functions/__pycache__/7-islower.cpython-36.pyc -------------------------------------------------------------------------------- /0x04-python-more_data_structures/9-multiply_by_2.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python3 2 | def multiply_by_2(my_dict): 3 | tmp_dict = my_dict.copy() 4 | for x in tmp_dict.keys(): 5 | tmp_dict[x] *= 2 6 | return (tmp_dict) 7 | -------------------------------------------------------------------------------- /0x08-python-more_classes/0-rectangle.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python3 2 | """ 3 | This is a Rectangle class. 4 | """ 5 | 6 | 7 | class Rectangle: 8 | """ 9 | Create an empty Rectangle Object. 10 | """ 11 | pass 12 | -------------------------------------------------------------------------------- /0x0E-SQL_more_queries/0-privileges.sql: -------------------------------------------------------------------------------- 1 | -- Script that lists all privileges of the MySQL users user_0d_1 and user_0d_2 on your server (in localhost) 2 | SHOW GRANTS FOR user_0d_1@localhost; 3 | SHOW GRANTS FOR user_0d_2@localhost; 4 | -------------------------------------------------------------------------------- /#1-last_digit.py#: -------------------------------------------------------------------------------- 1 | #t = number % 10 last > 5: 2 | print("{:d} and is greater than 5".format(last)) 3 | elif last == 0: 4 | print("{:d} and is 0".format(last)) 5 | else: 6 | print("{:d} and is less than 6 and not 0".format(last)) -------------------------------------------------------------------------------- /0x01-python-if_else_loops_functions/__pycache__/8-uppercase.cpython-36.pyc: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/afinesami/holbertonschool-higher_level_programming/HEAD/0x01-python-if_else_loops_functions/__pycache__/8-uppercase.cpython-36.pyc -------------------------------------------------------------------------------- /0x03-python-data_structures/__pycache__/0-print_list_integer.cpython-36.pyc: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/afinesami/holbertonschool-higher_level_programming/HEAD/0x03-python-data_structures/__pycache__/0-print_list_integer.cpython-36.pyc -------------------------------------------------------------------------------- /0x04-python-more_data_structures/0-square_matrix_simple.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python3 2 | def square_matrix_simple(matrix=[]): 3 | tmp = [] 4 | for x in matrix: 5 | tmp.append(list(map(lambda x: x**2, x))) 6 | return (tmp) 7 | -------------------------------------------------------------------------------- /0x02-python-import_modules/README.md: -------------------------------------------------------------------------------- 1 | Python - import & modules 2 | Import a simple function from a simple file 3 | My first toolbox! 4 | How to make a script dynamic! 5 | Infinite addition 6 | Who are you? 7 | Everything can be imported -------------------------------------------------------------------------------- /0x06-python-classes/1-square.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python3 2 | 3 | 4 | class Square: 5 | """ 6 | class Square with private instance attribute size 7 | """ 8 | def __init__(self, size): 9 | self.__size = size 10 | -------------------------------------------------------------------------------- /0x13-javascript_objects_scopes_closures/1-rectangle.js: -------------------------------------------------------------------------------- 1 | #!/usr/bin/node 2 | 3 | class Rectangle { 4 | constructor (w, h) { 5 | this.width = w; 6 | this.height = h; 7 | } 8 | } 9 | 10 | module.exports = Rectangle; 11 | -------------------------------------------------------------------------------- /0x01-python-if_else_loops_functions/3-print_alphabt.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python3 2 | for i in range(ord('a'), ord('z') + 1): 3 | if chr(i) == 'e' or chr(i) == 'q': 4 | continue 5 | else: 6 | print("{:s}".format(chr(i)), end="") 7 | -------------------------------------------------------------------------------- /0x09-python-everything_is_object/100-magic_string.py~: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python3 2 | def magic_string(): 3 | magic_string.counter = getattr(magic_string, "counter", 0) + 1 4 | return ", ".join(["Holberton" for i in range(magic_string.counter)]) 5 | -------------------------------------------------------------------------------- /0x0A-python-inheritance/0-lookup.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python3 2 | ''' function that returns the list 3 | ''' 4 | 5 | 6 | def lookup(obj): 7 | ''' function: lookup() 8 | Returns a list object 9 | ''' 10 | return dir(obj) 11 | -------------------------------------------------------------------------------- /0x15-javascript-web_jquery/9-script.js: -------------------------------------------------------------------------------- 1 | $(() => { 2 | $.get('https://fourtonfish.com/hellosalut/?lang=fr', (data, textStatus) => { 3 | if (textStatus === 'success') { 4 | $('div#hello').text(data.hello); 5 | } 6 | }); 7 | }); 8 | -------------------------------------------------------------------------------- /0x03-python-data_structures/3-print_reversed_list_integer.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python3 2 | def print_reversed_list_integer(my_list=[]): 3 | if my_list is None: 4 | return 5 | for i in reversed(my_list): 6 | print('{:d}'.format(i)) 7 | -------------------------------------------------------------------------------- /0x03-python-data_structures/8-multiple_returns.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python3 2 | def multiple_returns(sentence): 3 | length = len(sentence) 4 | first_char = sentence[0] if length > 0 else "None" 5 | tup = length, first_char 6 | return(tup) 7 | -------------------------------------------------------------------------------- /0x0E-SQL_more_queries/1-create_user.sql: -------------------------------------------------------------------------------- 1 | -- script that creates the MySQL server user user_0d_1 2 | 3 | CREATE USER IF NOT EXISTS 'user_0d_1'@'localhost' IDENTIFIED BY 'user_0d_1_pwd'; 4 | GRANT ALL PRIVILEGES ON * . * TO 'user_0d_1'@'localhost'; 5 | -------------------------------------------------------------------------------- /0x12-javascript-warm_up/1-multi_languages.js: -------------------------------------------------------------------------------- 1 | #!/usr/bin/node 2 | const myVar0 = 'C is fun'; 3 | const myVar1 = 'Python is cool'; 4 | const myVar2 = 'Javascript is amazing'; 5 | console.log(myVar0); 6 | console.log(myVar1); 7 | console.log(myVar2); 8 | -------------------------------------------------------------------------------- /0x09-python-everything_is_object/100-magic_string.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python3 2 | 3 | 4 | def magic_string(): 5 | magic_string.counter = getattr(magic_string, "counter", 0) + 1 6 | return ", ".join(["Holberton" for i in range(magic_string.counter)]) 7 | -------------------------------------------------------------------------------- /0x0A-python-inheritance/101-add_attribute.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python3 2 | def add_attribute(*args): 3 | if "main" in str(type(args[0])): 4 | setattr(args[0], args[1], args[2]) 5 | else: 6 | raise TypeError("can't add new attribute") 7 | -------------------------------------------------------------------------------- /0x07-python-test_driven_development/2-main.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python3 2 | matrix_divided = __import__('2-matrix_divided').matrix_divided 3 | 4 | matrix = [ 5 | [1, 2, 3], 6 | [4, 5, 6] 7 | ] 8 | print(matrix_divided(matrix, 3)) 9 | print(matrix) 10 | -------------------------------------------------------------------------------- /0x0E-SQL_more_queries/9-cities_by_state_join.sql: -------------------------------------------------------------------------------- 1 | -- Script that lists all cities contained in the database hbtn_0d_usa. 2 | 3 | SELECT cities.id, cities.name, states.name FROM cities INNER JOIN states ON states.id = cities.state_id ORDER BY cities.id ASC; 4 | -------------------------------------------------------------------------------- /0x01-python-if_else_loops_functions/6-print_comb3.py~: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python3 2 | for i in range(0, 9): 3 | for j in range(i + 1, 10): 4 | if i == 8 and j == 9: 5 | print("{:d}{:d}".format(i, j)) 6 | else: 7 | print("{:d}{:d}".format(i, j), end=", ") 8 | -------------------------------------------------------------------------------- /0x03-python-data_structures/4-new_in_list.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python3 2 | def new_in_list(my_list, idx, element): 3 | tmp_list = my_list[:] 4 | if 0 <= idx < len(my_list): 5 | tmp_list[idx] = element 6 | return(tmp_list) 7 | return(my_list) 8 | -------------------------------------------------------------------------------- /0x15-javascript-web_jquery/7-script.js: -------------------------------------------------------------------------------- 1 | // Javascript script that fetches and replaces the name 2 | // Must use the jQuery API 3 | 4 | $.getJSON('https://swapi.co/api/people/5/?format=json', function (data) { 5 | $('DIV#character').html(data['name']); 6 | }); 7 | -------------------------------------------------------------------------------- /0x00-python-hello_world/8-concat_edges.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python3 2 | str = "Python is an interpreted, interactive, object-oriented programming\ 3 | language that combines remarkable power with very clear syntax" 4 | str = str[39:67] + str[107:112] + str[:6] 5 | print(str) 6 | -------------------------------------------------------------------------------- /0x01-python-if_else_loops_functions/8-uppercase.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python3 2 | def uppercase(str): 3 | for i in str: 4 | if ord(i) >= ord('a') and ord(i) <= ord('z'): 5 | i = chr(ord(i) - 32) 6 | print("{:s}".format(i), end="") 7 | print() 8 | -------------------------------------------------------------------------------- /0x03-python-data_structures/9-max_integer.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python3 2 | def max_integer(my_list=[]): 3 | if len(my_list) == 0: 4 | return ("None") 5 | x = my_list[0] 6 | for i in my_list: 7 | if i > x: 8 | x = i 9 | return (x) 10 | -------------------------------------------------------------------------------- /0x0A-python-inheritance/2-is_same_class.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python3 2 | 3 | 4 | def is_same_class(obj, a_class): 5 | """'''function: is_same_class 6 | obj: an object 7 | a_class: a class 8 | Returns: Bool 9 | """ 10 | return type(obj) == a_class 11 | -------------------------------------------------------------------------------- /0x12-javascript-warm_up/2-arguments.js: -------------------------------------------------------------------------------- 1 | #!/usr/bin/node 2 | if (process.argv.slice(2).length > 1) { 3 | console.log('Arguments found'); 4 | } else if (process.argv.slice(2).length === 1) { 5 | console.log('Argument found'); 6 | } else { 7 | console.log('No argument'); 8 | } 9 | -------------------------------------------------------------------------------- /0x0E-SQL_more_queries/8-cities_of_california_subquery.sql: -------------------------------------------------------------------------------- 1 | -- Script that lists all the cities of California that can be found in the database hbtn_0d_usa. 2 | 3 | SELECT id, name FROM cities WHERE state_id = (SELECT id FROM states WHERE name='California') ORDER BY cities.id ASC; 4 | -------------------------------------------------------------------------------- /0x13-javascript_objects_scopes_closures/2-rectangle.js: -------------------------------------------------------------------------------- 1 | #!/usr/bin/node 2 | 3 | class Rectangle { 4 | constructor (w, h) { 5 | if (w > 0 && h > 0) { 6 | this.width = w; 7 | this.height = h; 8 | } 9 | } 10 | } 11 | 12 | module.exports = Rectangle; 13 | -------------------------------------------------------------------------------- /0x13-javascript_objects_scopes_closures/7-occurrences.js: -------------------------------------------------------------------------------- 1 | #!/usr/bin/node 2 | // function that returns the number of occurrences in a list 3 | 4 | exports.nbOccurences = function (list, searchElement) { 5 | return list.filter((value) => (value === searchElement)).length; 6 | }; 7 | -------------------------------------------------------------------------------- /0x00-python-hello_world/README.md: -------------------------------------------------------------------------------- 1 | 0x00. Python - Hello, World 2 | Run Python file 3 | Run inline 4 | Hello, print 5 | Print integer 6 | Print float 7 | Print string 8 | Play with strings 9 | Copy - Cut - Paste 10 | Create a new sentence 11 | Easter Egg 12 | Linked list cycle 13 | -------------------------------------------------------------------------------- /0x01-python-if_else_loops_functions/6-print_comb3.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python3 2 | for i in range(0, 9): 3 | for j in range(i + 1, 10): 4 | if i == 8 and j == 9: 5 | print("{:d}{:d}".format(i, j)) 6 | else: 7 | print("{:d}{:d}".format(i, j), end=", ") 8 | -------------------------------------------------------------------------------- /0x02-python-import_modules/add_0.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python3 2 | def add(a, b): 3 | """My addition function 4 | 5 | Args: 6 | a: first integer 7 | b: second integer 8 | 9 | Returns: 10 | The return value. a + b 11 | """ 12 | return (a + b) 13 | -------------------------------------------------------------------------------- /0x12-javascript-warm_up/5-to_integer.js: -------------------------------------------------------------------------------- 1 | #!/usr/bin/node 2 | const args = process.argv; 3 | let result; 4 | result = parseInt(args[2]); 5 | if (isNaN(result)) { 6 | result = 'Not a number'; 7 | } else { 8 | result = ('My number: ' + result); 9 | } 10 | console.log(result); 11 | -------------------------------------------------------------------------------- /0x03-python-data_structures/5-no_c.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python3 2 | def no_c(my_string): 3 | new_str = "" 4 | for i in my_string: 5 | if i is not 'c' and i is not 'C': 6 | new_str += i 7 | return (new_str) 8 | # return my_string.translate({ord(c): None for c in "cC"}) 9 | -------------------------------------------------------------------------------- /0x0A-python-inheritance/100-my_int.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python3 2 | class MyInt(int): 3 | def __init__(self, value): 4 | self.num = value 5 | 6 | def __eq__(self, other): 7 | return self.num != other 8 | 9 | def __ne__(self, other): 10 | return self.num == other 11 | -------------------------------------------------------------------------------- /0x11-python-network_1/1-hbtn_header.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python3 2 | # Python script that takes in a URL sends a request to the URL 3 | import sys 4 | import urllib.request 5 | 6 | if __name__ == "__main__": 7 | with urllib.request.urlopen(sys.argv[1]) as res: 8 | print(res.info()['X-Request-Id']) 9 | -------------------------------------------------------------------------------- /0x04-python-more_data_structures/10-best_score.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python3 2 | def best_score(my_dict): 3 | if my_dict is None or my_dict == {}: 4 | return None 5 | biggest = max(my_dict.values()) 6 | for key, value in my_dict.items(): 7 | if value is biggest: 8 | return key 9 | -------------------------------------------------------------------------------- /0x0B-python-input_output/4-append_write.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python3 2 | """ 3 | function that appends a string at the end of a text file (UTF8) and returns the number of characters added 4 | """ 5 | 6 | def append_write(filename="", text=""): 7 | with open(filename, 'a') as f: 8 | return f.write(text) 9 | -------------------------------------------------------------------------------- /0x01-python-if_else_loops_functions/100-print_tebahpla.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python3 2 | i = 122 3 | while i >= 97: 4 | flag = 0 5 | if i % 2 != 0: 6 | i = i - 32 7 | flag = 1 8 | print("{:s}".format(chr(i)), end="") 9 | if flag == 1: 10 | i = i + 32 11 | i = i - 1 12 | -------------------------------------------------------------------------------- /0x02-python-import_modules/4-hidden_discovery.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python3 2 | import hidden_4 3 | 4 | 5 | def discovr(): 6 | name = dir(hidden_4) 7 | for i in name: 8 | if i[:2] != '__': 9 | print("{:s}".format(i)) 10 | 11 | 12 | if __name__ == "__main__": 13 | discovr() 14 | -------------------------------------------------------------------------------- /0x0B-python-input_output/10-class_to_json.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python3 2 | '''function that returns the dictionary description with simple data structure 3 | ''' 4 | 5 | 6 | def class_to_json(obj): 7 | '''module class_to_json 8 | returns builds a dictionary 9 | ''' 10 | return obj.__dict__ 11 | -------------------------------------------------------------------------------- /0x13-javascript_objects_scopes_closures/8-esrever.js: -------------------------------------------------------------------------------- 1 | #!/usr/bin/node 2 | // function that returns the reversed version of a list 3 | 4 | exports.esrever = function (list) { 5 | 6 | let rlist = []; 7 | while (list.length > 0) { 8 | rlist.push(list.pop()); 9 | } 10 | return rlist; 11 | }; 12 | -------------------------------------------------------------------------------- /0x00-python-hello_world/7-edges.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python3 2 | word = "Holberton" 3 | word_first_3 = word[:3] 4 | word_last_2 = word[-2:] 5 | middle_word = word[1:-1] 6 | print("First 3 letters: {}".format(word_first_3)) 7 | print("Last 2 letters: {}".format(word_last_2)) 8 | print("Middle word: {}".format(middle_word)) 9 | -------------------------------------------------------------------------------- /0x03-python-data_structures/13-is_palindrome.c: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include "lists.h" 4 | 5 | /** 6 | * main - check the code for Holberton School students. 7 | * 8 | * Return: Always 0. 9 | */ 10 | int main(void) 11 | { 12 | listint_t *head; 13 | 14 | return (0); 15 | } 16 | -------------------------------------------------------------------------------- /0x07-python-test_driven_development/102-python.c: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include 4 | 5 | /** 6 | * print_python_string - Prints info about python str 7 | * @p: pointer to PyObject 8 | * Return: Nothing 9 | **/ 10 | void print_python_string(PyObject *p) 11 | { 12 | } 13 | -------------------------------------------------------------------------------- /0x0A-python-inheritance/1-my_list.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python3 2 | ''' Module: 1-my_list 3 | ''' 4 | 5 | 6 | class MyList(list): 7 | ''' Represents a MyList 8 | ''' 9 | 10 | def print_sorted(self): 11 | ''' 12 | prints the list, but sorted 13 | ''' 14 | print(sorted(self)) 15 | -------------------------------------------------------------------------------- /0x0E-SQL_more_queries/10-genre_id_by_show.sql: -------------------------------------------------------------------------------- 1 | -- Import the database dump from hbtn_0d_tvshows to your MySQL server 2 | 3 | SELECT tv_shows.title, tv_show_genres.genre_id 4 | FROM tv_shows 5 | INNER JOIN tv_show_genres 6 | ON tv_shows.id=tv_show_genres.show_id 7 | ORDER BY tv_shows.title, tv_show_genres.genre_id; 8 | -------------------------------------------------------------------------------- /0x04-python-more_data_structures/100-weight_average.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python3 2 | def weight_average(my_list=[]): 3 | if my_list == [] or my_list is None: 4 | return (0) 5 | res = 0 6 | res2 = 0 7 | for x, y in my_list: 8 | res += x * y 9 | res2 += y 10 | return (res / res2) 11 | -------------------------------------------------------------------------------- /0x0A-python-inheritance/3-is_kind_of_class.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python3 2 | ''' module: 2-is_same_class 3 | ''' 4 | 5 | 6 | def is_kind_of_class(obj, a_class): 7 | '''function: is_kind_of_class 8 | obj: an object 9 | a_class: a class 10 | Returns: Bool 11 | ''' 12 | return isinstance(obj, a_class) 13 | -------------------------------------------------------------------------------- /0x0E-SQL_more_queries/11-genre_id_all_shows.sql: -------------------------------------------------------------------------------- 1 | -- script that lists all shows contained in the database hbtn_0d_tvshows 2 | 3 | SELECT tv_shows.title, tv_show_genres.genre_id 4 | FROM tv_shows 5 | LEFT JOIN tv_show_genres 6 | ON tv_show_genres.show_id = tv_shows.id 7 | ORDER BY tv_shows.title ASC, tv_show_genres.genre_id ASC; 8 | -------------------------------------------------------------------------------- /0x0E-SQL_more_queries/2-create_read_user.sql: -------------------------------------------------------------------------------- 1 | -- Script that creates the database hbtn_0d_2 and the user user_0d_2 2 | CREATE DATABASE IF NOT EXISTS hbtn_0d_2; 3 | CREATE USER IF NOT EXISTS 'user_0d_2'@'localhost' IDENTIFIED BY 'user_0d_2_pwd'; 4 | GRANT SELECT ON hbtn_0d_2 . * TO 'user_0d_2'@'localhost'; 5 | FLUSH PRIVILEGES; 6 | -------------------------------------------------------------------------------- /0x03-python-data_structures/10-divisible_by_2.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python3 2 | def divisible_by_2(my_list=[]): 3 | boolist = my_list[:] 4 | for count, i in enumerate(my_list): 5 | if i % 2 == 0: 6 | boolist[count] = True 7 | else: 8 | boolist[count] = False 9 | return(boolist) 10 | -------------------------------------------------------------------------------- /0x01-python-if_else_loops_functions/0-positive_or_negative.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python3 2 | import random 3 | number = random.randint(-10, 10) 4 | if number > 0: 5 | print("{:d} is positive".format(number)) 6 | elif number == 0: 7 | print("{:d} is zero".format(number)) 8 | else: 9 | print("{:d} is negative".format(number)) 10 | -------------------------------------------------------------------------------- /0x01-python-if_else_loops_functions/9-print_last_digit.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python3 2 | def print_last_digit(number): 3 | exe = 0 4 | if number < 0: 5 | number *= -1 6 | exe = 1 7 | last = number % 10 8 | if exe == 1: 9 | number *= -1 10 | print("{:d}".format(last), end="") 11 | return last 12 | -------------------------------------------------------------------------------- /0x02-python-import_modules/102-magic_calculation.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python3 2 | def magic_calculation(a, b): 3 | from magic_calculation_102 import add, sub 4 | if a < b: 5 | c = add(a, b) 6 | for n in range(4, 6): 7 | c = add(c, n) 8 | return c 9 | else: 10 | return sub(a, b) 11 | -------------------------------------------------------------------------------- /0x04-python-more_data_structures/102-complex_delete.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python3 2 | def complex_delete(my_dict, value): 3 | targets = [] 4 | for key, key_value in my_dict.items(): 5 | if key_value is value: 6 | targets.append(key) 7 | for x in targets: 8 | del my_dict[x] 9 | return(my_dict) 10 | -------------------------------------------------------------------------------- /0x0B-python-input_output/5-to_json_string.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python3 2 | ''' function that returns the JSON representation of an object (string) 3 | ''' 4 | 5 | import json 6 | 7 | 8 | def to_json_string(my_obj): 9 | ''' module to_json_strin 10 | returns JSON representation 11 | ''' 12 | return json.dumps(my_obj) 13 | -------------------------------------------------------------------------------- /0x13-javascript_objects_scopes_closures/100-map.js: -------------------------------------------------------------------------------- 1 | #!/usr/bin/node 2 | // script that imports an array and computes a new array 3 | 4 | const array = require('./100-data').list; 5 | 6 | console.log(array); 7 | let cont = 0; 8 | const map1 = array.map(function (x) { 9 | return (x * cont++); 10 | }); 11 | console.log(map1); 12 | -------------------------------------------------------------------------------- /0x13-javascript_objects_scopes_closures/102-concat.js: -------------------------------------------------------------------------------- 1 | #!/usr/bin/node 2 | // script that concats 2 files. 3 | 4 | const args = process.argv.slice(2); 5 | const fs = require('fs'); 6 | const first = fs.readFileSync('./' + args[0]); 7 | const second = fs.readFileSync('./' + args[1]); 8 | fs.writeFileSync('./' + args[2], first + second); 9 | -------------------------------------------------------------------------------- /0x05-python-exceptions/101-safe_function.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python3 2 | import sys 3 | 4 | 5 | def safe_function(fct, *args): 6 | try: 7 | return fct(*args) 8 | except (ZeroDivisionError, ValueError, TypeError, IndexError) as error: 9 | print("Exception: {}".format(error), file=sys.stderr) 10 | return None 11 | -------------------------------------------------------------------------------- /0x05-python-exceptions/3-safe_print_division.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python3 2 | def safe_print_division(a, b): 3 | try: 4 | result = a / b 5 | print("Inside result: {:.1f}".format(result)) 6 | except: 7 | result = None 8 | print("Inside result: {}".format(result)) 9 | finally: 10 | return result 11 | -------------------------------------------------------------------------------- /0x12-javascript-warm_up/7-multi_c.js: -------------------------------------------------------------------------------- 1 | #!/usr/bin/node 2 | const x = parseInt(process.argv[2]); 3 | let result; 4 | if (isNaN(x)) { 5 | result = 'Missing number of occurrences'; 6 | console.log(result); 7 | } else { 8 | result = 'C is fun'; 9 | let i; 10 | for (i = 0; i < x; i++) { 11 | console.log(result); 12 | } 13 | } 14 | -------------------------------------------------------------------------------- /0x12-javascript-warm_up/9-add.js: -------------------------------------------------------------------------------- 1 | #!/usr/bin/node 2 | const args = process.argv; 3 | let A = parseInt(args[2]); 4 | let B = parseInt(args[3]); 5 | if (typeof A === 'number' && typeof B === 'number') { 6 | console.log(add(A, B)); 7 | } else { 8 | console.log('NaN'); 9 | } 10 | 11 | function add (a, b) { 12 | return (a + b); 13 | } 14 | -------------------------------------------------------------------------------- /0x14-javascript-web_scraping/1-writeme.js: -------------------------------------------------------------------------------- 1 | #!/usr/bin/node 2 | // script that writes a string to a file 3 | 4 | const fs = require('fs'); 5 | const file = process.argv[2]; 6 | const write_ = process.argv[3]; 7 | 8 | fs.writeFile(file, write_, 'utf8', function (error) { 9 | if (error) { 10 | console.log(error); 11 | } 12 | }); 13 | -------------------------------------------------------------------------------- /0x0B-python-input_output/0-read_file.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python3 2 | """ 3 | function that reads a text file 4 | """ 5 | 6 | 7 | def read_file(filename=""): 8 | """reads a text file (UTF8) and prints it to stdout 9 | Returns none 10 | """ 11 | with open(filename, "r", encoding="utf-8") as f: 12 | print(f.read(), end="") 13 | -------------------------------------------------------------------------------- /0x0B-python-input_output/3-write_file.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python3 2 | """ 3 | function that writes a string to a text file (UTF8) and returns the number of characters written 4 | """ 5 | 6 | 7 | def write_file(filename="", text=""): 8 | """ module write_file 9 | """ 10 | with open(filename, 'w') as f: 11 | return f.write(text) 12 | -------------------------------------------------------------------------------- /0x0B-python-input_output/6-from_json_string.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python3 2 | ''' function that returns an object (Python data structure) represented by a JSON string 3 | ''' 4 | 5 | import json 6 | 7 | 8 | def from_json_string(my_str): 9 | ''' module from_json_string 10 | returns Python objects 11 | ''' 12 | return json.loads(my_str) 13 | -------------------------------------------------------------------------------- /0x14-javascript-web_scraping/0-readme.js: -------------------------------------------------------------------------------- 1 | #!/usr/bin/node 2 | // script that reads and prints the content of a file 3 | 4 | const file = process.argv[2]; 5 | const fs = require('fs'); 6 | 7 | fs.readFile(file, 'utf8', (error, data) => { 8 | if (error) { 9 | console.log(error); 10 | } else { 11 | console.log(data); 12 | } 13 | }); 14 | -------------------------------------------------------------------------------- /0x12-javascript-warm_up/8-square.js: -------------------------------------------------------------------------------- 1 | #!/usr/bin/node 2 | const x = parseInt(process.argv[2]); 3 | if (isNaN(x)) { 4 | console.log('Missing size'); 5 | } else { 6 | let i, j, string; 7 | for (i = 0; i < x; i++) { 8 | string = ''; 9 | for (j = 0; j < x; j++) { 10 | string += 'X'; 11 | } 12 | console.log(string); 13 | } 14 | } 15 | -------------------------------------------------------------------------------- /0x13-javascript_objects_scopes_closures/5-square.js: -------------------------------------------------------------------------------- 1 | #!/usr/bin/node 2 | // class Square that defines a square and inherits from Rectangle 3 | 4 | const Rectangle = require('./4-rectangle'); 5 | 6 | const Square = class Square extends Rectangle { 7 | constructor (size) { 8 | super(size, size); 9 | } 10 | }; 11 | 12 | module.exports = Square; 13 | -------------------------------------------------------------------------------- /0x07-python-test_driven_development/100-matrix_mul.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python3 2 | """ 3 | This is the "matrix_mul" module. 4 | Module functions: matrix_mul(m_a, m_b). 5 | """ 6 | 7 | 8 | def matrix_mul(m_a, m_b): 9 | """ 10 | print_square: prints a square with the character #. 11 | size (int): multiplies 2 matrices 12 | """ 13 | return matrix 14 | -------------------------------------------------------------------------------- /0x0E-SQL_more_queries/12-no_genre.sql: -------------------------------------------------------------------------------- 1 | -- script that lists all shows contained in hbtn_0d_tvshows without a genre linked 2 | 3 | SELECT tv_shows.title, tv_show_genres.genre_id 4 | FROM tv_shows 5 | LEFT JOIN tv_show_genres 6 | ON tv_show_genres.show_id = tv_shows.id 7 | WHERE tv_show_genres.genre_id IS NULL 8 | ORDER BY tv_shows.title ASC, tv_show_genres.genre_id ASC; 9 | -------------------------------------------------------------------------------- /0x15-javascript-web_jquery/8-script.js: -------------------------------------------------------------------------------- 1 | $(() => { 2 | $.get('https://swapi-api.hbtn.io/api/films/?format=json', (data, textStatus) => { 3 | if (textStatus === 'success') { 4 | const films = data.results; 5 | films.forEach(film => { 6 | $('#list_movies').append('
  • ' + film.title + '
  • '); 7 | }); 8 | } 9 | }); 10 | }); 11 | -------------------------------------------------------------------------------- /0x0E-SQL_more_queries/13-count_shows_by_genre.sql: -------------------------------------------------------------------------------- 1 | -- script that lists all genres from hbtn_0d_tvshows and displays the number of shows linked to each 2 | 3 | SELECT tv_genres.name AS genre, COUNT(tv_show_genres.genre_id) AS number_of_shows 4 | FROM tv_genres INNER JOIN tv_show_genres ON tv_genres.id=tv_show_genres.genre_id 5 | GROUP BY genre 6 | ORDER BY number_of_shows DESC; 7 | -------------------------------------------------------------------------------- /0x0E-SQL_more_queries/14-my_genres.sql: -------------------------------------------------------------------------------- 1 | -- script that uses the hbtn_0d_tvshows database to lists all genres of the show Dexter 2 | 3 | SELECT tv_genres.name 4 | FROM tv_genres 5 | INNER JOIN tv_show_genres ON tv_genres.id = tv_show_genres.genre_id 6 | INNER JOIN tv_shows ON tv_shows.id = tv_show_genres.show_id 7 | WHERE tv_shows.title = "Dexter" 8 | ORDER BY tv_genres.name ASC; 9 | -------------------------------------------------------------------------------- /0x11-python-network_1/5-hbtn_header.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python3 2 | """ 3 | Python script that takes in a URL, sends a request to the URL and displays 4 | the value of the variable X-Request-Id in the response header 5 | """ 6 | import requests 7 | from sys import argv 8 | 9 | if __name__ == '__main__': 10 | r = requests.get(argv[1]) 11 | print(r.headers.get('X-Request-Id')) 12 | -------------------------------------------------------------------------------- /0x12-javascript-warm_up/10-factorial.js: -------------------------------------------------------------------------------- 1 | #!/usr/bin/node 2 | const array = process.argv.slice(2); 3 | const number = parseInt(array[0]); 4 | if (isNaN(array[0])) { 5 | console.log(1); 6 | } else { 7 | console.log(factorial(number)); 8 | } 9 | function factorial (n) { 10 | if (n === 0) { 11 | return 1; 12 | } else { 13 | return n * factorial(n - 1); 14 | } 15 | } 16 | -------------------------------------------------------------------------------- /0x07-python-test_driven_development/101-lazy_matrix_mul.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python3 2 | """ 3 | This is the "lazy_matrix_mul" module. 4 | The lazy_matrix_mul matrix multiplication using numpy.dot 5 | """ 6 | 7 | 8 | import numpy as np 9 | 10 | 11 | def lazy_matrix_mul(m_a, m_b): 12 | """ 13 | Multiplies two Matrix 14 | Return: matrix 15 | """ 16 | return matrix 17 | -------------------------------------------------------------------------------- /0x0A-python-inheritance/4-inherits_from.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python3 2 | ''' module: 4-inherits_from 3 | ''' 4 | 5 | 6 | def inherits_from(obj, a_class): 7 | '''the object is an instance of a class that inherited (directly or indirectly) 8 | obj: an object 9 | a_class: a class 10 | returns None 11 | ''' 12 | return type(obj) != a_class and isinstance(obj, a_class) 13 | -------------------------------------------------------------------------------- /0x0B-python-input_output/8-load_from_json_file.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python3 2 | import json 3 | """ 4 | function that creates an Object from a "JSON file". 5 | """ 6 | 7 | 8 | def load_from_json_file(filename): 9 | '''module load_from_json_file 10 | returns corresponding Python object 11 | ''' 12 | with open(filename, 'r') as f: 13 | return json.loads(f.read()) 14 | -------------------------------------------------------------------------------- /0x0E-SQL_more_queries/15-comedy_only.sql: -------------------------------------------------------------------------------- 1 | -- script that lists all Comedy shows in the database hbtn_0d_tvshows 2 | 3 | SELECT tv_shows.title 4 | FROM tv_shows 5 | INNER JOIN tv_show_genres 6 | ON tv_shows.id = tv_show_genres.show_id 7 | INNER JOIN tv_genres 8 | ON tv_show_genres.genre_id = tv_genres.id 9 | WHERE tv_genres.name = "Comedy" 10 | ORDER BY tv_shows.title; 11 | -------------------------------------------------------------------------------- /0x0E-SQL_more_queries/16-shows_by_genre.sql: -------------------------------------------------------------------------------- 1 | -- script that lists all shows, and all genres linked to that show, from the database hbtn_0d_tvshows 2 | 3 | SELECT tv_shows.title, tv_genres.name 4 | FROM tv_shows 5 | LEFT JOIN tv_show_genres ON tv_shows.id = tv_show_genres.show_id 6 | LEFT JOIN tv_genres ON tv_genres.id = tv_show_genres.genre_id 7 | ORDER BY tv_shows.title ASC, tv_genres.name ASC; 8 | -------------------------------------------------------------------------------- /0x01-python-if_else_loops_functions/12-fizzbuzz.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python3 2 | def fizzbuzz(): 3 | for i in range(1, 101): 4 | if i % 15 == 0: 5 | print("FizzBuzz ", end="") 6 | elif i % 5 == 0: 7 | print("Buzz ", end="") 8 | elif i % 3 == 0: 9 | print("Fizz ", end="") 10 | else: 11 | print("{:d} ".format(i), end="") 12 | -------------------------------------------------------------------------------- /0x0B-python-input_output/12-student.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python3 2 | ''' class Student that defines a student 3 | ''' 4 | 5 | 6 | class Student: 7 | '''module class student 8 | ''' 9 | 10 | def __init__(self, first_name, last_name, age): 11 | '''method __init__ 12 | ''' 13 | self.first_name = first_name 14 | self.last_name = last_name 15 | self.age = age 16 | -------------------------------------------------------------------------------- /0x11-python-network_1/4-hbtn_status.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python3 2 | """ 3 | fetches https://intranet.hbtn.io/status 4 | """ 5 | import requests 6 | 7 | if __name__ == '__main__': 8 | url = "https://intranet.hbtn.io/status" 9 | r = requests.get(url) 10 | text = r.text 11 | print("Body response:") 12 | print("\t- type: {}".format(type(text))) 13 | print("\t- content: {}".format(text)) 14 | -------------------------------------------------------------------------------- /0x02-python-import_modules/1-calculation.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python3 2 | if __name__ == "__main__": 3 | from calculator_1 import add, sub, mul, div 4 | a = 10 5 | b = 5 6 | print("{:d} + {:d} = {:d}".format(a, b, add(a, b))) 7 | print("{:d} - {:d} = {:d}".format(a, b, sub(a, b))) 8 | print("{:d} * {:d} = {:d}".format(a, b, mul(a, b))) 9 | print("{:d} / {:d} = {:d}".format(a, b, div(a, b))) 10 | -------------------------------------------------------------------------------- /0x14-javascript-web_scraping/2-statuscode.js: -------------------------------------------------------------------------------- 1 | #!/usr/bin/node 2 | // Script that display the status code of a GET request 3 | 4 | const args = process.argv; 5 | let request = require('request'); 6 | request(args[2], function (error, response, body) { 7 | if (error) { 8 | console.log('error:', error); // Print the error if one occurred 9 | } else console.log('code:', response && response.statusCode); 10 | }); 11 | -------------------------------------------------------------------------------- /0x0E-SQL_more_queries/7-cities.sql: -------------------------------------------------------------------------------- 1 | -- Script that creates the database hbtn_0d_usa and the table cities (in the database hbtn_0d_usa) on your MySQL server. 2 | 3 | CREATE DATABASE 4 | IF NOT EXISTS hbtn_0d_usa; 5 | USE hbtn_0d_usa; 6 | CREATE TABLE 7 | IF NOT EXISTS cities (id INT NOT NULL AUTO_INCREMENT, state_id INT NOT NULL, name VARCHAR(256) NOT NULL, UNIQUE(id), PRIMARY KEY(id), FOREIGN KEY(state_id) REFERENCES states(id)); 8 | -------------------------------------------------------------------------------- /0x0B-python-input_output/7-save_to_json_file.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python3 2 | ''' function that writes an Object to a text file, using a JSON representation 3 | ''' 4 | import json 5 | 6 | 7 | def save_to_json_file(my_obj, filename): 8 | ''' module save_to_json_file 9 | accepts Python object and sends JSON representation to file 10 | ''' 11 | with open(filename, 'w') as f: 12 | f.write(json.dumps(my_obj)) 13 | -------------------------------------------------------------------------------- /0x11-python-network_1/6-post_email.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python3 2 | """ 3 | takes in a URL and an email address, sends a POST request to the passed URL 4 | with the email as a parameter, and finally displays the body of the response 5 | """ 6 | import requests 7 | from sys import argv 8 | 9 | if __name__ == '__main__': 10 | payload = {'email': argv[2]} 11 | r = requests.post(argv[1], data=payload) 12 | print(r.text) 13 | -------------------------------------------------------------------------------- /0x11-python-network_1/7-error_code.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python3 2 | """ 3 | Python Script takes in a URL, sends a request to the URL 4 | & displays the body of the response 5 | """ 6 | import requests 7 | from sys import argv 8 | 9 | if __name__ == '__main__': 10 | r = requests.get(argv[1]) 11 | status = r.status_code 12 | print(r.text) if status < 400 else print( 13 | "Error code: {}".format(r.status_code)) 14 | -------------------------------------------------------------------------------- /0x0A-python-inheritance/7-base_geometry.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python3 2 | class BaseGeometry: 3 | def area(self): 4 | raise Exception("area() is not implemented") 5 | 6 | def integer_validator(self, name, value): 7 | if type(value) is not int: 8 | raise TypeError("{} must be an integer".format(name)) 9 | if value <= 0: 10 | raise ValueError("{} must be greater than 0". format(name)) 11 | -------------------------------------------------------------------------------- /0x01-python-if_else_loops_functions/7-main.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python3 2 | islower = __import__('7-islower').islower 3 | 4 | print("a is {}".format("lower" if islower("a") else "upper")) 5 | print("H is {}".format("lower" if islower("H") else "upper")) 6 | print("A is {}".format("lower" if islower("A") else "upper")) 7 | print("3 is {}".format("lower" if islower("3") else "upper")) 8 | print("g is {}".format("lower" if islower("g") else "upper")) 9 | -------------------------------------------------------------------------------- /0x0A-python-inheritance/10-square.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python3 2 | """ 3 | more class base 4 | """ 5 | 6 | 7 | Rectangle = __import__('9-rectangle').Rectangle 8 | 9 | 10 | """ 11 | Square class 12 | """ 13 | 14 | 15 | class Square(Rectangle): 16 | """ Square Class """ 17 | def __init__(self, size): 18 | """ instantiation with size """ 19 | self.__size = size 20 | super().__init__(self.__size, self.__size) 21 | -------------------------------------------------------------------------------- /0x12-javascript-warm_up/11-second_biggest.js: -------------------------------------------------------------------------------- 1 | #!/usr/bin/node 2 | const array = process.argv.slice(2); 3 | let array2 = []; 4 | function sortNumber (a, b) { 5 | return a - b; 6 | } 7 | if (array[0] === undefined) { 8 | console.log(0); 9 | } else if (array.length === 1) { 10 | console.log(0); 11 | } else { 12 | array2 = array.sort(sortNumber); 13 | array2.pop(); 14 | console.log(parseInt(array2[array2.length - 1])); 15 | } 16 | -------------------------------------------------------------------------------- /0x13-javascript_objects_scopes_closures/101-sorted.js: -------------------------------------------------------------------------------- 1 | #!/usr/bin/node 2 | // Script imports a dictionary of occurrences by user id 3 | // and computes a dictionary of user ids by occurrence. 4 | 5 | const { dict } = require('./101-data.js'); 6 | const Dictn = {}; 7 | for (const N in dict) { 8 | if (Dictn[dict[N]] === undefined) { 9 | Dictn[dict[N]] = []; 10 | } 11 | Dictn[dict[N]].push(N); 12 | } 13 | console.log(Dictn); 14 | -------------------------------------------------------------------------------- /0x05-python-exceptions/0-safe_print_list.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python3 2 | def safe_print_list(my_list=[], x=0): 3 | index = 0 4 | while True: 5 | try: 6 | if index < x: 7 | print(my_list[index], end='') 8 | index += 1 9 | else: 10 | print() 11 | return index 12 | except IndexError: 13 | print() 14 | return index 15 | -------------------------------------------------------------------------------- /0x0D-SQL_introduction/9-full_creation.sql: -------------------------------------------------------------------------------- 1 | -- script that creates a table second_table in the database hbtn_0c_0 in your MySQL server and add multiples rows. 2 | CREATE TABLE IF NOT EXISTS second_table (id INT, name VARCHAR(256), score INT); 3 | INSERT INTO second_table VALUES (1, 'John', 10); 4 | INSERT INTO second_table VALUES (2, 'Alex', 3); 5 | INSERT INTO second_table VALUES (3, 'Bob', 14); 6 | INSERT INTO second_table VALUES (4, 'George', 8); 7 | -------------------------------------------------------------------------------- /0x10-python-network_0/6-peak.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python3 2 | """ 3 | function that finds a peak in a list of unsorted integers 4 | """ 5 | 6 | 7 | def find_peak(list_of_integers): 8 | """ 9 | This function will find a peak. 10 | """ 11 | if list_of_integers is None: 12 | return None 13 | if len(list_of_integers) == 0: 14 | return None 15 | 16 | return find_peak(list_of_integers[midpoint:]) 17 | -------------------------------------------------------------------------------- /0x14-javascript-web_scraping/3-starwars_title.js: -------------------------------------------------------------------------------- 1 | #!/usr/bin/node 2 | // prints the title of a Star Wars movie where the episode num matches given int 3 | 4 | const request = require('request'); 5 | const url = 'https://swapi-api.hbtn.io/api/films/' + process.argv[2]; 6 | request(url, function (error, response, body) { 7 | if (error) { 8 | console.error(error); 9 | } else { 10 | console.log(JSON.parse(body).title); 11 | } 12 | }); 13 | -------------------------------------------------------------------------------- /0x02-python-import_modules/3-infinite_add.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python3 2 | def add_arg(argv): 3 | n = len(argv) - 1 4 | if n == 0: 5 | print("{:d}".format(n)) 6 | return 7 | else: 8 | i = 1 9 | add = 0 10 | while i <= n: 11 | add += int(argv[i]) 12 | i += 1 13 | print("{:d}".format(add)) 14 | 15 | if __name__ == "__main__": 16 | import sys 17 | add_arg(sys.argv) 18 | -------------------------------------------------------------------------------- /0x0B-python-input_output/1-number_of_lines.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python3 2 | ''' function that returns the number of lines of a text file 3 | ''' 4 | 5 | 6 | def number_of_lines(filename=""): 7 | ''' function: number_of_lines 8 | ''' 9 | if filename == "" or type(filename) != str: 10 | return 0 11 | counter = 0 12 | with open(filename, 'r') as f: 13 | for line in f: 14 | counter += 1 15 | return counter 16 | -------------------------------------------------------------------------------- /0x0F-python-object_relational_mapping/model_city.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python3 2 | 3 | 4 | from sqlalchemy import Column, Integer, String, ForeingnKey 5 | from model_state import Base, State 6 | 7 | 8 | class City(Base): 9 | ''' 10 | class city 11 | ''' 12 | __tablename__ = 'cities' 13 | id = Column(Integer, primary_key=True) 14 | name = Column(String(128), nullable=False) 15 | state_id = Column(Integer, ForeignKey('states.id')) 16 | -------------------------------------------------------------------------------- /0x05-python-exceptions/100-safe_print_integer_err.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python3 2 | import sys 3 | 4 | 5 | def safe_print_integer_err(value): 6 | try: 7 | print("{:d}".format(value)) 8 | return True 9 | except ValueError as err: 10 | print("Exception: {}".format(err), file=sys.stderr) 11 | return False 12 | except TypeError as err: 13 | print("Exception: {}".format(err), file=sys.stderr) 14 | return False 15 | -------------------------------------------------------------------------------- /0x06-python-classes/2-square.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python3 2 | 3 | 4 | class Square: 5 | '''Class Square object intialized with size 6 | ''' 7 | pass 8 | 9 | def __init__(self, size=0): 10 | '''init method of class Square 11 | ''' 12 | if type(size) != int: 13 | raise TypeError("size must be an integer") 14 | if size < 0: 15 | raise ValueError("size must be >= 0") 16 | self.__size = size 17 | -------------------------------------------------------------------------------- /0x0E-SQL_more_queries/101-not_a_comedy.sql: -------------------------------------------------------------------------------- 1 | -- script that lists all shows without the genre Comedy in the database hbtn_0d_tvshows 2 | 3 | SELECT tv_shows.title 4 | FROM tv_shows 5 | WHERE tv_shows.id NOT IN 6 | (SELECT tv_shows.id 7 | FROM tv_shows 8 | INNER JOIN tv_show_genres 9 | ON tv_shows.id = tv_show_genres.show_id 10 | INNER JOIN tv_genres 11 | ON tv_show_genres.genre_id = tv_genres.id 12 | WHERE tv_genres.name = "Comedy") 13 | ORDER BY tv_shows.title; 14 | -------------------------------------------------------------------------------- /0x0E-SQL_more_queries/100-not_my_genres.sql: -------------------------------------------------------------------------------- 1 | -- script that uses the hbtn_0d_tvshows database to list all genres not linked to the show Dexter 2 | 3 | SELECT tv_genres.name 4 | FROM tv_genres 5 | WHERE tv_genres.name NOT IN ( 6 | SELECT tv_genres.name 7 | FROM tv_genres 8 | INNER JOIN tv_show_genres ON tv_genres.id = tv_show_genres.genre_id 9 | INNER JOIN tv_shows ON tv_shows.id = tv_show_genres.show_id 10 | WHERE tv_shows.title = "Dexter") 11 | ORDER BY tv_genres.name ASC; 12 | -------------------------------------------------------------------------------- /0x11-python-network_1/2-post_email.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python3 2 | # Take in a URL and email, send POST request 3 | 4 | import sys 5 | import urllib.request 6 | import urllib.parse 7 | 8 | if __name__ == "__main__": 9 | values = {'email': sys.argv[2]} 10 | data = urllib.parse.urlencode(values) 11 | data = data.encode('utf-8') 12 | req = urllib.request.Request(sys.argv[1], data) 13 | with urllib.request.urlopen(req) as res: 14 | print(res.read().decode('utf-8')) 15 | -------------------------------------------------------------------------------- /0x11-python-network_1/3-error_code.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python3 2 | # Take in a URL, send a request to URL, and dispaly body 3 | 4 | import sys 5 | import urllib.request 6 | import urllib.error 7 | 8 | if __name__ == "__main__": 9 | req = urllib.request.Request(sys.argv[1]) 10 | try: 11 | with urllib.request.urlopen(req) as res: 12 | print(res.read().decode('utf-8')) 13 | except urllib.error.URLError as e: 14 | print("Error code: {}".format(e.code)) 15 | -------------------------------------------------------------------------------- /0x11-python-network_1/10-my_github.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python3 2 | """ 3 | Python script takes your Github credentials (username and password) 4 | and uses the Github API to display your id 5 | """ 6 | import requests 7 | from requests.auth import HTTPBasicAuth 8 | from sys import argv 9 | 10 | if __name__ == '__main__': 11 | url = 'https://api.github.com/users/{}'.format(argv[1]) 12 | r = requests.get(url, 13 | auth=HTTPBasicAuth(argv[1], argv[2])) 14 | print(r.json().get('id')) 15 | -------------------------------------------------------------------------------- /0x11-python-network_1/0-hbtn_status.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python3 2 | # Python script that fetches https://intranet.hbtn.io/status 3 | import urllib.request 4 | 5 | if __name__ == "__main__": 6 | with urllib.request.urlopen('https://intranet.hbtn.io/status') as res: 7 | content = res.read() 8 | print("Body response:") 9 | print("\t- type: {}".format(type(content))) 10 | print("\t- content: {}".format(content)) 11 | print("\t- utf8 content: {}".format(content.decode('utf-8'))) 12 | -------------------------------------------------------------------------------- /0x0B-python-input_output/11-student.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python3 2 | ''' a class Student that defines a student 3 | ''' 4 | 5 | 6 | class Student: 7 | '''module class student 8 | ''' 9 | 10 | def __init__(self, first_name, last_name, age): 11 | '''method __init__ 12 | ''' 13 | self.first_name = first_name 14 | self.last_name = last_name 15 | self.age = age 16 | 17 | def to_json(self): 18 | '''method to_json 19 | ''' 20 | return self.__dict__ 21 | -------------------------------------------------------------------------------- /0x05-python-exceptions/2-safe_print_list_integers.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python3 2 | def safe_print_list_integers(my_list=[], x=0): 3 | 4 | index = printed_ints = 0 5 | while True: 6 | try: 7 | if index < x: 8 | print("{:d}".format(my_list[index]), end='') 9 | index += 1 10 | printed_ints += 1 11 | else: 12 | print() 13 | return printed_ints 14 | except (ValueError, TypeError): 15 | index += 1 16 | -------------------------------------------------------------------------------- /0x11-python-network_1/100-github_commits.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python3 2 | """ 3 | Python script that takes 2 arguments in order to solve this challenge 4 | """ 5 | import requests 6 | from sys import argv 7 | 8 | if __name__ == '__main__': 9 | url = "https://api.github.com/repos/{}/{}/commits".format(argv[2], argv[1]) 10 | r = requests.get(url) 11 | commits = r.json() 12 | for commit in commits[:10]: 13 | print(commit.get('sha'), end=': ') 14 | print(commit.get('commit').get('author').get('name')) 15 | -------------------------------------------------------------------------------- /0x06-python-classes/3-square.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python3 2 | 3 | 4 | class Square: 5 | """ 6 | Class Square 7 | """ 8 | def __init__(self, size=0): 9 | if type(size) is not int: 10 | raise TypeError("size must be an integer") 11 | elif size < 0: 12 | raise ValueError("size must be >= 0") 13 | else: 14 | self.__size = size 15 | 16 | """ 17 | Return area of Square object 18 | """ 19 | def area(self): 20 | return (self.__size * self.__size) 21 | -------------------------------------------------------------------------------- /0x0A-python-inheritance/11-square.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python3 2 | """ 3 | more class base 4 | """ 5 | 6 | 7 | Rectangle = __import__('9-rectangle').Rectangle 8 | 9 | 10 | """ 11 | Square class 12 | """ 13 | 14 | 15 | class Square(Rectangle): 16 | """ Square Class """ 17 | def __init__(self, size): 18 | """ size init""" 19 | self.__size = size 20 | super().__init__(self.__size, self.__size) 21 | 22 | def __str__(self): 23 | return ("[Square] " + str(self.__size) + "/" + str(self.__size)) 24 | -------------------------------------------------------------------------------- /0x15-javascript-web_jquery/8-main.html: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | Holberton School 5 | 6 | 7 | 8 |
    9 | Star Wars movies 10 |
    11 |
    12 |
      13 |
    14 |
    15 |
    16 | Holberton School - 2017 17 |
    18 | 19 | 20 | 21 | -------------------------------------------------------------------------------- /0x12-javascript-warm_up/4-concat.js: -------------------------------------------------------------------------------- 1 | #!/usr/bin/node 2 | const array = process.argv.slice(2); 3 | if (array[0] === undefined && array[1] === undefined) { 4 | console.log('undefined is undefined'); 5 | } else if (array[0] !== undefined && array[1] !== undefined) { 6 | console.log(array[0] + ' is ' + array[1]); 7 | } else if (array[0] !== undefined && array[1] === undefined) { 8 | console.log(array[0] + ' is undefined'); 9 | } else if (array[0] === undefined && array[1] !== undefined) { 10 | console.log('undefined is ' + array[1]); 11 | } 12 | -------------------------------------------------------------------------------- /0x14-javascript-web_scraping/100-starwars_characters.js: -------------------------------------------------------------------------------- 1 | #!/usr/bin/node 2 | const request = require('request'); 3 | const film = process.argv[2]; 4 | const url = `https://swapi-api.hbtn.io/api/films/${film}`; 5 | request(url, (err, res, body) => { 6 | if (!err) { 7 | const characters = JSON.parse(body).characters; 8 | characters.forEach((character) => { 9 | request(character, function (err, res, body) { 10 | if (!err) { 11 | console.log(JSON.parse(body).name); 12 | } 13 | }); 14 | }); 15 | } 16 | }); 17 | -------------------------------------------------------------------------------- /0x02-python-import_modules/2-args.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python3 2 | def print_arg(argv): 3 | n = len(argv) - 1 4 | if n == 0: 5 | print("{:d} argument.".format(n)) 6 | return 7 | else: 8 | if n == 1: 9 | print("{:d} argument:".format(n)) 10 | else: 11 | print("{:d} arguments:".format(n)) 12 | i = 1 13 | while i <= n: 14 | print("{:d}: {:s}".format(i, argv[i])) 15 | i += 1 16 | 17 | if __name__ == "__main__": 18 | import sys 19 | print_arg(sys.argv) 20 | -------------------------------------------------------------------------------- /0x0C-python-almost_a_circle/tests/rectangle_unitest.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python3 2 | """Module to test the function rectangle""" 3 | import unittest 4 | import rectangle 5 | 6 | 7 | class TestRectangle(unittest.TestCase): 8 | 9 | def test_rectangle_output(self): 10 | """Function to test the output the function rectangle""" 11 | 12 | self.assertAlmostEqual(rectangle(,) 13 | 14 | def test_rectangle_input(self): 15 | """Function to test the input the function rectangle""" 16 | 17 | self.assertRaises(TypeError, rectangle, ) 18 | -------------------------------------------------------------------------------- /0x01-python-if_else_loops_functions/1-last_digit.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python3 2 | import random 3 | number = random.randint(-10000, 10000) 4 | exe = 0 5 | if number < 0: 6 | number *= -1 7 | exe = 1 8 | lastd = number % 10 9 | if exe == 1: 10 | number *= -1 11 | lastd *= -1 12 | print("Last digit of {:d} is ".format(number), end="") 13 | if lastd > 5: 14 | print("{:d} and is greater than 5".format(lastd)) 15 | elif lastd == 0: 16 | print("{:d} and is 0".format(lastd)) 17 | else: 18 | print("{:d} and is less than 6 and not 0".format(lastd)) 19 | -------------------------------------------------------------------------------- /0x06-python-classes/103-magic_class.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python3 2 | import math 3 | 4 | 5 | class MagicClass: 6 | ''' Magic Class reverses given Class to bytecode''' 7 | 8 | def __init__(self, radius=0): 9 | self.__radius = 0 10 | if type(radius) is not int and type(radius) is not float: 11 | raise TypeError('radius must be a number') 12 | self.__radius = radius 13 | 14 | def area(self): 15 | return self.__radius**2 * math.pi 16 | 17 | def circumference(self): 18 | return 2 * math.pi * self.__radius 19 | -------------------------------------------------------------------------------- /0x07-python-test_driven_development/0-add_integer.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python3 2 | ''' 3 | add_integer module 4 | ''' 5 | 6 | 7 | def add_integer(a, b): 8 | """ 9 | Return sum of a and b. 10 | """ 11 | if type(a) == float: 12 | a = int(a) 13 | if type(b) == float: 14 | b = int(b) 15 | 16 | if not isinstance(a, int) or isinstance(a, bool): 17 | raise TypeError("a must be an integer") 18 | if not isinstance(b, int) or isinstance(b, bool): 19 | raise TypeError("b must be an integer") 20 | 21 | return ( a + b ) 22 | -------------------------------------------------------------------------------- /0x0E-SQL_more_queries/102-rating_shows.sql: -------------------------------------------------------------------------------- 1 | -- script that lists all shows from hbtn_0d_tvshows_rate by their rating. 2 | -- Each record should display: tv_shows.title - rating sum 3 | -- Results must be sorted in descending order by the rating 4 | -- You can use only one SELECT statement 5 | -- The database name will be passed as an argument of the mysql command 6 | 7 | 8 | SELECT tv_shows.title, SUM(tv_show_ratings.rate) AS rating 9 | FROM tv_shows 10 | INNER JOIN tv_show_ratings 11 | ON tv_shows.id = tv_show_ratings.show_id 12 | GROUP BY tv_shows.id 13 | ORDER BY rating DESC; 14 | -------------------------------------------------------------------------------- /0x0F-python-object_relational_mapping/0-select_states.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python3 2 | 3 | 4 | import MySQLdb 5 | from sys import argv 6 | 7 | ''' 8 | a script that lists all states 9 | from the database 10 | ''' 11 | if __name__ == "__main__": 12 | con = MySQLdb.connect( 13 | host="localhost", port=3306, user=argv[1], 14 | password=argv[2], database=argv[3]) 15 | cursor = con.cursor() 16 | cursor.execute("SELECT * FROM states ORDER BY id ASC") 17 | db = cursor.fetchall() 18 | for i in db: 19 | print(i) 20 | cursor.close() 21 | db.close() 22 | 23 | -------------------------------------------------------------------------------- /0x07-python-test_driven_development/4-print_square.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python3 2 | """ 3 | This is the print_square module. 4 | The print_square module provides a simple function print_square() 5 | that prints a square with #. 6 | """ 7 | 8 | 9 | def print_square(size): 10 | """Print square with #. 11 | """ 12 | if not isinstance(size, int): 13 | raise TypeError("size must be an integer") 14 | if size < 0: 15 | raise ValueError("size must be >= 0") 16 | for i in range(size): 17 | for j in range(size): 18 | print("#", end="") 19 | print() 20 | -------------------------------------------------------------------------------- /0x06-python-classes/4-square.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python3 2 | 3 | 4 | class Square: 5 | '''Initialize Class Square 6 | ''' 7 | 8 | def __init__(self, size=0): 9 | self.size = size 10 | 11 | @property 12 | def size(self): 13 | return self.__size 14 | 15 | @size.setter 16 | def size(self, size): 17 | if type(size) != int: 18 | raise TypeError("size must be an integer") 19 | if size < 0: 20 | raise ValueError("size must be >= 0") 21 | self.__size = size 22 | 23 | def area(self): 24 | return (self.size * self.size) 25 | -------------------------------------------------------------------------------- /0x0F-python-object_relational_mapping/1-filter_states.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python3 2 | 3 | 4 | import MySQLdb 5 | from sys import argv 6 | 7 | ''' 8 | lists all states with starting name with N 9 | from the database hbtn_0e_0_usa 10 | ''' 11 | if __name__ == "__main__": 12 | con = MySQLdb.connect( 13 | host="localhost", port=3306, user=argv[1], 14 | password=argv[2], database=argv[3]) 15 | cursor = con.cursor() 16 | cursor.execute( 17 | "SELECT * FROM states WHERE name LIKE BINARY 'N%'ORDER BY id ASC") 18 | db = cursor.fetchall() 19 | for i in db: 20 | print(i) 21 | -------------------------------------------------------------------------------- /0x03-python-data_structures/lists.h: -------------------------------------------------------------------------------- 1 | #ifndef LISTS_H 2 | #define LISTS_H 3 | 4 | /** 5 | * struct listint_s - singly linked list 6 | * @n: integer 7 | * @next: points to the next node 8 | * 9 | * Description: singly linked list node structure 10 | * for Holberton project 11 | */ 12 | typedef struct listint_s 13 | { 14 | int n; 15 | struct listint_s *next; 16 | } listint_t; 17 | 18 | size_t print_listint(const listint_t *h); 19 | listint_t *add_nodeint_end(listint_t **head, const int n); 20 | void free_listint(listint_t *head); 21 | 22 | int is_palindrome(listint_t **head); 23 | 24 | #endif /* LISTS_H */ 25 | -------------------------------------------------------------------------------- /0x05-python-exceptions/103-python.c: -------------------------------------------------------------------------------- 1 | #include 2 | 3 | /** 4 | * print_python_bytes - print some basic info about Python bytes objects 5 | * @p: python object 6 | * Return: nothing 7 | **/ 8 | void print_python_bytes(PyObject *p) 9 | { 10 | } 11 | /** 12 | * print_python_float - print Python float 13 | * @p: python float 14 | * Return: nothing 15 | **/ 16 | void print_python_float(PyObject *p) 17 | { 18 | } 19 | /** 20 | * print_python_list - print some basic info about Python lists 21 | * @p: python object 22 | * Return: nothing 23 | **/ 24 | void print_python_list(PyObject *p) 25 | { 26 | } 27 | -------------------------------------------------------------------------------- /0x0B-python-input_output/100-append_after.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python3 2 | """ 3 | function that inserts a line of text to a file, after each line containing a specific string 4 | """ 5 | 6 | 7 | def append_after(filename="", search_string="", new_string=""): 8 | '''module Search and update 9 | ''' 10 | with open(filename, 'r+') as f: 11 | lines = f.readlines() 12 | i = 0 13 | for line in lines: 14 | if line.find(search_string) is not -1: 15 | lines.insert(i + 1, new_string) 16 | i += 1 17 | f.seek(0) 18 | f.write("".join(lines)) 19 | -------------------------------------------------------------------------------- /0x0B-python-input_output/9-add_item.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python3 2 | ''' script that adds all arguments to a Python list, and then save them to a file 3 | ''' 4 | import json 5 | import sys 6 | 7 | save_to_json_file = __import__('7-save_to_json_file').save_to_json_file 8 | load_from_json_file = __import__('8-load_from_json_file').load_from_json_file 9 | 10 | filename = "add_item.json" 11 | try: 12 | py_list = load_from_json_file(filename) 13 | except FileNotFoundError: 14 | py_list = [] 15 | finally: 16 | for el in sys.argv[1:]: 17 | py_list.append(str(el)) 18 | save_to_json_file(py_list, filename) 19 | -------------------------------------------------------------------------------- /0x0F-python-object_relational_mapping/3-my_safe_filter_states.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python3 2 | 3 | 4 | import MySQLdb 5 | from sys import argv 6 | 7 | ''' 8 | script that lists all states from the database 9 | ''' 10 | if __name__ == "__main__": 11 | cont = MySQLdb.connect( 12 | host="localhost", port=3306, user=argv[1], 13 | password=argv[2], database=argv[3]) 14 | cursor = cont.cursor() 15 | cursor.execute( 16 | "SELECT * FROM states WHERE name LIKE %s ORDER BY id ASC", 17 | (argv[4],) 18 | ) 19 | db = cursor.fetchall() 20 | for i in db: 21 | print(i) 22 | -------------------------------------------------------------------------------- /0x13-javascript_objects_scopes_closures/3-rectangle.js: -------------------------------------------------------------------------------- 1 | #!/usr/bin/node 2 | // Script class Rectangle that defines a rectangle 3 | 4 | const Rectangle = class Rectangle { 5 | constructor (w, h) { 6 | if (w > 0 && h > 0) { 7 | this.width = w; 8 | this.height = h; 9 | } 10 | } 11 | 12 | print () { 13 | let prints = ''; 14 | for (let cont1 = 0; cont1 < this.height; cont1++) { 15 | for (let cont = 0; cont < this.width; cont++) { 16 | prints = prints + 'X'; 17 | } 18 | console.log(prints); 19 | prints = ''; 20 | } 21 | } 22 | }; 23 | 24 | module.exports = Rectangle; 25 | -------------------------------------------------------------------------------- /0x08-python-more_classes/101-nqueens.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python3 2 | import sys 3 | ''' 4 | column first element, row second element 5 | ''' 6 | def reject(board): 7 | for col_A in board: 8 | for col_B in board: 9 | if not col_A is col_B: 10 | if col_A[0] == col_B[0]: 11 | return True 12 | if col_A[1] == col_B[1]: 13 | return True 14 | if col_A[1] - col_A[0] == col_B[1] - col_B[0]: 15 | return True 16 | if col_A[0] + col_A[1] == col_B[0] + col_B[1]: 17 | return True 18 | return False 19 | -------------------------------------------------------------------------------- /0x0E-SQL_more_queries/6-states.sql: -------------------------------------------------------------------------------- 1 | -- script that creates the database hbtn_0d_usa and the table states (in the database hbtn_0d_usa) on your MySQL server 2 | -- states description: 3 | -- id INT unique, auto generated, can’t be null and is a primary key 4 | -- name VARCHAR(256) can’t be null 5 | -- If the database hbtn_0d_usa already exists, your script should not fail 6 | -- If the table states already exists, your script should not fail 7 | 8 | CREATE DATABASE 9 | IF NOT EXISTS hbtn_0d_usa; 10 | USE hbtn_0d_usa; 11 | CREATE TABLE 12 | IFNOT EXISTS states (id INT NOT NULL AUTO_INCREMENT, name VARCHAR(256) NOT NULL, UNIQUE(id), PRIMARY KEY(id)); 13 | -------------------------------------------------------------------------------- /0x13-javascript_objects_scopes_closures/6-square.js: -------------------------------------------------------------------------------- 1 | #!/usr/bin/node 2 | // class Square that defines a square and inherits from Square 3 | 4 | const Square_ = require('./5-square'); 5 | 6 | const Square = class Square extends Square_ { 7 | charPrint (c) { 8 | if (c) { 9 | let prints = ''; 10 | for (let cont = 0; cont < this.height; cont++) { 11 | for (let cont = 0; cont < this.height; cont++) { 12 | prints = prints + c; 13 | } 14 | console.log(prints); 15 | prints = ''; 16 | } 17 | } else { 18 | super.print(); 19 | } 20 | } 21 | }; 22 | 23 | module.exports = Square; 24 | -------------------------------------------------------------------------------- /0x0B-python-input_output/2-read_lines.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python3 2 | ''' function that reads n lines of a text file (UTF8) and prints it to stdout 3 | ''' 4 | 5 | 6 | def read_lines(filename="", nb_lines=0): 7 | ''' function: read_lines 8 | ''' 9 | if filename == "" or type(filename) != str: 10 | return 11 | if type(nb_lines) != int: 12 | return 13 | counter = 0 14 | with open(filename, "r") as f: 15 | for line in f: 16 | counter += 1 17 | if nb_lines <= 0 or (counter <= nb_lines and nb_lines > 0): 18 | print(line, end='') 19 | else: 20 | break 21 | -------------------------------------------------------------------------------- /0x0F-python-object_relational_mapping/2-my_filter_states.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python3 2 | 3 | 4 | import MySQLdb 5 | from sys import argv 6 | 7 | ''' 8 | Script that lists all states from the database 9 | ''' 10 | if __name__ == "__main__": 11 | cont = MySQLdb.connect( 12 | host="localhost", port=3306, user=argv[1], 13 | password=argv[2], database=argv[3]) 14 | cursor = cont.cursor() 15 | cursor.execute( 16 | "SELECT * FROM states WHERE name LIKE" 17 | " '{:s}' ORDER BY id ASC".format(argv[4])) 18 | db = cursor.fetchall() 19 | for i in db: 20 | if i[1] == argv[4]: 21 | print(i) 22 | -------------------------------------------------------------------------------- /0x06-python-classes/6-square.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python3 2 | 3 | 4 | class Square: 5 | '''Inisialize Class Square 6 | ''' 7 | 8 | def __init__(self, size=0, position=(0, 0)): 9 | self.size = size 10 | self.position = position 11 | 12 | @property 13 | def size(self): 14 | return self.__size 15 | 16 | @size.setter 17 | def size(self, size): 18 | if type(size) != int: 19 | raise TypeError("size must be an integer") 20 | if size < 0: 21 | raise ValueError("size must be >= 0") 22 | self.__size = size 23 | 24 | def area(self): 25 | return (self.size * self.size) 26 | -------------------------------------------------------------------------------- /0x0A-python-inheritance/8-rectangle.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python3 2 | class BaseGeometry: 3 | def area(self): 4 | raise Exception("area() is not implemented") 5 | 6 | def integer_validator(self, name, value): 7 | if type(value) is not int: 8 | raise TypeError("{} must be an integer".format(name)) 9 | if value <= 0: 10 | raise ValueError("{} must be greater than 0". format(name)) 11 | 12 | 13 | class Rectangle(BaseGeometry): 14 | def __init__(self, width, height): 15 | super().integer_validator("width", width) 16 | super().integer_validator("height", height) 17 | self.__width = width 18 | self.__height = height 19 | -------------------------------------------------------------------------------- /0x03-python-data_structures/100-print_python_list_info.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python3 2 | import ctypes 3 | 4 | lib = ctypes.CDLL('./libPyList.so') 5 | lib.print_python_list_info.argtypes = [ctypes.py_object] 6 | l = ['hello', 'World'] 7 | 8 | lib.print_python_list_info(l) 9 | 10 | del l[1] 11 | 12 | lib.print_python_list_info(l) 13 | 14 | l = l + [4, 5, 6.0, (9, 8), [9, 8, 1024], "Holberton"] 15 | 16 | lib.print_python_list_info(l) 17 | 18 | l = [] 19 | 20 | lib.print_python_list_info(l) 21 | 22 | l.append(0) 23 | 24 | lib.print_python_list_info(l) 25 | 26 | l.append(1) 27 | l.append(2) 28 | l.append(3) 29 | l.append(4) 30 | 31 | lib.print_python_list_info(l) 32 | 33 | l.pop() 34 | 35 | lib.print_python_list_info(l) 36 | -------------------------------------------------------------------------------- /0x0F-python-object_relational_mapping/11-model_state_insert.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python3 2 | """ 3 | All states via SQLAlchemy 4 | """ 5 | from sys import argv 6 | from model_state import Base, State 7 | from sqlalchemy import (create_engine) 8 | from sqlalchemy.orm import Session 9 | 10 | if __name__ == "__main__": 11 | engine = create_engine('mysql+mysqldb://{}:{}@localhost/{}'. 12 | format(argv[1], argv[2], argv[3]), 13 | pool_pre_ping=True) 14 | Base.metadata.create_all(engine) 15 | 16 | session = Session(engine) 17 | new_obj = State(name='Louisiana') 18 | session.add(new_obj) 19 | session.commit() 20 | print(new_obj.id) 21 | session.close() 22 | -------------------------------------------------------------------------------- /0x0F-python-object_relational_mapping/4-cities_by_state.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python3 2 | """ 3 | lists all cities from the database hbtn_0e_4_usa 4 | """ 5 | if __name__ == "__main__": 6 | 7 | import MySQLdb 8 | from sys import argv 9 | 10 | conect = MySQLdb.connect(host="localhost", port=3306, user=argv[1], 11 | passwd=argv[2], db=argv[3], charset="utf8") 12 | cursor = conect.cursor() 13 | cursor.execute("""SELECT cities.id, cities.name, states.name 14 | FROM cities 15 | LEFT JOIN states ON cities.state_id = states.id 16 | ORDER BY cities.id ASC""") 17 | query_rows = cursor.fetchall() 18 | for row in query_rows: 19 | print(row) 20 | cursor.close() 21 | conect.close() 22 | -------------------------------------------------------------------------------- /0x14-javascript-web_scraping/101-starwars_characters.js: -------------------------------------------------------------------------------- 1 | #!/usr/bin/node 2 | const request = require('request'); 3 | const url = 'https://swapi-api.hbtn.io/api/films/' + process.argv[2]; 4 | 5 | function printCharacters (characters, idx) { 6 | request(characters[idx], (err, res, body) => { 7 | if (err) { 8 | console.log(err); 9 | } else { 10 | console.log(JSON.parse(body).name); 11 | if (idx + 1 < characters.length) { 12 | printCharacters(characters, idx + 1); 13 | } 14 | } 15 | }); 16 | } 17 | 18 | request(url, (err, res, body) => { 19 | if (err) { 20 | console.log(err); 21 | } else { 22 | const characters = JSON.parse(body).characters; 23 | printCharacters(characters, 0); 24 | } 25 | }); 26 | -------------------------------------------------------------------------------- /0x05-python-exceptions/4-list_division.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python3 2 | def list_division(my_list_1, my_list_2, list_length): 3 | 4 | new_list = [] 5 | index = 0 6 | if list_length <= 0: 7 | print("out of range") 8 | return new_list 9 | while index < list_length: 10 | try: 11 | new_list.append(my_list_1[index] / my_list_2[index]) 12 | except ZeroDivisionError: 13 | print("division by 0") 14 | new_list.append(0) 15 | except TypeError: 16 | print("wrong type") 17 | new_list.append(0) 18 | except IndexError: 19 | print("out of range") 20 | new_list.append(0) 21 | finally: 22 | index += 1 23 | return new_list 24 | -------------------------------------------------------------------------------- /0x0F-python-object_relational_mapping/13-model_state_delete_a.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python3 2 | """ 3 | All states via SQLAlchemy 4 | """ 5 | from sys import argv 6 | from model_state import Base, State 7 | from sqlalchemy import (create_engine) 8 | from sqlalchemy.orm import Session 9 | 10 | if __name__ == "__main__": 11 | engine = create_engine('mysql+mysqldb://{}:{}@localhost/{}'. 12 | format(argv[1], argv[2], argv[3]), 13 | pool_pre_ping=True) 14 | Base.metadata.create_all(engine) 15 | 16 | session = Session(engine) 17 | data = session.query(State).filter(State.name.like("%a%"))\ 18 | .delete(synchronize_session='fetch') 19 | session.commit() 20 | session.close() 21 | -------------------------------------------------------------------------------- /0x11-python-network_1/8-json_api.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python3 2 | """ 3 | Python script takes in a letter and sends a POST request to 4 | http://0.0.0.0:5000/search_user with the letter as a parameter 5 | """ 6 | import requests 7 | from sys import argv 8 | 9 | if __name__ == '__main__': 10 | q = argv[1] if len(argv) == 2 else "" 11 | url = 'http://0.0.0.0:5000/search_user' 12 | r = requests.post(url, data={'q': q}) 13 | try: 14 | r_dict = r.json() 15 | id, name = r_dict.get('id'), r_dict.get('name') 16 | if len(r_dict) == 0 or not id or not name: 17 | print("No result") 18 | else: 19 | print("[{}] {}".format(r_dict.get('id'), r_dict.get('name'))) 20 | except: 21 | print("Not a valid JSON") 22 | -------------------------------------------------------------------------------- /0x07-python-test_driven_development/tests/4-print_square.txt: -------------------------------------------------------------------------------- 1 | >>> print_square = __import__('4-print_square').print_square 2 | 3 | >>> print_square(4) 4 | #### 5 | #### 6 | #### 7 | #### 8 | >>> print_square(0) 9 | 10 | >>> print_square(1) 11 | # 12 | >>> print_square(-1) 13 | Traceback (most recent call last): 14 | ... 15 | ValueError: size must be >= 0 16 | 17 | >>> print_square("string") 18 | Traceback (most recent call last): 19 | ... 20 | TypeError: size must be an integer 21 | 22 | >>> print_square(None) 23 | Traceback (most recent call last): 24 | ... 25 | TypeError: size must be an integer 26 | 27 | >>> print_square(True) 28 | # 29 | 30 | >>> print_square(-1.0) 31 | Traceback (most recent call last): 32 | ... 33 | TypeError: size must be an integer 34 | -------------------------------------------------------------------------------- /0x0A-python-inheritance/9-rectangle.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python3 2 | """ 3 | more class base 4 | """ 5 | 6 | 7 | BaseGeometry = __import__('7-base_geometry').BaseGeometry 8 | 9 | 10 | class Rectangle(BaseGeometry): 11 | """ definition of a Rectangle """ 12 | def __init__(self, width, height): 13 | """ constructor and width, height""" 14 | self.__width = width 15 | self.__height = height 16 | BaseGeometry.integer_validator(self, "width", self.__width) 17 | BaseGeometry.integer_validator(self, "height", self.__height) 18 | 19 | def area(self): 20 | return self.__width * self.__height 21 | 22 | def __str__(self): 23 | """ print """ 24 | return ("[Rectangle] " + str(self.__width) + "/" + str(self.__height)) 25 | -------------------------------------------------------------------------------- /0x14-javascript-web_scraping/6-completed_tasks.js: -------------------------------------------------------------------------------- 1 | #!/usr/bin/node 2 | // script that computes the number of tasks completed by user id. 3 | 4 | const args = process.argv; 5 | let reqURL = args[2]; 6 | let request = require('request'); 7 | request(reqURL, function (error, response, body) { 8 | if (error) { 9 | console.log('error:', error); 10 | } else { 11 | let todos = JSON.parse(body); 12 | let dash = {}; 13 | for (let i = 0; i < todos.length; i++) { 14 | let status = (todos[i]['completed']); 15 | let key = todos[i]['userId'].toString(); 16 | if (status) { 17 | if (dash[key]) { 18 | dash[key]++; 19 | } else { 20 | dash[key] = 1; 21 | } 22 | } 23 | } 24 | console.log(dash); 25 | } 26 | }); 27 | -------------------------------------------------------------------------------- /0x13-javascript_objects_scopes_closures/4-rectangle.js: -------------------------------------------------------------------------------- 1 | #!/usr/bin/node 2 | // class Rectangle that defines a rectangle 3 | 4 | class Rectangle { 5 | constructor (w, h) { 6 | if (w > 0 && h > 0) { 7 | this.width = w; 8 | this.height = h; 9 | } 10 | } 11 | 12 | print () { 13 | let i, j, string; 14 | for (i = 0; i < this.height; i++) { 15 | string = ''; 16 | for (j = 0; j < this.width; j++) { 17 | string += 'X'; 18 | } 19 | console.log(string); 20 | } 21 | } 22 | 23 | rotate () { 24 | let temp; 25 | temp = this.height; 26 | this.height = this.width; 27 | this.width = temp; 28 | } 29 | 30 | double () { 31 | this.height *= 2; 32 | this.width *= 2; 33 | } 34 | } 35 | 36 | module.exports = Rectangle; 37 | -------------------------------------------------------------------------------- /0x0F-python-object_relational_mapping/9-model_state_filter_a.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python3 2 | """ 3 | All states via SQLAlchemy 4 | """ 5 | from sys import argv 6 | from model_state import Base, State 7 | from sqlalchemy import (create_engine) 8 | from sqlalchemy.orm import Session 9 | 10 | if __name__ == "__main__": 11 | engine = create_engine('mysql+mysqldb://{}:{}@localhost/{}'. 12 | format(argv[1], argv[2], argv[3]), 13 | pool_pre_ping=True) 14 | Base.metadata.create_all(engine) 15 | 16 | session = Session(engine) 17 | data = session.query(State).order_by(State.id)\ 18 | .filter(State.name.like("%a%")).all() 19 | for row in data: 20 | print("{}: {}".format(row.id, row.name)) 21 | session.close() 22 | -------------------------------------------------------------------------------- /0x14-javascript-web_scraping/4-starwars_count.js: -------------------------------------------------------------------------------- 1 | #!/usr/bin/node 2 | // prints the number of movies where the character Wedge Antilles is present 3 | 4 | const args = process.argv; 5 | let reqURL = args[2]; 6 | let request = require('request'); 7 | request(reqURL, function (error, response, body) { 8 | if (error) { 9 | console.log('error:', error); // Print the error if one occurred 10 | } else { 11 | let jso = JSON.parse(body); 12 | let results = jso['results']; 13 | let count = 0; 14 | for (let i = 0; i < results.length; i++) { 15 | let chars = (results[i]['characters']); 16 | for (let j = 0; j < chars.length; j++) { 17 | let check18 = chars[j].endsWith('18/'); 18 | if (check18) { 19 | count++; 20 | } 21 | } 22 | } 23 | console.log(count); 24 | } 25 | }); 26 | -------------------------------------------------------------------------------- /0x0F-python-object_relational_mapping/model_state.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python3 2 | """ 3 | class definition of a State and an instance Base 4 | """ 5 | 6 | from sqlalchemy import Column, Integer, String 7 | from sqlalchemy.ext.declarative import declarative_base 8 | 9 | Base = declarative_base() 10 | 11 | 12 | class State(Base): 13 | """ 14 | State class: 15 | inherits from Base 16 | links to the MySQL table states 17 | class attribute id that represents a column of an auto-generated, 18 | unique integer, cant be null and is a primary key 19 | class attribute name that represents a column of a string 20 | with maximum 128 characters and cant be null 21 | """ 22 | __tablename__ = 'states' 23 | id = Column(Integer, primary_key=True, nullable=False, autoincrement=True) 24 | name = Column(String(128), nullable=False) 25 | -------------------------------------------------------------------------------- /0x0F-python-object_relational_mapping/100-relationship_states_cities.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python3 2 | """ 3 | All states via SQLAlchemy 4 | """ 5 | from sys import argv 6 | from relationship_state import Base, State 7 | from relationship_city import City 8 | from sqlalchemy import (create_engine) 9 | from sqlalchemy.orm import Session 10 | 11 | if __name__ == "__main__": 12 | engine = create_engine('mysql+mysqldb://{}:{}@localhost/{}'. 13 | format(argv[1], argv[2], argv[3]), 14 | pool_pre_ping=True) 15 | Base.metadata.create_all(engine) 16 | 17 | session = Session(engine) 18 | new_state = State(name='California') 19 | 20 | new_city = City(name='San Francisco') 21 | new_state.cities.append(new_city) 22 | 23 | session.add(new_state) 24 | session.commit() 25 | session.close() 26 | -------------------------------------------------------------------------------- /0x0F-python-object_relational_mapping/7-model_state_fetch_all.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python3 2 | """ 3 | All states via SQLAlchemy 4 | """ 5 | 6 | from sys import argv 7 | from sqlalchemy import create_engine 8 | from sqlalchemy.ext.declarative import declarative_base 9 | from sqlalchemy.orm import sessionmaker 10 | from model_state import Base, State 11 | 12 | if __name__ == "__main__": 13 | engine = create_engine( 14 | 'mysql+mysqldb://{}:{}@localhost/{}'.format(argv[1], 15 | argv[2], 16 | argv[3])) 17 | Base.metadata.create_all(engine) 18 | Session = sessionmaker(bind=engine) 19 | session = Session() 20 | for state in session.query(State).order_by(State.id): 21 | print("{}: {}".format(state.id, state.name)) 22 | session.close() 23 | -------------------------------------------------------------------------------- /0x07-python-test_driven_development/3-say_my_name.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python3 2 | ''' 3 | module: say_my_name 4 | ''' 5 | 6 | 7 | def say_my_name(first_name, last_name=''): 8 | ''' print first and last name, make the big bucks 9 | Keyword arguments: 10 | first_name -- string 11 | last_name -- string 12 | ''' 13 | 14 | # ERROR MESSAGE DICT # 15 | err_msg = {} 16 | err_msg["FirstNotStr"] = "first_name must be a string" 17 | err_msg["LastNotStr"] = "last_name must be a string" 18 | 19 | # TESTS # 20 | if type(first_name) != str: 21 | raise TypeError(err_msg["FirstNotStr"]) 22 | if type(last_name) != str: 23 | raise TypeError(err_msg["LastNotStr"]) 24 | 25 | # OUTPUT # 26 | print("My name is {}".format(first_name), end='') 27 | if len(last_name) == 0: 28 | print() 29 | else: 30 | print(" {}".format(last_name)) 31 | -------------------------------------------------------------------------------- /0x0F-python-object_relational_mapping/5-filter_cities.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python3 2 | """ 3 | lists all cities from the database 4 | """ 5 | if __name__ == "__main__": 6 | 7 | import MySQLdb 8 | from sys import argv 9 | 10 | cont = 0 11 | conect = MySQLdb.connect(host="localhost", port=3306, user=argv[1], 12 | passwd=argv[2], db=argv[3], charset="utf8") 13 | cursor = conect.cursor() 14 | cursor.execute("""SELECT cities.id, cities.name, states.name 15 | FROM cities 16 | LEFT JOIN states ON cities.state_id = states.id 17 | ORDER BY cities.id ASC""") 18 | query_rows = cursor.fetchall() 19 | for row in query_rows: 20 | if row[2] == argv[4]: 21 | if cont > 0: 22 | print(", ", end="") 23 | print(row[1], end="") 24 | cont = cont + 1 25 | print() 26 | cursor.close() 27 | conect.close() 28 | -------------------------------------------------------------------------------- /0x02-python-import_modules/100-my_calculator.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python3 2 | from calculator_1 import add, sub, mul, div 3 | 4 | 5 | def arg_calc(argv): 6 | n = len(argv) - 1 7 | if n != 3: 8 | print("Usage: ./100-my_calculator.py ") 9 | exit(1) 10 | a = int(argv[1]) 11 | op = argv[2] 12 | b = int(argv[3]) 13 | if op == '+': 14 | print("{:d} {:s} {:d} = {:d}".format(a, op, b, add(a, b))) 15 | elif op == '-': 16 | print("{:d} {:s} {:d} = {:d}".format(a, op, b, sub(a, b))) 17 | elif op == '*': 18 | print("{:d} {:s} {:d} = {:d}".format(a, op, b, mul(a, b))) 19 | elif op == '/': 20 | print("{:d} {:s} {:d} = {:d}".format(a, op, b, div(a, b))) 21 | else: 22 | print("Unknown operator. Available operators: +, -, * and /") 23 | exit(1) 24 | 25 | 26 | if __name__ == "__main__": 27 | import sys 28 | arg_calc(sys.argv) 29 | -------------------------------------------------------------------------------- /0x0F-python-object_relational_mapping/12-model_state_update_id_2.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python3 2 | ''' 3 | a script that lists all State objects 4 | from the database hbtn_0e_6_usa 5 | ''' 6 | 7 | 8 | from sys import argv 9 | from sqlalchemy import create_engine 10 | from sqlalchemy.ext.declarative import declarative_base 11 | from sqlalchemy.orm import sessionmaker 12 | from model_state import Base, State 13 | 14 | if __name__ == "__main__": 15 | engine = create_engine( 16 | 'mysql+mysqldb://{}:{}@localhost/{}'.format(argv[1], 17 | argv[2], 18 | argv[3])) 19 | Base.metadata.create_all(engine) 20 | Session = sessionmaker(bind=engine) 21 | session = Session() 22 | state = session.query(State).filter_by(id=2).first() 23 | state.name = "New Mexico" 24 | session.commit() 25 | session.close() 26 | -------------------------------------------------------------------------------- /0x06-python-classes/5-square.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python3 2 | 3 | 4 | class Square: 5 | '''Initialize Class Square 6 | ''' 7 | 8 | def __init__(self, size=0): 9 | '''init method of class Square 10 | ''' 11 | self.size = size 12 | 13 | @property 14 | def size(self): 15 | return self.__size 16 | 17 | @size.setter 18 | def size(self, size): 19 | if type(size) != int: 20 | raise TypeError("size must be an integer") 21 | if size < 0: 22 | raise ValueError("size must be >= 0") 23 | self.__size = size 24 | 25 | def area(self): 26 | return (self.size * self.size) 27 | 28 | def my_print(self): 29 | if self.__size == 0: 30 | print() 31 | return 32 | for i in range(self.__size): 33 | for j in range(self.__size): 34 | print("#", end="") 35 | print() 36 | -------------------------------------------------------------------------------- /0x0F-python-object_relational_mapping/101-relationship_states_cities_list.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python3 2 | """ 3 | All states via SQLAlchemy 4 | """ 5 | from sys import argv 6 | from relationship_state import Base, State 7 | from relationship_city import City 8 | from sqlalchemy import (create_engine) 9 | from sqlalchemy.orm import Session 10 | 11 | if __name__ == "__main__": 12 | engine = create_engine('mysql+mysqldb://{}:{}@localhost/{}'. 13 | format(argv[1], argv[2], argv[3]), 14 | pool_pre_ping=True) 15 | Base.metadata.create_all(engine) 16 | 17 | session = Session(engine) 18 | 19 | data = session.query(State).order_by(State.id).all() 20 | 21 | for row in data: 22 | print("{}: {}".format(row.id, row.name)) 23 | for city in row.cities: 24 | print(" {}: {}".format(city.id, city.name)) 25 | 26 | session.commit() 27 | session.close() 28 | -------------------------------------------------------------------------------- /0x0F-python-object_relational_mapping/8-model_state_fetch_first.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python3 2 | """ 3 | All states via SQLAlchemy 4 | """ 5 | 6 | from sys import argv 7 | from sqlalchemy import create_engine 8 | from sqlalchemy.ext.declarative import declarative_base 9 | from sqlalchemy.orm import sessionmaker 10 | from model_state import Base, State 11 | 12 | if __name__ == "__main__": 13 | engine = create_engine( 14 | 'mysql+mysqldb://{}:{}@localhost/{}'.format(argv[1], 15 | argv[2], 16 | argv[3])) 17 | Base.metadata.create_all(engine) 18 | Session = sessionmaker(bind=engine) 19 | session = Session() 20 | state = session.query(State).order_by(State.id).first() 21 | if state: 22 | print("{}: {}".format(state.id, state.name)) 23 | else: 24 | print("Nothing") 25 | session.close() 26 | -------------------------------------------------------------------------------- /0x0F-python-object_relational_mapping/102-relationship_cities_states_list.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python3 2 | """ 3 | script that lists all City objects 4 | from the database hbtn_0e_101_usa 5 | """ 6 | import sqlalchemy 7 | from sqlalchemy import create_engine 8 | from sqlalchemy.orm import sessionmaker 9 | from relationship_state import Base, State 10 | from relationship_city import City 11 | from sys import argv 12 | 13 | 14 | if __name__ == "__main__": 15 | e = 'mysql+mysqldb://{}:{}@localhost/{}'.format(argv[1], 16 | argv[2], 17 | argv[3]) 18 | engine = create_engine(e) 19 | Base.metadata.create_all(engine) 20 | Session = sessionmaker(bind=engine) 21 | s = Session() 22 | cities = s.query(City).all() 23 | for city in cities: 24 | print("{}: {} -> {}".format(city.id, city.name, city.state.name)) 25 | s.close() 26 | -------------------------------------------------------------------------------- /0x04-python-more_data_structures/103-python.py: -------------------------------------------------------------------------------- 1 | import ctypes 2 | 3 | lib = ctypes.CDLL('./libPython.so') 4 | lib.print_python_list.argtypes = [ctypes.py_object] 5 | lib.print_python_bytes.argtypes = [ctypes.py_object] 6 | s = b"Hello" 7 | lib.print_python_bytes(s); 8 | b = b'\xff\xf8\x00\x00\x00\x00\x00\x00'; 9 | lib.print_python_bytes(b); 10 | b = b'What does the \'b\' character do in front of a string literal?'; 11 | lib.print_python_bytes(b); 12 | l = [b'Hello', b'World'] 13 | lib.print_python_list(l) 14 | del l[1] 15 | lib.print_python_list(l) 16 | l = l + [4, 5, 6.0, (9, 8), [9, 8, 1024], b"Holberton", "Betty"] 17 | lib.print_python_list(l) 18 | l = [] 19 | lib.print_python_list(l) 20 | l.append(0) 21 | lib.print_python_list(l) 22 | l.append(1) 23 | l.append(2) 24 | l.append(3) 25 | l.append(4) 26 | lib.print_python_list(l) 27 | l.pop() 28 | lib.print_python_list(l) 29 | l = ["Holberton"] 30 | lib.print_python_list(l) 31 | lib.print_python_bytes(l); 32 | -------------------------------------------------------------------------------- /0x0F-python-object_relational_mapping/14-model_city_fetch_by_state.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python3 2 | ''' 3 | a script that lists all State objects 4 | ''' 5 | 6 | 7 | from sys import argv 8 | from sqlalchemy import create_engine 9 | from sqlalchemy.orm import sessionmaker 10 | from model_state import Base, State 11 | from model_city import City 12 | 13 | if __name__ == "__main__": 14 | engine = create_engine( 15 | 'mysql+mysqldb://{}:{}@localhost/{}'.format(argv[1], 16 | argv[2], 17 | argv[3])) 18 | Base.metadata.create_all(engine) 19 | Session = sessionmaker(bind=engine) 20 | session = Session() 21 | c = session.query(City, State).filter(City.state_id == State.id)\ 22 | .order_by(City.id).all() 23 | for cty, st in c: 24 | print("{}: ({}) {}".format(st.name, cty.id, cty.name)) 25 | session.close() 26 | -------------------------------------------------------------------------------- /0x07-python-test_driven_development/tests/101-lazy_matrix_mul.txt: -------------------------------------------------------------------------------- 1 | >>> lazy_matrix_mul = __import__('101-lazy_matrix_mul').lazy_matrix_mul 2 | 3 | >>> print(lazy_matrix_mul([[1, 2], [3, 4]], [[1, 2], [3, 4]])) 4 | [[7, 10], [15, 22]] 5 | 6 | >>> print(lazy_matrix_mul([[1, 2]], [[3, 4], [5, 6]])) 7 | [[13, 16]] 8 | 9 | >>> print(lazy_matrix_mul([[1, 2]], [])) 10 | Traceback (most recent call last): 11 | ... 12 | ValueError: m_b can't be empty 13 | 14 | >>> print(lazy_matrix_mul([[]], [])) 15 | Traceback (most recent call last): 16 | ... 17 | ValueError: m_b can't be empty 18 | 19 | 20 | >>> print(lazy_matrix_mul([[1, 2]], ["h"])) 21 | Traceback (most recent call last): 22 | ... 23 | TypeError: m_b must be a list 24 | 25 | >>> print(lazy_matrix_mul(None, [])) 26 | Traceback (most recent call last): 27 | ... 28 | ValueError: m_a can't be empty 29 | 30 | >>> print(lazy_matrix_mul([[1, 2], []], [1, 2])) 31 | Traceback (most recent call last): 32 | ... 33 | TypeError: m_b must be a list 34 | -------------------------------------------------------------------------------- /0x0F-python-object_relational_mapping/10-model_state_my_get.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python3 2 | ''' 3 | a script that lists all State objects 4 | from the database hbtn_0e_6_usa 5 | ''' 6 | 7 | 8 | from sys import argv 9 | from sqlalchemy import create_engine 10 | from sqlalchemy.ext.declarative import declarative_base 11 | from sqlalchemy.orm import sessionmaker 12 | from model_state import Base, State 13 | 14 | if __name__ == "__main__": 15 | engine = create_engine( 16 | 'mysql+mysqldb://{}:{}@localhost/{}'.format(argv[1], 17 | argv[2], 18 | argv[3])) 19 | Base.metadata.create_all(engine) 20 | Session = sessionmaker(bind=engine) 21 | session = Session() 22 | state = session.query(State).filter_by(name=argv[4]).first() 23 | if state is not None: 24 | print(str(state.id)) 25 | else: 26 | print("Not found") 27 | session.close() 28 | -------------------------------------------------------------------------------- /0x03-python-data_structures/100-print_python_list_info.c: -------------------------------------------------------------------------------- 1 | #include "Python.h" 2 | /** 3 | * print_python_list_info - Prints information about python objects 4 | * @p: PyObject pointer to print info about 5 | * Compile with: 6 | * gcc -Wall -Werror -Wextra -pedantic -std=c99 -shared 7 | (* -Wl,-soname,PyList -o libPyList.so -fPIC -I/usr/include/python3.4 8 | (* 100-print_python_list_info.c 9 | */ 10 | void print_python_list_info(PyObject *p) 11 | { 12 | Py_ssize_t i, py_list_size; 13 | PyObject *item; 14 | const char *item_type; 15 | PyListObject *list_object_cast; 16 | 17 | list_object_cast = (PyListObject *)p; 18 | py_list_size = PyList_Size(p); 19 | 20 | printf("[*] Size of the Python List = %d\n", (int) py_list_size); 21 | printf("[*] Allocated = %d\n", (int)list_object_cast->allocated); 22 | for (i = 0; i < py_list_size; i++) 23 | { 24 | item = PyList_GetItem(p, i); 25 | item_type = Py_TYPE(item)->tp_name; 26 | printf("Element %d: %s\n", (int) i, item_type); 27 | } 28 | } 29 | -------------------------------------------------------------------------------- /0x02-python-import_modules/calculator_1.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python3 2 | def add(a, b): 3 | """My addition function 4 | 5 | Args: 6 | a: first integer 7 | b: second integer 8 | 9 | Returns: 10 | The return value. a + b 11 | """ 12 | return (a + b) 13 | 14 | 15 | def sub(a, b): 16 | """My subtraction function 17 | 18 | Args: 19 | a: first integer 20 | b: second integer 21 | 22 | Returns: 23 | The return value. a - b 24 | """ 25 | return (a - b) 26 | 27 | 28 | def mul(a, b): 29 | """My multiplication function 30 | 31 | Args: 32 | a: first integer 33 | b: second integer 34 | 35 | Returns: 36 | The return value. a * b 37 | """ 38 | return (a * b) 39 | 40 | 41 | def div(a, b): 42 | """My division function 43 | 44 | Args: 45 | a: first integer 46 | b: second integer 47 | 48 | Returns: 49 | The return value. a / b 50 | """ 51 | return int(a / b) 52 | -------------------------------------------------------------------------------- /0x0F-python-object_relational_mapping/relationship_state.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python3 2 | """ 3 | class definition of a State and an instance Base = declarative_base() 4 | """ 5 | 6 | from sqlalchemy import Column, Integer, String 7 | from sqlalchemy.ext.declarative import declarative_base 8 | from sqlalchemy.orm import relationship 9 | 10 | Base = declarative_base() 11 | 12 | 13 | class State(Base): 14 | """ 15 | State class: 16 | inherits from Base 17 | links to the MySQL table states 18 | class attribute id that represents a column of an auto-generated, 19 | unique integer, cant be null and is a primary key 20 | class attribute name that represents a column of a string 21 | with maximum 128 characters and cant be null 22 | """ 23 | __tablename__ = 'states' 24 | id = Column(Integer, primary_key=True, nullable=False, autoincrement=True) 25 | name = Column(String(128), nullable=False) 26 | cities = relationship('City', cascade='save-update, merge, delete', 27 | backref='state') 28 | -------------------------------------------------------------------------------- /0x0F-python-object_relational_mapping/relationship_city.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python3 2 | """ 3 | class definition of a State and an instance Base = declarative_base() 4 | """ 5 | 6 | from sqlalchemy import Column, Integer, String, ForeignKey 7 | from sqlalchemy.ext.declarative import declarative_base 8 | from relationship_state import Base 9 | 10 | 11 | class City(Base): 12 | """ 13 | City class: 14 | inherits from Base 15 | links to the MySQL table states 16 | class attribute id that represents a column of an auto-generated, 17 | unique integer, cant be null and is a primary key 18 | class attribute name that represents a column of a string 19 | with maximum 128 characters and cant be null 20 | class attribute state_id that represents a column of an integer, 21 | can’t be null and is a foreign key to states.id 22 | """ 23 | __tablename__ = 'cities' 24 | id = Column(Integer, primary_key=True, autoincrement=True, nullable=False) 25 | name = Column(String(128), nullable=False) 26 | state_id = Column(Integer, ForeignKey("states.id"), nullable=False) 27 | -------------------------------------------------------------------------------- /0x08-python-more_classes/1-rectangle.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python3 2 | """ 3 | This is a Rectangle class. 4 | """ 5 | 6 | 7 | class Rectangle: 8 | """ 9 | Initialize Rectangle object with height and width. 10 | """ 11 | 12 | def __init__(self, width=0, height=0): 13 | self.__width = width 14 | self.__height = height 15 | 16 | @property 17 | def width(self): 18 | """get rectangle width 19 | """ 20 | return self.__width 21 | 22 | @property 23 | def height(self): 24 | """rectangle height 25 | """ 26 | return self.__height 27 | 28 | @width.setter 29 | def width(self, value): 30 | if type(value) is not int: 31 | raise TypeError("width must be an integer") 32 | if value <= 0: 33 | raise ValueError("width must be >= 0") 34 | self.__width = value 35 | 36 | @height.setter 37 | def height(self, value): 38 | if type(value) is not int: 39 | raise TypeError("height must be an integer") 40 | if value < 0: 41 | raise ValueError("height must be >= 0") 42 | self.__height = value 43 | -------------------------------------------------------------------------------- /0x0C-python-almost_a_circle/README.md: -------------------------------------------------------------------------------- 1 | # 0x0C. Python - Almost a circle 2 | 3 | ## *args and **kwargs in python explained 4 | 5 | Hi there folks. I have come to see that most new python programmers have a hard time figuring out the *args and **kwargs magic variables. So what are they ? First of all let me tell you that it is not necessary to write *args or **kwargs. Only the * (aesteric) is necessary. You could have also written *var and **vars. Writing *args and **kwargs is just a convention. So now lets take a look at *args first. 6 | 7 | 8 | ## Serialization and Deserialization of Python Objects 9 | 10 | Python object serialization and deserialization is an important aspect of any non-trivial program. If in Python you save something to a file, if you read a configuration file, or if you respond to an HTTP request, you do object serialization and deserialization. 11 | 12 | 13 | ## JSON in Python 14 | 15 | Python has a JSON module that will help converting the datastructures to JSON strings. Use the import function to import the JSON module. import json. The JSON module is mainly used to convert the python dictionary above into a JSON string that can be written into a file. 16 | -------------------------------------------------------------------------------- /0x0F-python-object_relational_mapping/14-model_city_fetch_by_state.sql: -------------------------------------------------------------------------------- 1 | -- Create database hbtn_0e_14_usa, tables states and cities + some data 2 | CREATE DATABASE IF NOT EXISTS hbtn_0e_14_usa; 3 | USE hbtn_0e_14_usa; 4 | 5 | CREATE TABLE IF NOT EXISTS states ( 6 | id INT NOT NULL AUTO_INCREMENT, 7 | name VARCHAR(256) NOT NULL, 8 | PRIMARY KEY (id) 9 | ); 10 | INSERT INTO states (name) VALUES ("California"), ("Arizona"), ("Texas"), ("New York"), ("Nevada"); 11 | 12 | CREATE TABLE IF NOT EXISTS cities ( 13 | id INT NOT NULL AUTO_INCREMENT, 14 | state_id INT NOT NULL, 15 | name VARCHAR(256) NOT NULL, 16 | PRIMARY KEY (id), 17 | FOREIGN KEY(state_id) REFERENCES states(id) 18 | ); 19 | INSERT INTO cities (state_id, name) VALUES (1, "San Francisco"), (1, "San Jose"), (1, "Los Angeles"), (1, "Fremont"), (1, "Livermore"); 20 | INSERT INTO cities (state_id, name) VALUES (2, "Page"), (2, "Phoenix"); 21 | INSERT INTO cities (state_id, name) VALUES (3, "Dallas"), (3, "Houston"), (3, "Austin"); 22 | INSERT INTO cities (state_id, name) VALUES (4, "New York"); 23 | INSERT INTO cities (state_id, name) VALUES (5, "Las Vegas"), (5, "Reno"), (5, "Henderson"), (5, "Carson City"); 24 | -------------------------------------------------------------------------------- /0x14-javascript-web_scraping/102-search_twitter.js: -------------------------------------------------------------------------------- 1 | #!/usr/bin/node 2 | 3 | const base64 = require('base-64'); 4 | const request = require('request'); 5 | const utf8 = require('utf8'); 6 | 7 | function search (bearer) { 8 | const url = 'https://api.twitter.com/1.1/search/tweets.json'; 9 | request.get({ 10 | url, 11 | headers: { 12 | Authorization: `Bearer ${bearer}` 13 | }, 14 | qs: { 15 | q: process.argv[4], 16 | count: '5' 17 | } 18 | }, (err, res, body) => { 19 | if (!err) { 20 | const tweets = JSON.parse(body).statuses; 21 | tweets.forEach((tweet) => console.log(`[${tweet.id}] ${tweet.text} by ${tweet.user.name}`)); 22 | } 23 | }); 24 | } 25 | 26 | const promise = new Promise((resolve, reject) => { 27 | const token = utf8.decode(base64.encode(`${process.argv[2]}:${process.argv[3]}`)); 28 | const url = 'https://api.twitter.com/oauth2/token'; 29 | request.post({ 30 | url, 31 | headers: { 32 | Authorization: `Basic ${token}`, 33 | 'Content-Type': 'application/x-www-form-urlencoded;charset=UTF-8' 34 | }, 35 | form: { 36 | grant_type: 'client_credentials' 37 | } 38 | }, (err, res, body) => { 39 | if (!err) { 40 | resolve(JSON.parse(body).access_token); 41 | } 42 | }); 43 | }); 44 | promise.then( 45 | result => search(result), 46 | err => console.log(err) 47 | ); 48 | -------------------------------------------------------------------------------- /0x07-python-test_driven_development/2-matrix_divided.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python3 2 | """ 3 | This is the "2-matrix_divided" module. 4 | The 2-matrix_divided module functions: matrix_divided(a, b). 5 | """ 6 | 7 | 8 | def matrix_divided(matrix, div): 9 | """ 10 | matrix_divided: divides all elements of a matrix 11 | Args: 12 | matrix (int, float): list of lists of integers or floats 13 | div (int): divident 14 | Returns: 15 | int 16 | """ 17 | size = None 18 | if type(matrix) is not list: 19 | raise TypeError( 20 | "matrix must be a matrix (list of lists) of integers/floats") 21 | for l in matrix: 22 | if type(l) is not list: 23 | raise TypeError( 24 | "matrix must be a matrix (list of lists) of integers/floats") 25 | if size is None: 26 | size = len(l) 27 | elif size != len(l): 28 | raise TypeError("Each row of the matrix must have the same size") 29 | for i in l: 30 | if type(i) is not int and type(i) is not float: 31 | raise TypeError( 32 | "matrix must be a matrix (list of lists) of integers/floats") 33 | if type(div) is not int and type(div) is not float: 34 | raise TypeError("div must be a number") 35 | if div == 0: 36 | raise ZeroDivisionError("division by zero") 37 | return [[round(i / div, 2) for i in l] for l in matrix] 38 | -------------------------------------------------------------------------------- /0x04-python-more_data_structures/103-python.c: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | 4 | 5 | /** 6 | * print_python_bytes - print some basic info about Python bytes objects 7 | * @p: python object 8 | * Return: nothing 9 | **/ 10 | void print_python_bytes(PyObject *p) 11 | { 12 | char *s; 13 | Py_ssize_t len, i; 14 | 15 | printf("[.] bytes object info\n"); 16 | if (!PyBytes_Check(p)) 17 | printf(" [ERROR] Invalid Bytes Object\n"); 18 | else 19 | { 20 | PyBytes_AsStringAndSize(p, &s, &len); 21 | printf(" size: %lu\n", len); 22 | printf(" trying string: %s\n", s); 23 | if (len > 10) 24 | len = 10; 25 | else 26 | len++; 27 | printf(" first %lu bytes: ", len); 28 | for (i = 0; i < len - 1; i++) 29 | printf("%02x ", s[i] & 0xff); 30 | printf("%02x\n", s[len - 1] & 0xff); 31 | } 32 | } 33 | 34 | 35 | /** 36 | * print_python_list - print some basic info about Python lists 37 | * @p: python object 38 | * Return: nothing 39 | **/ 40 | void print_python_list(PyObject *p) 41 | { 42 | Py_ssize_t i; 43 | PyObject *in_list; 44 | 45 | if (PyList_Check(p)) 46 | { 47 | printf("[*] Python list info\n"); 48 | printf("[*] Size of the Python List = %lu\n", PyList_Size(p)); 49 | printf("[*] Allocated = %lu\n", ((PyListObject *)p)->allocated); 50 | for (i = 0; i < PyList_Size(p); i++) 51 | { 52 | in_list = PySequence_GetItem(p, i); 53 | printf("Element %lu: %s\n", i, 54 | in_list->ob_type->tp_name); 55 | if (strcmp(in_list->ob_type->tp_name, "bytes") == 0) 56 | print_python_bytes(in_list); 57 | } 58 | } 59 | } 60 | -------------------------------------------------------------------------------- /0x07-python-test_driven_development/tests/0-add_integer.txt: -------------------------------------------------------------------------------- 1 | The ``0-add_integer`` module 2 | ============================ 3 | 4 | Using ``add_integer`` 5 | --------------------- 6 | 7 | This is an example text file in reStructuredText format. First import 8 | ``add_integer`` from the ``0-add_integer`` module: 9 | 10 | >>> add_integer = __import__('0-add_integer').add_integer 11 | 12 | Now use it: 13 | 14 | >>> add_integer(2, 3) 15 | 5 16 | 17 | >>> add_integer(100.3, -2) 18 | 98 19 | 20 | >>> add_integer(-True, False) 21 | -1 22 | 23 | >>> add_integer(-True, -False) 24 | -1 25 | 26 | >>> add_integer(True, False) 27 | 1 28 | 29 | >>> add_integer(True, -False) 30 | 1 31 | 32 | >>> add_integer(100.3, 100.3) 33 | 200 34 | 35 | >>> add_integer("school", 100.3) 36 | Traceback (most recent call last): 37 | ... 38 | TypeError: a must be an integer 39 | 40 | >>> add_integer("Holberton", "School") 41 | Traceback (most recent call last): 42 | ... 43 | TypeError: a must be an integer 44 | 45 | >>> add_integer(None, "School") 46 | Traceback (most recent call last): 47 | ... 48 | TypeError: a must be an integer 49 | 50 | >>> add_integer(5.25, 3.3) 51 | 8 52 | 53 | >>> add_integer(10, None) 54 | Traceback (most recent call last): 55 | ... 56 | TypeError: b must be an integer 57 | 58 | >>> add_integer("adc", 10) 59 | Traceback (most recent call last): 60 | ... 61 | TypeError: a must be an integer 62 | 63 | >>> add_integer(float('inf'),8) 64 | Traceback (most recent call last): 65 | ... 66 | OverflowError: cannot convert float infinity to integer 67 | 68 | >>> add_integer(float('NaN'), 7) 69 | Traceback (most recent call last): 70 | ... 71 | ValueError: cannot convert float NaN to integer 72 | -------------------------------------------------------------------------------- /0x0C-python-almost_a_circle/models/rectangle.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python3 2 | ''' First rectangle 3 | ''' 4 | 5 | from models.base import Base 6 | 7 | 8 | class Rectangle(Base): 9 | '''class Rectangle inherits from base 10 | ''' 11 | KV_dict = {'id': 'id', 'width': '_Rectangle__width', 12 | 'height': '_Rectangle__height', 13 | 'x': '_Rectangle__x', 'y': '_Rectangle__y'} 14 | 15 | def __init__(self, width, height, x=0, y=0, id=None): 16 | '''method __init__ Initialization a Rectangle 17 | ''' 18 | super().__init__(id) 19 | self.width = width 20 | self.height = height 21 | self.x = x 22 | self.y = y 23 | 24 | def update(self, *args, **kwargs): 25 | '''method update 26 | ''' 27 | key_list = ['id', '_Rectangle__width', '_Rectangle__height', 28 | '_Rectangle__x', '_Rectangle__y'] 29 | KV_dict = {'id': 'id', 'width': '_Rectangle__width', 30 | 'height': '_Rectangle__height', 31 | 'x': '_Rectangle__x', 'y': '_Rectangle__y'} 32 | for idx, el in enumerate(args): 33 | self.__dict__[key_list[idx]] = el 34 | if len(args) == 0: 35 | for key, val in kwargs.items(): 36 | self.__dict__[KV_dict[key]] = val 37 | 38 | def __str__(self): 39 | '''method __str__ 40 | ''' 41 | 42 | return ("[Rectangle] ({}) {}/{} - {}/{}".format(self.id, self.__x, 43 | self.__y, self.__width, self.__height)) 44 | 45 | def area(self): 46 | '''public_method area of rectangle 47 | ''' 48 | return self.__width * self.__height 49 | 50 | def display(self): 51 | '''public method display self prints in stdout # 52 | ''' 53 | print("\n" * (self.__y), end="") 54 | for i in range(self.__height): 55 | print(" " * self.__x + "#" * self.__width) 56 | -------------------------------------------------------------------------------- /0x0C-python-almost_a_circle/models/square.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python3 2 | """Define Rectangle Class 3 | """ 4 | 5 | from models.rectangle import Rectangle 6 | 7 | 8 | class Square(Rectangle): 9 | """Module Representation of Square 10 | """ 11 | 12 | def __init__(self, size, x=0, y=0, id=None): 13 | """Initialization a Square 14 | """ 15 | super().__init__(size, size, x, y, id) 16 | 17 | @property 18 | def size(self): 19 | """module Square size getter 20 | """ 21 | return self.width 22 | 23 | @size.setter 24 | def size(self, value): 25 | """module Square size setter 26 | """ 27 | self.width = value 28 | self.height = value 29 | 30 | def __str__(self): 31 | """module string represation of square 32 | """ 33 | return "[Square] ({:d}) {:d}/{:d} - {:d}".format(self.id, 34 | self.x, 35 | self.y, 36 | self.width) 37 | 38 | def update(self, *args, **kwargs): 39 | """module update square 40 | """ 41 | if len(args): 42 | for i, arg in enumerate(args): 43 | if i == 0: 44 | self.id = arg 45 | elif i == 1: 46 | self.size = arg 47 | elif i == 2: 48 | self.x = arg 49 | elif i == 3: 50 | self.y = arg 51 | else: 52 | for key, value in kwargs.items(): 53 | if hasattr(self, key) is True: 54 | setattr(self, key, value) 55 | 56 | def to_dictionary(self): 57 | """retrun dictonary 58 | """ 59 | return { 60 | "id": self.id, 61 | "size": self.size, 62 | "x": self.x, 63 | "y": self.y 64 | } 65 | -------------------------------------------------------------------------------- /0x0C-python-almost_a_circle/models/base.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python3 2 | ''' models/base.py 3 | ''' 4 | import json 5 | 6 | 7 | class Base: 8 | ''' first class Base 9 | ''' 10 | 11 | __nb_objects = 0 12 | 13 | def __init__(self, id=None): 14 | ''' initialize Base __init__ 15 | ''' 16 | if id is not None: 17 | self.id = id 18 | else: 19 | Base.__nb_objects += 1 20 | self.id = Base.__nb_objects 21 | 22 | @classmethod 23 | def save_to_file(cls, list_objs): 24 | '''method: save_to_file 25 | ''' 26 | list_dicts = [] 27 | if list_objs is not None: 28 | for obj in list_objs: 29 | tmp_dict = cls.to_dictionary(obj) 30 | list_dicts.append(tmp_dict) 31 | json_L_of_D = cls.to_json_string(list_dicts) 32 | else: 33 | json_L_of_D = "[]" 34 | 35 | filename = cls.__name__ + ".json" 36 | 37 | with open(filename, "w") as file: 38 | num_char = file.write(json_L_of_D) 39 | 40 | @staticmethod 41 | def to_json_string(list_dictionaries): 42 | ''' method json string 43 | ''' 44 | ret_list = [] 45 | if list_dictionaries is None or len(list_dictionaries) == 0: 46 | return "[]" 47 | 48 | if type(list_dictionaries) != list: 49 | ret_list.append(list_dictionaries) 50 | else: 51 | ret_list = list_dictionaries 52 | return json.dumps(ret_list) 53 | 54 | @staticmethod 55 | def to_json_string(list_dictionaries): 56 | ''' method json string 57 | ''' 58 | ret_list = [] 59 | if list_dictionaries is None or len(list_dictionaries) == 0: 60 | return "[]" 61 | 62 | if type(list_dictionaries) != list: 63 | ret_list.append(list_dictionaries) 64 | else: 65 | ret_list = list_dictionaries 66 | return json.dumps(ret_list) 67 | -------------------------------------------------------------------------------- /0x07-python-test_driven_development/tests/3-say_my_name.txt: -------------------------------------------------------------------------------- 1 | The ``3-say_my_name`` module 2 | ====================== 3 | 4 | Using ``say_my_name`` 5 | ------------------- 6 | 7 | Importing the function from the module: 8 | >>> say_my_name = __import__("3-say_my_name").say_my_name 9 | 10 | Checking for module docstring: 11 | >>> m = __import__("3-say_my_name").__doc__ 12 | >>> len(m) > 1 13 | True 14 | 15 | Checking for function docstring: 16 | >>> f = __import__("3-say_my_name").say_my_name.__doc__ 17 | >>> len(f) > 1 18 | True 19 | 20 | Checking for passing None as first name: 21 | >>> say_my_name(None, "Hello") 22 | Traceback (most recent call last): 23 | ... 24 | TypeError: first_name must be a string 25 | 26 | Checking for passing None as last name: 27 | >>> say_my_name("Hello", None) 28 | Traceback (most recent call last): 29 | ... 30 | TypeError: last_name must be a string 31 | 32 | Checking for wrong type as first name: 33 | >>> say_my_name(1, "Hello") 34 | Traceback (most recent call last): 35 | ... 36 | TypeError: first_name must be a string 37 | 38 | Checking for wrong type as last name: 39 | >>> say_my_name("Hello", [4]) 40 | Traceback (most recent call last): 41 | ... 42 | TypeError: last_name must be a string 43 | 44 | Checking for normal use: 45 | >>> say_my_name("Hello", "World") 46 | My name is Hello World 47 | >>> say_my_name("You know nothing", "John Snow") 48 | My name is You know nothing John Snow 49 | 50 | Checking for 1 arg: 51 | >>> say_my_name("Hello") 52 | My name is Hello 53 | 54 | Checking for more than 2 args: 55 | >>> say_my_name("Hello", "World", "hi") 56 | Traceback (most recent call last): 57 | ... 58 | TypeError: say_my_name() takes from 1 to 2 positional arguments but 3 were given 59 | -------------------------------------------------------------------------------- /0x08-python-more_classes/3-rectangle.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python3 2 | """ 3 | Defines: class Rectangle 4 | Creates a Rectangle object height and width and calculates its area, 5 | perimeter and prints it with # 6 | """ 7 | 8 | 9 | class Rectangle: 10 | """Represents a Rectangle width and height 11 | """ 12 | def __init__(self, width=0, height=0): 13 | """Initializes a rectangle 14 | """ 15 | self.__width = width 16 | self.__height = height 17 | 18 | @property 19 | def width(self): 20 | """Private instance attribute __width 21 | """ 22 | return self.__width 23 | 24 | @property 25 | def height(self): 26 | """rectangle height 27 | Returns private instance attribute __height 28 | """ 29 | return self.__height 30 | 31 | @width.setter 32 | def width(self, value): 33 | """set of rectangle width 34 | """ 35 | if type(value) is not int: 36 | raise TypeError("width must be an integer") 37 | if value <= 0: 38 | raise ValueError("width must be >= 0") 39 | self.__width = value 40 | 41 | @height.setter 42 | def height(self, value): 43 | 44 | if type(value) is not int: 45 | raise TypeError("height must be an integer") 46 | if value < 0: 47 | raise ValueError("height must be >= 0") 48 | self.__height = value 49 | 50 | def area(self): 51 | """Returns the area of the rectangle 52 | """ 53 | return self.__width * self.__height 54 | 55 | def perimeter(self): 56 | """Returns the perimeter of the rectangle 57 | """ 58 | if self.__width == 0 or self.__height == 0: 59 | return 0 60 | return 2 * self.__width + 2 * self.__height 61 | 62 | def __str__(self): 63 | """Returns string 64 | """ 65 | rep_str = "" 66 | if self.__width != 0 and self.__height != 0: 67 | rep_str += "\n".join("#" * self.__width 68 | for i in range(self.__height)) 69 | return rep_str 70 | -------------------------------------------------------------------------------- /0x0A-python-inheritance/tests/1-my_list.txt: -------------------------------------------------------------------------------- 1 | 0t.txt module 2 | ==================== 3 | 4 | Importing the class from the module: 5 | >>> MyList = __import__("1-my_list").MyList 6 | 7 | Checking for module docstring: 8 | >>> m = __import__("1-my_list").__doc__ 9 | >>> len(m) > 1 10 | True 11 | 12 | Checking for class docstring: 13 | >>> c = __import__("1-my_list").MyList.__doc__ 14 | >>> len(c) > 1 15 | True 16 | 17 | Checking for method docstring 18 | >>> f = __import__("1-my_list").MyList.print_sorted.__doc__ 19 | >>> len(f) > 1 20 | True 21 | 22 | Checking given test case 23 | >>> my_list = MyList() 24 | 25 | >>> my_list.append(1) 26 | 27 | >>> my_list.append(4) 28 | 29 | >>> my_list.append(2) 30 | 31 | >>> my_list.append(3) 32 | 33 | >>> my_list.append(5) 34 | 35 | >>> print(my_list) 36 | [1, 4, 2, 3, 5] 37 | 38 | >>> my_list.print_sorted() 39 | [1, 2, 3, 4, 5] 40 | 41 | >>> print(my_list) 42 | [1, 4, 2, 3, 5] 43 | 44 | Checking empty object 45 | >>> obj1 = MyList() 46 | 47 | >>> print(obj1) 48 | [] 49 | 50 | >>> obj1.print_sorted() 51 | [] 52 | 53 | Checking negative values 54 | >>> obj2 = MyList() 55 | 56 | >>> obj2.append(-1) 57 | 58 | >>> obj2.append(0) 59 | 60 | >>> obj2.append(-233) 61 | 62 | >>> obj2.append(-9) 63 | 64 | >>> print(obj2) 65 | [-1, 0, -233, -9] 66 | 67 | >>> obj2.print_sorted() 68 | [-233, -9, -1, 0] 69 | 70 | Checking NULL object 71 | >>> obj3 = MyList() 72 | 73 | >>> obj3.append(NULL) 74 | Traceback (most recent call last): 75 | ... 76 | NameError: name 'NULL' is not defined 77 | 78 | >>> print(obj3) 79 | [] 80 | 81 | >>> obj3.print_sorted() 82 | [] 83 | 84 | Checking NaN object 85 | >>> obj4 = MyList() 86 | 87 | >>> obj4.append(NaN) 88 | Traceback (most recent call last): 89 | ... 90 | NameError: name 'NaN' is not defined 91 | 92 | >>> print(obj4) 93 | [] 94 | 95 | >>> obj4.print_sorted() 96 | [] 97 | 98 | Checking None object 99 | >>> obj5 = MyList() 100 | 101 | >>> obj5.append(None) 102 | 103 | >>> print(obj5) 104 | [None] 105 | 106 | >>> obj5.print_sorted() 107 | [None] 108 | -------------------------------------------------------------------------------- /0x08-python-more_classes/2-rectangle.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python3 2 | 3 | '''module: 2-rectangle 4 | This is a Rectangle class. 5 | ''' 6 | 7 | 8 | class Rectangle: 9 | '''class: Rectangle this is an empty class 10 | ''' 11 | 12 | def __init__(self, width=0, height=0): 13 | '''method: __init__ 14 | initialize instance of Rectangle 15 | ''' 16 | self.__width = width 17 | self.__height = height 18 | 19 | @property 20 | def width(self): 21 | '''method: set_width getter 22 | ''' 23 | if (not isinstance(self.__width, int)) or isinstance(self.__width, 24 | bool): 25 | raise TypeError("width must be an integer") 26 | if self.__width < 0: 27 | raise ValueError("width must be >= 0") 28 | return self.__width 29 | 30 | @width.setter 31 | def width(self, width): 32 | '''method: set_width setter 33 | ''' 34 | if not isinstance(self.__width, int) or isinstance(self.__width, bool): 35 | raise TypeError("width must be an integer") 36 | if self.__width < 0: 37 | raise ValueError("width must be >= 0") 38 | self.__width = width 39 | 40 | @property 41 | def height(self): 42 | '''method: set_height getter 43 | ''' 44 | if (not isinstance(self.__height, int)) or isinstance(self.__height, 45 | bool): 46 | raise TypeError("height must be an integer") 47 | if self.__height < 0: 48 | raise ValueError("height must be >= 0") 49 | return self.__height 50 | 51 | @height.setter 52 | def height(self, height): 53 | '''method: set_height 54 | setter 55 | ''' 56 | if not isinstance(self.__height, int) or isinstance(self.__height, 57 | bool): 58 | raise TypeError("height must be an integer") 59 | if self.__height < 0: 60 | raise ValueError("height must be >= 0") 61 | self.__height = height 62 | 63 | """ 64 | Calculate area of Rectangle. 65 | """ 66 | def area(self): 67 | return self.__height * self.__width 68 | 69 | """ 70 | Calculate perimeter of Rectangle object. 71 | """ 72 | def perimeter(self): 73 | if self.__height == 0 or self.width == 0: 74 | return 0 75 | return (self.__height + self.width) * 2 76 | -------------------------------------------------------------------------------- /0x07-python-test_driven_development/tests/6-max_integer_test.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python3 2 | """Unittest for max_integer([..]) 3 | """ 4 | import unittest 5 | max_integer = __import__('6-max_integer').max_integer 6 | 7 | 8 | class TestMaxInteger(unittest.TestCase): 9 | """Presence of docstrings""" 10 | 11 | def test_module_docstring(self): 12 | """Check: module docsting""" 13 | module = __import__('6-max_integer').__doc__ 14 | self.assertTrue(len(module) > 1) 15 | 16 | def test_function_docstring(self): 17 | """Check: funstion docstring""" 18 | f = max_integer.__doc__ 19 | self.assertTrue(len(f) > 1) 20 | 21 | def test_no_args(self): 22 | """Check: no arguments passed to func""" 23 | self.assertIsNone(max_integer()) 24 | 25 | def test_empty_list(self): 26 | """Check: empty list []""" 27 | test = [] 28 | self.assertIsNone(max_integer(test)) 29 | 30 | def test_max_at_end(self): 31 | """Check: all positive max at end""" 32 | test = [12, 1, 18, 6, 14, 40] 33 | self.assertEqual(max_integer(test), 40) 34 | 35 | def test_two_of_max(self): 36 | """Check: max at end""" 37 | test = [12, 1, 40, 6, 14, 40] 38 | self.assertEqual(max_integer(test), 40) 39 | 40 | def test_none(self): 41 | """Check: passing none as argument""" 42 | with self.assertRaises(TypeError): 43 | max_integer(None) 44 | 45 | def test_non_int_arg(self): 46 | """Check: non integer type""" 47 | test = [1, "string", 3, 4, 5] 48 | with self.assertRaises(TypeError): 49 | max_integer(test) 50 | 51 | def test_one_element(self): 52 | """Check: only one number""" 53 | test_ele = [10] 54 | self.assertEqual(max_integer(test_ele), 10) 55 | 56 | def test_max_at_beginning(self): 57 | """Check: positive max at beginning""" 58 | test_pos = [130, 129, 23, 6, 0, 10] 59 | self.assertEqual(max_integer(test_pos), 130) 60 | 61 | def test_max_at_middle(self): 62 | """Check: max in middle""" 63 | test_max = [1, 10, 23, 30, 14, 12] 64 | self.assertEqual(max_integer(test_max), 30) 65 | 66 | def test_one_negative(self): 67 | """Check: negative number""" 68 | test = [10, -10, 1, 6, 4, 2] 69 | self.assertEqual(max_integer(test), 10) 70 | 71 | def test_all_10(self): 72 | """Check: all otems """ 73 | test = [10, 10, 10, 10, 10, 10] 74 | self.assertEqual(max_integer(test), 10) 75 | 76 | def test_all_negative(self): 77 | """Check: all negative numbers""" 78 | test_neg = [-1, -2, -3, -4, -5] 79 | self.assertEqual(max_integer(test_neg), -1) 80 | 81 | 82 | if __name__ == "__main__": 83 | unittest.main() 84 | -------------------------------------------------------------------------------- /0x04-python-more_data_structures/103-tests.py: -------------------------------------------------------------------------------- 1 | import ctypes 2 | 3 | lib = ctypes.CDLL('./libPython.so') 4 | lib.print_python_list.argtypes = [ctypes.py_object] 5 | lib.print_python_bytes.argtypes = [ctypes.py_object] 6 | s = b"Hello" 7 | lib.print_python_bytes(s); 8 | b = b'\xff\xf8\x00\x00\x00\x00\x00\x00'; 9 | lib.print_python_bytes(b); 10 | b = b'What does the \'b\' character do in front of a string literal?'; 11 | lib.print_python_bytes(b); 12 | l = [b'Hello', b'World'] 13 | lib.print_python_list(l) 14 | del l[1] 15 | lib.print_python_list(l) 16 | l = l + [4, 5, 6.0, (9, 8), [9, 8, 1024], b"Holberton", "Betty"] 17 | lib.print_python_list(l) 18 | l = [] 19 | lib.print_python_list(l) 20 | l.append(0) 21 | lib.print_python_list(l) 22 | l.append(1) 23 | l.append(2) 24 | l.append(3) 25 | l.append(4) 26 | lib.print_python_list(l) 27 | l.pop() 28 | lib.print_python_list(l) 29 | l = ["Holberton"] 30 | lib.print_python_list(l) 31 | lib.print_python_bytes(l); 32 | julien@ubuntu:~/CPython$ python3 103-tests.py 33 | [.] bytes object info 34 | size: 5 35 | trying string: Hello 36 | first 6 bytes: 48 65 6c 6c 6f 00 37 | [.] bytes object info 38 | size: 8 39 | trying string: 40 | first 9 bytes: ff f8 00 00 00 00 00 00 00 41 | [.] bytes object info 42 | size: 60 43 | trying string: What does the 'b' character do in front of a string literal? 44 | first 10 bytes: 57 68 61 74 20 64 6f 65 73 20 45 | [*] Python list info 46 | [*] Size of the Python List = 2 47 | [*] Allocated = 2 48 | Element 0: bytes 49 | [.] bytes object info 50 | size: 5 51 | trying string: Hello 52 | first 6 bytes: 48 65 6c 6c 6f 00 53 | Element 1: bytes 54 | [.] bytes object info 55 | size: 5 56 | trying string: World 57 | first 6 bytes: 57 6f 72 6c 64 00 58 | [*] Python list info 59 | [*] Size of the Python List = 1 60 | [*] Allocated = 2 61 | Element 0: bytes 62 | [.] bytes object info 63 | size: 5 64 | trying string: Hello 65 | first 6 bytes: 48 65 6c 6c 6f 00 66 | [*] Python list info 67 | [*] Size of the Python List = 8 68 | [*] Allocated = 8 69 | Element 0: bytes 70 | [.] bytes object info 71 | size: 5 72 | trying string: Hello 73 | first 6 bytes: 48 65 6c 6c 6f 00 74 | Element 1: int 75 | Element 2: int 76 | Element 3: float 77 | Element 4: tuple 78 | Element 5: list 79 | Element 6: bytes 80 | [.] bytes object info 81 | size: 9 82 | trying string: Holberton 83 | first 10 bytes: 48 6f 6c 62 65 72 74 6f 6e 00 84 | Element 7: str 85 | [*] Python list info 86 | [*] Size of the Python List = 0 87 | [*] Allocated = 0 88 | [*] Python list info 89 | [*] Size of the Python List = 1 90 | [*] Allocated = 4 91 | Element 0: int 92 | [*] Python list info 93 | [*] Size of the Python List = 5 94 | [*] Allocated = 8 95 | Element 0: int 96 | Element 1: int 97 | Element 2: int 98 | Element 3: int 99 | Element 4: int 100 | [*] Python list info 101 | [*] Size of the Python List = 4 102 | [*] Allocated = 8 103 | Element 0: int 104 | Element 1: int 105 | Element 2: int 106 | Element 3: int 107 | [*] Python list info 108 | [*] Size of the Python List = 1 109 | [*] Allocated = 1 110 | Element 0: str 111 | [.] bytes object info 112 | [ERROR] Invalid Bytes Object 113 | -------------------------------------------------------------------------------- /0x07-python-test_driven_development/tests/100-matrix_mul.txt: -------------------------------------------------------------------------------- 1 | Importing the function from the module: 2 | >>> matrix_mul = __import__("100-matrix_mul").matrix_mul 3 | 4 | Check: module docstring: 5 | >>> m = __import__("100-matrix_mul").__doc__ 6 | >>> len(m) > 1 7 | True 8 | 9 | Check: function docstring: 10 | >>> f = __import__("100-matrix_mul").matrix_mul.__doc__ 11 | >>> len(f) > 1 12 | True 13 | 14 | Check: no args: 15 | >>> matrix_mul() 16 | Traceback (most recent call last): 17 | ... 18 | TypeError: matrix_mul() missing 2 required positional arguments: 'm_a' and 'm_b' 19 | 20 | Check: one arg: 21 | >>> matrix_mul([[1, 2], [3, 4]]) 22 | Traceback (most recent call last): 23 | ... 24 | TypeError: matrix_mul() missing 1 required positional argument: 'm_b' 25 | 26 | Check: too many args: 27 | >>> matrix_mul([[1, 2], [3, 4]], [[5, 6], [7, 8]], [[9, 10], [11, 12]]) 28 | Traceback (most recent call last): 29 | ... 30 | TypeError: matrix_mul() takes 2 positional arguments but 3 were given 31 | 32 | Check: normal use with ints and floats: 33 | >>> matrix_mul([[1, 2], [3, 4]], [[1.5, 2.5, 3.5], [4.5, 6.5, 7.5]]) 34 | [[10.5, 15.5, 18.5], [22.5, 33.5, 40.5]] 35 | 36 | Check: passing m_a as None: 37 | >>> matrix_mul(None, [[1, 2], [2, 1]]) 38 | Traceback (most recent call last): 39 | ... 40 | TypeError: m_a must be a list 41 | 42 | Check: passing m_b as None: 43 | >>> matrix_mul([[1, 2], [2, 1]], None) 44 | Traceback (most recent call last): 45 | ... 46 | TypeError: m_b must be a list 47 | 48 | Check: passing empty m_a: 49 | >>> matrix_mul([], [[1, 2], [2, 1]]) 50 | Traceback (most recent call last): 51 | ... 52 | ValueError: m_a can't be empty 53 | 54 | Check: passing m_a with empty rows: 55 | >>> matrix_mul([[], []], [[1, 2], [2, 1]]) 56 | Traceback (most recent call last): 57 | ... 58 | ValueError: m_a can't be empty 59 | 60 | Check: passing empty m_b: 61 | >>> matrix_mul([[1, 2], [2, 1]], []) 62 | Traceback (most recent call last): 63 | ... 64 | ValueError: m_b can't be empty 65 | 66 | Check: passing m_b with empty rows: 67 | >>> matrix_mul([[1, 2], [2, 1]], [[]]) 68 | Traceback (most recent call last): 69 | ... 70 | ValueError: m_b can't be empty 71 | 72 | Check: uneven m_a: 73 | >>> matrix_mul([[1, 2], [1, 2, 3]], [[1, 2], [2, 1]]) 74 | Traceback (most recent call last): 75 | ... 76 | TypeError: each row of m_a must be of the same size 77 | 78 | Check: uneven m_b: 79 | >>> matrix_mul([[1, 2], [2, 1]], [[1, 2], [1, 2, 3]]) 80 | Traceback (most recent call last): 81 | ... 82 | TypeError: each row of m_b must be of the same size 83 | 84 | Check: string in list in m_a: 85 | >>> matrix_mul([[1, "Friends"], [2, 1]], [[1, 2], [2, 1]]) 86 | Traceback (most recent call last): 87 | ... 88 | TypeError: m_a should contain only integers or floats 89 | 90 | Check: string in list in m_b: 91 | >>> matrix_mul([[1, 2], [2, 1]], [[1, "Friends"], [2, 1]]) 92 | Traceback (most recent call last): 93 | ... 94 | TypeError: m_b should contain only integers or floats 95 | 96 | Check: mismatching matrices: 97 | >>> matrix_mul([[1, 1, 1], [1, 1, 1]], [[1, 1], [1, 1,]]) 98 | Traceback (most recent call last): 99 | ... 100 | ValueError: m_a and m_b can't be multiplied 101 | -------------------------------------------------------------------------------- /0x08-python-more_classes/4-rectangle.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python3 2 | 3 | '''module: 4-rectangle 4 | this module contains the class Rectangle ... 5 | ''' 6 | 7 | 8 | class Rectangle: 9 | '''class: Rectangle 10 | this is an empty class, further additions in subsequent assignments 11 | ''' 12 | 13 | def __init__(self, width=0, height=0): 14 | '''method: __init__ 15 | initialize instance of class Rectangle 16 | ''' 17 | self.__width = width 18 | self.__height = height 19 | 20 | @property 21 | def width(self): 22 | '''method: set_width 23 | getter 24 | ''' 25 | if (not isinstance(self.__width, int)) or isinstance(self.__width, 26 | bool): 27 | raise TypeError("width must be an integer") 28 | if self.__width < 0: 29 | raise ValueError("width must be >= 0") 30 | return self.__width 31 | 32 | @width.setter 33 | def width(self, width): 34 | '''method: set_width 35 | setter 36 | ''' 37 | if not isinstance(self.__width, int) or isinstance(self.__width, bool): 38 | raise TypeError("width must be an integer") 39 | if self.__width < 0: 40 | raise ValueError("width must be >= 0") 41 | self.__width = width 42 | 43 | @property 44 | def height(self): 45 | '''method: set_height 46 | getter 47 | ''' 48 | if (not isinstance(self.__height, int)) or isinstance(self.__height, 49 | bool): 50 | raise TypeError("height must be an integer") 51 | if self.__height < 0: 52 | raise ValueError("height must be >= 0") 53 | return self.__height 54 | 55 | @height.setter 56 | def height(self, height): 57 | '''method: set_height 58 | setter 59 | ''' 60 | if not isinstance(self.__height, int) or isinstance(self.__height, 61 | bool): 62 | raise TypeError("height must be an integer") 63 | if self.__height < 0: 64 | raise ValueError("height must be >= 0") 65 | self.__height = height 66 | 67 | def area(self): 68 | '''method: area 69 | return area of rectangle 70 | ''' 71 | return self.__height * self.__width 72 | 73 | def perimeter(self): 74 | '''method: perimeter 75 | return perimeter of perimeter 76 | ''' 77 | if self.__height == 0 or self.width == 0: 78 | return 0 79 | return (self.__height + self.width) * 2 80 | 81 | def __str__(self): 82 | '''method: __str__ 83 | return: nice string representation of rectangle 84 | ''' 85 | ret_str = "" 86 | if self.__height == 0 or self.__width == 0: 87 | return "" 88 | for idx in range(self.__height): 89 | ret_str += '#' * self.width 90 | if idx + 1 < self.__height: 91 | ret_str += '\n' 92 | return ret_str 93 | 94 | def __repr__(self): 95 | '''method: __repr)__ 96 | return: representation of rectangle that can be used by eval() to 97 | create new object 98 | ''' 99 | ret_str = "Rectangle(" + str(self.__width) + "," 100 | ret_str += str(self.__height) + ")" 101 | return ret_str 102 | -------------------------------------------------------------------------------- /0x08-python-more_classes/6-rectangle.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python3 2 | 3 | '''module: rectangle 4 | this module contains the class Rectangle ... 5 | ''' 6 | 7 | 8 | class Rectangle: 9 | '''class: Rectangle 10 | this is Rectangle class 11 | ''' 12 | 13 | number_of_instances = 0 14 | 15 | def __init__(self, width=0, height=0): 16 | '''method: __init__ 17 | initialize instance of class 18 | ''' 19 | Rectangle.number_of_instances += 1 20 | self.__width = width 21 | self.__height = height 22 | 23 | @property 24 | def width(self): 25 | '''method: set_width 26 | getter 27 | ''' 28 | if (not isinstance(self.__width, int)) or isinstance(self.__width, 29 | bool): 30 | raise TypeError("width must be an integer") 31 | if self.__width < 0: 32 | raise ValueError("width must be >= 0") 33 | return self.__width 34 | 35 | @width.setter 36 | def width(self, width): 37 | '''method set_width 38 | ''' 39 | if not isinstance(self.__width, int) or isinstance(self.__width, bool): 40 | raise TypeError("width must be an integer") 41 | if self.__width < 0: 42 | raise ValueError("width must be >= 0") 43 | self.__width = width 44 | 45 | @property 46 | def height(self): 47 | '''method: set_height 48 | getter 49 | ''' 50 | if (not isinstance(self.__height, int)) or isinstance(self.__height, 51 | bool): 52 | raise TypeError("height must be an integer") 53 | if self.__height < 0: 54 | raise ValueError("height must be >= 0") 55 | return self.__height 56 | 57 | @height.setter 58 | def height(self, height): 59 | '''setter 60 | ''' 61 | if not isinstance(self.__height, int) or isinstance(self.__height, 62 | bool): 63 | raise TypeError("height must be an integer") 64 | if self.__height < 0: 65 | raise ValueError("height must be >= 0") 66 | self.__height = height 67 | 68 | def area(self): 69 | '''method area of rectangle 70 | ''' 71 | return self.__height * self.__width 72 | 73 | def perimeter(self): 74 | '''method return perimeter of perimeter 75 | ''' 76 | if self.__height == 0 or self.width == 0: 77 | return 0 78 | return (self.__height + self.width) * 2 79 | 80 | def __str__(self): 81 | '''method: __str__ 82 | return nice string rectangle 83 | ''' 84 | ret_str = "" 85 | if self.__height == 0 or self.__width == 0: 86 | return "" 87 | for idx in range(self.__height): 88 | ret_str += '#' * self.width 89 | if idx + 1 < self.__height: 90 | ret_str += '\n' 91 | return ret_str 92 | 93 | def __repr__(self): 94 | '''method: __repr__ create new object 95 | ''' 96 | ret_str = "Rectangle(" + str(self.__width) + "," 97 | ret_str += str(self.__height) + ")" 98 | return ret_str 99 | 100 | def __del__(self): 101 | '''method: __del__ 102 | deletes instance, prints "bye" message 103 | ''' 104 | Rectangle.number_of_instances -= 1 105 | print("Bye rectangle...") 106 | -------------------------------------------------------------------------------- /0x08-python-more_classes/5-rectangle.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python3 2 | 3 | '''module: 5-rectangle 4 | this module contains the class Rectangle ... 5 | ''' 6 | 7 | 8 | class Rectangle: 9 | '''class: Rectangle 10 | this is an empty class, further additions in subsequent assignments 11 | ''' 12 | 13 | def __init__(self, width=0, height=0): 14 | '''method: __init__ 15 | initialize instance of class Rectangle 16 | ''' 17 | self.__width = width 18 | self.__height = height 19 | 20 | @property 21 | def width(self): 22 | '''method: set_width 23 | getter 24 | ''' 25 | if (not isinstance(self.__width, int)) or isinstance(self.__width, 26 | bool): 27 | raise TypeError("width must be an integer") 28 | if self.__width < 0: 29 | raise ValueError("width must be >= 0") 30 | return self.__width 31 | 32 | @width.setter 33 | def width(self, width): 34 | '''method: set_width 35 | setter 36 | ''' 37 | if not isinstance(self.__width, int) or isinstance(self.__width, bool): 38 | raise TypeError("width must be an integer") 39 | if self.__width < 0: 40 | raise ValueError("width must be >= 0") 41 | self.__width = width 42 | 43 | @property 44 | def height(self): 45 | '''method: set_height 46 | getter 47 | ''' 48 | if (not isinstance(self.__height, int)) or isinstance(self.__height, 49 | bool): 50 | raise TypeError("height must be an integer") 51 | if self.__height < 0: 52 | raise ValueError("height must be >= 0") 53 | return self.__height 54 | 55 | @height.setter 56 | def height(self, height): 57 | '''method: set_height 58 | setter 59 | ''' 60 | if not isinstance(self.__height, int) or isinstance(self.__height, 61 | bool): 62 | raise TypeError("height must be an integer") 63 | if self.__height < 0: 64 | raise ValueError("height must be >= 0") 65 | self.__height = height 66 | 67 | def area(self): 68 | '''method: area 69 | return area of rectangle 70 | ''' 71 | return self.__height * self.__width 72 | 73 | def perimeter(self): 74 | '''method: perimeter 75 | return perimeter of perimeter 76 | ''' 77 | if self.__height == 0 or self.width == 0: 78 | return 0 79 | return (self.__height + self.width) * 2 80 | 81 | def __str__(self): 82 | '''method: __str__ 83 | return: nice string representation of rectangle 84 | ''' 85 | ret_str = "" 86 | if self.__height == 0 or self.__width == 0: 87 | return "" 88 | for idx in range(self.__height): 89 | ret_str += '#' * self.width 90 | if idx + 1 < self.__height: 91 | ret_str += '\n' 92 | return ret_str 93 | 94 | def __repr__(self): 95 | '''method: __repr__ 96 | return: representation of rectangle that can be used by eval() to 97 | create new object 98 | ''' 99 | ret_str = "Rectangle(" + str(self.__width) + "," 100 | ret_str += str(self.__height) + ")" 101 | return ret_str 102 | 103 | def __del__(self): 104 | '''method: __del__ 105 | deletes instance of Rectangle class, and prints "bye" message 106 | ''' 107 | print("Bye rectangle...") 108 | -------------------------------------------------------------------------------- /0x08-python-more_classes/7-rectangle.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python3 2 | 3 | '''module: 7-rectangle 4 | this module contains the class Rectangle ... 5 | ''' 6 | 7 | 8 | class Rectangle: 9 | '''class: Rectangle 10 | this is an empty class, further additions in subsequent assignments 11 | ''' 12 | 13 | number_of_instances = 0 14 | print_symbol = "#" 15 | 16 | def __init__(self, width=0, height=0): 17 | '''method: __init__ 18 | initialize instance of class Rectangle 19 | ''' 20 | Rectangle.number_of_instances += 1 21 | self.__width = width 22 | self.__height = height 23 | 24 | @property 25 | def width(self): 26 | '''method: set_width 27 | getter 28 | ''' 29 | if (not isinstance(self.__width, int)) or isinstance(self.__width, 30 | bool): 31 | raise TypeError("width must be an integer") 32 | if self.__width < 0: 33 | raise ValueError("width must be >= 0") 34 | return self.__width 35 | 36 | @width.setter 37 | def width(self, width): 38 | '''method: set_width 39 | setter 40 | ''' 41 | if not isinstance(self.__width, int) or isinstance(self.__width, bool): 42 | raise TypeError("width must be an integer") 43 | if self.__width < 0: 44 | raise ValueError("width must be >= 0") 45 | self.__width = width 46 | 47 | @property 48 | def height(self): 49 | '''method: set_height 50 | getter 51 | ''' 52 | if (not isinstance(self.__height, int)) or isinstance(self.__height, 53 | bool): 54 | raise TypeError("height must be an integer") 55 | if self.__height < 0: 56 | raise ValueError("height must be >= 0") 57 | return self.__height 58 | 59 | @height.setter 60 | def height(self, height): 61 | '''method: set_height 62 | setter 63 | ''' 64 | if not isinstance(self.__height, int) or isinstance(self.__height, 65 | bool): 66 | raise TypeError("height must be an integer") 67 | if self.__height < 0: 68 | raise ValueError("height must be >= 0") 69 | self.__height = height 70 | 71 | def area(self): 72 | '''method: area 73 | return area of rectangle 74 | ''' 75 | return self.__height * self.__width 76 | 77 | def perimeter(self): 78 | '''method: perimeter 79 | return perimeter of perimeter 80 | ''' 81 | if self.__height == 0 or self.width == 0: 82 | return 0 83 | return (self.__height + self.width) * 2 84 | 85 | def __str__(self): 86 | '''method: __str__ 87 | return: nice string representation of rectangle 88 | ''' 89 | ret_str = "" 90 | if self.__height == 0 or self.__width == 0: 91 | return "" 92 | for idx in range(self.__height): 93 | ret_str += str(self.print_symbol) * self.width 94 | if idx + 1 < self.__height: 95 | ret_str += '\n' 96 | return ret_str 97 | 98 | def __repr__(self): 99 | '''method: __repr__ 100 | return: representation of rectangle that can be used by eval() to 101 | create new object 102 | ''' 103 | ret_str = "Rectangle(" + str(self.__width) + "," 104 | ret_str += str(self.__height) + ")" 105 | return ret_str 106 | 107 | def __del__(self): 108 | '''method: __del__ 109 | deletes instance of Rectangle class, and prints "bye" message 110 | ''' 111 | Rectangle.number_of_instances -= 1 112 | print("Bye rectangle...") 113 | -------------------------------------------------------------------------------- /0x0E-SQL_more_queries/hbtn_0d_tvshows.sql: -------------------------------------------------------------------------------- 1 | -- MySQL dump 10.13 Distrib 5.7.8-rc, for Linux (x86_64) 2 | -- 3 | -- Host: localhost Database: hbtn_0d_tvshows 4 | -- ------------------------------------------------------ 5 | -- Server version5.7.8-rc 6 | 7 | /*!40101 SET @OLD_CHARACTER_SET_CLIENT=@@CHARACTER_SET_CLIENT */; 8 | /*!40101 SET @OLD_CHARACTER_SET_RESULTS=@@CHARACTER_SET_RESULTS */; 9 | /*!40101 SET @OLD_COLLATION_CONNECTION=@@COLLATION_CONNECTION */; 10 | /*!40101 SET NAMES utf8 */; 11 | /*!40103 SET @OLD_TIME_ZONE=@@TIME_ZONE */; 12 | /*!40103 SET TIME_ZONE='+00:00' */; 13 | /*!40014 SET @OLD_UNIQUE_CHECKS=@@UNIQUE_CHECKS, UNIQUE_CHECKS=0 */; 14 | /*!40014 SET @OLD_FOREIGN_KEY_CHECKS=@@FOREIGN_KEY_CHECKS, FOREIGN_KEY_CHECKS=0 */; 15 | /*!40101 SET @OLD_SQL_MODE=@@SQL_MODE, SQL_MODE='NO_AUTO_VALUE_ON_ZERO' */; 16 | /*!40111 SET @OLD_SQL_NOTES=@@SQL_NOTES, SQL_NOTES=0 */; 17 | 18 | -- 19 | -- Table structure for table `tv_genres` 20 | -- 21 | 22 | DROP TABLE IF EXISTS `tv_genres`; 23 | /*!40101 SET @saved_cs_client = @@character_set_client */; 24 | /*!40101 SET character_set_client = utf8 */; 25 | CREATE TABLE `tv_genres` ( 26 | `id` int(11) NOT NULL AUTO_INCREMENT, 27 | `name` varchar(256) NOT NULL, 28 | PRIMARY KEY (`id`) 29 | ) ENGINE=InnoDB AUTO_INCREMENT=9 DEFAULT CHARSET=latin1; 30 | /*!40101 SET character_set_client = @saved_cs_client */; 31 | 32 | -- 33 | -- Dumping data for table `tv_genres` 34 | -- 35 | 36 | LOCK TABLES `tv_genres` WRITE; 37 | /*!40000 ALTER TABLE `tv_genres` DISABLE KEYS */; 38 | INSERT INTO `tv_genres` VALUES (1,'Drama'),(2,'Mystery'),(3,'Adventure'),(4,'Fantasy'),(5,'Comedy'),(6,'Crime'),(7,'Suspense'),(8,'Thriller'); 39 | /*!40000 ALTER TABLE `tv_genres` ENABLE KEYS */; 40 | UNLOCK TABLES; 41 | 42 | -- 43 | -- Table structure for table `tv_show_genres` 44 | -- 45 | 46 | DROP TABLE IF EXISTS `tv_show_genres`; 47 | /*!40101 SET @saved_cs_client = @@character_set_client */; 48 | /*!40101 SET character_set_client = utf8 */; 49 | CREATE TABLE `tv_show_genres` ( 50 | `show_id` int(11) NOT NULL, 51 | `genre_id` int(11) NOT NULL, 52 | KEY `show_id` (`show_id`), 53 | KEY `genre_id` (`genre_id`), 54 | CONSTRAINT `tv_show_genres_ibfk_1` FOREIGN KEY (`show_id`) REFERENCES `tv_shows` (`id`), 55 | CONSTRAINT `tv_show_genres_ibfk_2` FOREIGN KEY (`genre_id`) REFERENCES `tv_genres` (`id`) 56 | ) ENGINE=InnoDB DEFAULT CHARSET=latin1; 57 | /*!40101 SET character_set_client = @saved_cs_client */; 58 | 59 | -- 60 | -- Dumping data for table `tv_show_genres` 61 | -- 62 | 63 | LOCK TABLES `tv_show_genres` WRITE; 64 | /*!40000 ALTER TABLE `tv_show_genres` DISABLE KEYS */; 65 | INSERT INTO `tv_show_genres` VALUES (1,1),(1,2),(2,3),(2,1),(2,4),(3,5),(4,5),(5,5),(6,6),(6,1),(6,7),(6,8),(8,6),(8,1),(8,2),(8,7),(8,8),(10,5),(10,1); 66 | /*!40000 ALTER TABLE `tv_show_genres` ENABLE KEYS */; 67 | UNLOCK TABLES; 68 | 69 | -- 70 | -- Table structure for table `tv_shows` 71 | -- 72 | 73 | DROP TABLE IF EXISTS `tv_shows`; 74 | /*!40101 SET @saved_cs_client = @@character_set_client */; 75 | /*!40101 SET character_set_client = utf8 */; 76 | CREATE TABLE `tv_shows` ( 77 | `id` int(11) NOT NULL AUTO_INCREMENT, 78 | `title` varchar(256) NOT NULL, 79 | PRIMARY KEY (`id`) 80 | ) ENGINE=InnoDB AUTO_INCREMENT=11 DEFAULT CHARSET=latin1; 81 | /*!40101 SET character_set_client = @saved_cs_client */; 82 | 83 | -- 84 | -- Dumping data for table `tv_shows` 85 | -- 86 | 87 | LOCK TABLES `tv_shows` WRITE; 88 | /*!40000 ALTER TABLE `tv_shows` DISABLE KEYS */; 89 | INSERT INTO `tv_shows` VALUES (1,'House'),(2,'Game of Thrones'),(3,'The Big Bang Theory'),(4,'New Girl'),(5,'Silicon Valley'),(6,'Breaking Bad'),(7,'Better Call Saul'),(8,'Dexter'),(9,'Homeland'),(10,'The Last Man on Earth'); 90 | /*!40000 ALTER TABLE `tv_shows` ENABLE KEYS */; 91 | UNLOCK TABLES; 92 | /*!40103 SET TIME_ZONE=@OLD_TIME_ZONE */; 93 | 94 | /*!40101 SET SQL_MODE=@OLD_SQL_MODE */; 95 | /*!40014 SET FOREIGN_KEY_CHECKS=@OLD_FOREIGN_KEY_CHECKS */; 96 | /*!40014 SET UNIQUE_CHECKS=@OLD_UNIQUE_CHECKS */; 97 | /*!40101 SET CHARACTER_SET_CLIENT=@OLD_CHARACTER_SET_CLIENT */; 98 | /*!40101 SET CHARACTER_SET_RESULTS=@OLD_CHARACTER_SET_RESULTS */; 99 | /*!40101 SET COLLATION_CONNECTION=@OLD_COLLATION_CONNECTION */; 100 | /*!40111 SET SQL_NOTES=@OLD_SQL_NOTES */; 101 | 102 | -- Dump completed on 2017-02-26 20:57:02 103 | -------------------------------------------------------------------------------- /0x05-python-exceptions/103-tests.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python3 -u 2 | 3 | import ctypes 4 | 5 | lib = ctypes.CDLL('./libPython.so') 6 | lib.print_python_list.argtypes = [ctypes.py_object] 7 | lib.print_python_bytes.argtypes = [ctypes.py_object] 8 | lib.print_python_float.argtypes = [ctypes.py_object] 9 | s = b"Hello" 10 | lib.print_python_bytes(s); 11 | b = b'\xff\xf8\x00\x00\x00\x00\x00\x00'; 12 | lib.print_python_bytes(b); 13 | b = b'What does the \'b\' character do in front of a string literal?'; 14 | lib.print_python_bytes(b); 15 | l = [b'Hello', b'World'] 16 | lib.print_python_list(l) 17 | del l[1] 18 | lib.print_python_list(l) 19 | l = l + [4, 5, 6.0, (9, 8), [9, 8, 1024], b"Holberton", "Betty"] 20 | lib.print_python_list(l) 21 | l = [] 22 | lib.print_python_list(l) 23 | l.append(0) 24 | lib.print_python_list(l) 25 | l.append(1) 26 | l.append(2) 27 | l.append(3) 28 | l.append(4) 29 | lib.print_python_list(l) 30 | l.pop() 31 | lib.print_python_list(l) 32 | l = ["Holberton"] 33 | lib.print_python_list(l) 34 | lib.print_python_bytes(l); 35 | f = 3.14 36 | lib.print_python_float(f); 37 | l = [-1.0, -0.1, 0.0, 1.0, 3.14, 3.14159, 3.14159265, 3.141592653589793238462643383279502884197169399375105820974944592307816406286] 38 | print(l) 39 | lib.print_python_list(l); 40 | lib.print_python_float(l); 41 | lib.print_python_list(f); 42 | julien@ubuntu:~/CPython$ ./103-tests.py 43 | [.] bytes object info 44 | size: 5 45 | trying string: Hello 46 | first 6 bytes: 48 65 6c 6c 6f 00 47 | [.] bytes object info 48 | size: 8 49 | trying string: ?? 50 | first 9 bytes: ff f8 00 00 00 00 00 00 00 51 | [.] bytes object info 52 | size: 60 53 | trying string: What does the 'b' character do in front of a string literal? 54 | first 10 bytes: 57 68 61 74 20 64 6f 65 73 20 55 | [*] Python list info 56 | [*] Size of the Python List = 2 57 | [*] Allocated = 2 58 | Element 0: bytes 59 | [.] bytes object info 60 | size: 5 61 | trying string: Hello 62 | first 6 bytes: 48 65 6c 6c 6f 00 63 | Element 1: bytes 64 | [.] bytes object info 65 | size: 5 66 | trying string: World 67 | first 6 bytes: 57 6f 72 6c 64 00 68 | [*] Python list info 69 | [*] Size of the Python List = 1 70 | [*] Allocated = 2 71 | Element 0: bytes 72 | [.] bytes object info 73 | size: 5 74 | trying string: Hello 75 | first 6 bytes: 48 65 6c 6c 6f 00 76 | [*] Python list info 77 | [*] Size of the Python List = 8 78 | [*] Allocated = 8 79 | Element 0: bytes 80 | [.] bytes object info 81 | size: 5 82 | trying string: Hello 83 | first 6 bytes: 48 65 6c 6c 6f 00 84 | Element 1: int 85 | Element 2: int 86 | Element 3: float 87 | [.] float object info 88 | value: 6.0 89 | Element 4: tuple 90 | Element 5: list 91 | Element 6: bytes 92 | [.] bytes object info 93 | size: 9 94 | trying string: Holberton 95 | first 10 bytes: 48 6f 6c 62 65 72 74 6f 6e 00 96 | Element 7: str 97 | [*] Python list info 98 | [*] Size of the Python List = 0 99 | [*] Allocated = 0 100 | [*] Python list info 101 | [*] Size of the Python List = 1 102 | [*] Allocated = 4 103 | Element 0: int 104 | [*] Python list info 105 | [*] Size of the Python List = 5 106 | [*] Allocated = 8 107 | Element 0: int 108 | Element 1: int 109 | Element 2: int 110 | Element 3: int 111 | Element 4: int 112 | [*] Python list info 113 | [*] Size of the Python List = 4 114 | [*] Allocated = 8 115 | Element 0: int 116 | Element 1: int 117 | Element 2: int 118 | Element 3: int 119 | [*] Python list info 120 | [*] Size of the Python List = 1 121 | [*] Allocated = 1 122 | Element 0: str 123 | [.] bytes object info 124 | [ERROR] Invalid Bytes Object 125 | [.] float object info 126 | value: 3.14 127 | [-1.0, -0.1, 0.0, 1.0, 3.14, 3.14159, 3.14159265, 3.141592653589793] 128 | [*] Python list info 129 | [*] Size of the Python List = 8 130 | [*] Allocated = 8 131 | Element 0: float 132 | [.] float object info 133 | value: -1.0 134 | Element 1: float 135 | [.] float object info 136 | value: -0.1 137 | Element 2: float 138 | [.] float object info 139 | value: 0.0 140 | Element 3: float 141 | [.] float object info 142 | value: 1.0 143 | Element 4: float 144 | [.] float object info 145 | value: 3.14 146 | Element 5: float 147 | [.] float object info 148 | value: 3.14159 149 | Element 6: float 150 | [.] float object info 151 | value: 3.14159265 152 | Element 7: float 153 | [.] float object info 154 | value: 3.141592653589793 155 | [.] float object info 156 | [ERROR] Invalid Float Object 157 | [*] Python list info 158 | [ERROR] Invalid List Object 159 | -------------------------------------------------------------------------------- /0x07-python-test_driven_development/tests/2-matrix_divided.txt: -------------------------------------------------------------------------------- 1 | Importing the function from the module: 2 | >>> matrix_divided = __import__("2-matrix_divided").matrix_divided 3 | 4 | Check: module docstring: 5 | >>> m = __import__("2-matrix_divided").__doc__ 6 | >>> len(m) > 1 7 | True 8 | 9 | Check: function docstring: 10 | >>> f = __import__("2-matrix_divided").matrix_divided.__doc__ 11 | >>> len(f) > 1 12 | True 13 | 14 | Check: passing None as matrix: 15 | >>> matrix_divided(None, 1) 16 | Traceback (most recent call last): 17 | ... 18 | TypeError: matrix must be a matrix (list of lists) of integers/floats 19 | 20 | Check: passing None as div: 21 | >>> matrix_divided([[1, 2, 3], [1, 2, 3]], None) 22 | Traceback (most recent call last): 23 | ... 24 | TypeError: div must be a number 25 | 26 | Check: matrix as string: 27 | >>> matrix_divided("Hello world!", 1) 28 | Traceback (most recent call last): 29 | ... 30 | TypeError: matrix must be a matrix (list of lists) of integers/floats 31 | 32 | Check: list and non-list items: 33 | >>> matrix_divided([[1, 2, 3], "Hey"], 1) 34 | Traceback (most recent call last): 35 | ... 36 | TypeError: matrix must be a matrix (list of lists) of integers/floats 37 | 38 | Check: uneven matrix: 39 | >>> matrix_divided([[1, 2, 3], [4, 5, 6, 7]], 3) 40 | Traceback (most recent call last): 41 | ... 42 | TypeError: Each row of the matrix must have the same size 43 | 44 | Check: mix of ints, floats, and string type: 45 | >>> matrix_divided([[1, "Hey", 3], [4.1, 5, 6.8]], 11) 46 | Traceback (most recent call last): 47 | ... 48 | TypeError: matrix must be a matrix (list of lists) of integers/floats 49 | 50 | Check: mix of ints, floats, and bool: 51 | >>> matrix_divided([[0, True, 0], [False, 1, 1]], 11) 52 | Traceback (most recent call last): 53 | ... 54 | TypeError: matrix must be a matrix (list of lists) of integers/floats 55 | 56 | Check: mix of ints, floats, and tuple: 57 | >>> matrix_divided([[(10,), 6], [4.4, 5.5]], 11) 58 | Traceback (most recent call last): 59 | ... 60 | TypeError: matrix must be a matrix (list of lists) of integers/floats 61 | 62 | Check: div as string: 63 | >>> matrix_divided([[1, 2, 3], [1, 2, 3]], "X") 64 | Traceback (most recent call last): 65 | ... 66 | TypeError: div must be a number 67 | 68 | Check: div as bool: 69 | >>> matrix_divided([[1, 2, 3], [4, 5, 6]], True) 70 | Traceback (most recent call last): 71 | ... 72 | TypeError: div must be a number 73 | 74 | Check: division by zero: 75 | >>> matrix_divided([[1, 2, 3], [4, 5, 6]], 0) 76 | Traceback (most recent call last): 77 | ... 78 | ZeroDivisionError: division by zero 79 | 80 | Check: regular division: 81 | >>> matrix = [[1, 2, 3], [4, 5, 6]] 82 | >>> matrix_divided(matrix, 3) 83 | [[0.33, 0.67, 1.0], [1.33, 1.67, 2.0]] 84 | >>> matrix 85 | [[1, 2, 3], [4, 5, 6]] 86 | 87 | Check: mix of ints and floats: 88 | >>> matrix = [[1, 2.4, 3], [4.1, 5, 6.8]] 89 | >>> matrix_divided(matrix, 11) 90 | [[0.09, 0.22, 0.27], [0.37, 0.45, 0.62]] 91 | >>> matrix 92 | [[1, 2.4, 3], [4.1, 5, 6.8]] 93 | 94 | Check: div as float: 95 | >>> matrix = [[1, 2, 3], [4, 5, 6]] 96 | >>> matrix_divided(matrix, 4.5) 97 | [[0.22, 0.44, 0.67], [0.89, 1.11, 1.33]] 98 | >>> matrix 99 | [[1, 2, 3], [4, 5, 6]] 100 | 101 | Check: negative numerators: 102 | >>> matrix = [[-1, -2, -3], [-4, -5, -6]] 103 | >>> matrix_divided(matrix, 3) 104 | [[-0.33, -0.67, -1.0], [-1.33, -1.67, -2.0]] 105 | >>> matrix 106 | [[-1, -2, -3], [-4, -5, -6]] 107 | 108 | Check: div as negative: 109 | >>> matrix = [[1, 2, 3], [4, 5, 6]] 110 | >>> matrix_divided(matrix, -3) 111 | [[-0.33, -0.67, -1.0], [-1.33, -1.67, -2.0]] 112 | >>> matrix 113 | [[1, 2, 3], [4, 5, 6]] 114 | 115 | Check: empty matrix: 116 | >>> matrix = [] 117 | >>> matrix_divided(matrix, 1) 118 | [] 119 | >>> matrix 120 | [] 121 | 122 | Check: 1xn matrix: 123 | >>> matrix = [[1, 2, 3]] 124 | >>> matrix_divided(matrix, 2) 125 | [[0.5, 1.0, 1.5]] 126 | >>> matrix 127 | [[1, 2, 3]] 128 | 129 | Check: nx1 matrix: 130 | >>> matrix = [[1], [2], [3]] 131 | >>> matrix_divided(matrix, 2) 132 | [[0.5], [1.0], [1.5]] 133 | >>> matrix 134 | [[1], [2], [3]] 135 | 136 | Check: division by infinity: 137 | >>> matrix_divided(matrix, float('inf')) 138 | [[0.0], [0.0], [0.0]] 139 | 140 | Check: division with infinity in numerator: 141 | >>> matrix_divided([[1, float('inf'), 3], [4, 5, 6]], 1) 142 | [[1.0, inf, 3.0], [4.0, 5.0, 6.0]] 143 | 144 | Check: division with infinity in numerator and denomenator 145 | >>> matrix_divided([[0, 0, 0], [0, 0, 0]], float('inf')) 146 | [[0.0, 0.0, 0.0], [0.0, 0.0, 0.0]] 147 | -------------------------------------------------------------------------------- /0x08-python-more_classes/9-rectangle.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python3 2 | 3 | '''module: 9-rectangle 4 | this module contains the class Rectangle ... 5 | ''' 6 | 7 | 8 | class Rectangle: 9 | '''class: Rectangle 10 | this is an empty class, further additions in subsequent assignments 11 | ''' 12 | 13 | number_of_instances = 0 14 | print_symbol = "#" 15 | 16 | @classmethod 17 | def square(cls, size=0): 18 | '''class method: creates a square, which is a type of rectangle 19 | ''' 20 | return cls(size, size) 21 | 22 | @staticmethod 23 | def bigger_or_equal(rect_1, rect_2): 24 | '''static class method: bigger or equal 25 | Return: boolean - true if rect_1 >= rect_2, based on area(?) 26 | ''' 27 | if not isinstance(rect_1, Rectangle): 28 | raise TypeError("rect_1 must be an instance of Rectangle") 29 | if not isinstance(rect_2, Rectangle): 30 | raise TypeError("rect_2 must be an instance of Rectangle") 31 | if rect_1.area() >= rect_2.area(): 32 | return True 33 | else: 34 | return False 35 | 36 | def __init__(self, width=0, height=0): 37 | '''method: __init__ 38 | initialize instance of class Rectangle 39 | ''' 40 | Rectangle.number_of_instances += 1 41 | self.__width = width 42 | self.__height = height 43 | 44 | @property 45 | def width(self): 46 | '''method: set_width 47 | getter 48 | ''' 49 | if (not isinstance(self.__width, int)) or isinstance(self.__width, 50 | bool): 51 | raise TypeError("width must be an integer") 52 | if self.__width < 0: 53 | raise ValueError("width must be >= 0") 54 | return self.__width 55 | 56 | @width.setter 57 | def width(self, width): 58 | '''method: set_width 59 | setter 60 | ''' 61 | if not isinstance(self.__width, int) or isinstance(self.__width, bool): 62 | raise TypeError("width must be an integer") 63 | if self.__width < 0: 64 | raise ValueError("width must be >= 0") 65 | self.__width = width 66 | 67 | @property 68 | def height(self): 69 | '''method: set_height 70 | getter 71 | ''' 72 | if (not isinstance(self.__height, int)) or isinstance(self.__height, 73 | bool): 74 | raise TypeError("height must be an integer") 75 | if self.__height < 0: 76 | raise ValueError("height must be >= 0") 77 | return self.__height 78 | 79 | @height.setter 80 | def height(self, height): 81 | '''method: set_height 82 | setter 83 | ''' 84 | if not isinstance(self.__height, int) or isinstance(self.__height, 85 | bool): 86 | raise TypeError("height must be an integer") 87 | if self.__height < 0: 88 | raise ValueError("height must be >= 0") 89 | self.__height = height 90 | 91 | def area(self): 92 | '''method: area 93 | return area of rectangle 94 | ''' 95 | return self.__height * self.__width 96 | 97 | def perimeter(self): 98 | '''method: perimeter 99 | return perimeter of perimeter 100 | ''' 101 | if self.__height == 0 or self.width == 0: 102 | return 0 103 | return (self.__height + self.width) * 2 104 | 105 | def __str__(self): 106 | '''method: __str__ 107 | return: nice string representation of rectangle 108 | ''' 109 | ret_str = "" 110 | if self.__height == 0 or self.__width == 0: 111 | return "" 112 | for idx in range(self.__height): 113 | ret_str += str(self.print_symbol) * self.width 114 | if idx + 1 < self.__height: 115 | ret_str += '\n' 116 | return ret_str 117 | 118 | def __repr__(self): 119 | '''method: __repr__ 120 | return: representation of rectangle that can be used by eval() to 121 | create new object 122 | ''' 123 | ret_str = "Rectangle(" + str(self.__width) + "," 124 | ret_str += str(self.__height) + ")" 125 | return ret_str 126 | 127 | def __del__(self): 128 | '''method: __del__ 129 | deletes instance of Rectangle class, and prints "bye" message 130 | ''' 131 | Rectangle.number_of_instances -= 1 132 | print("Bye rectangle...") 133 | --------------------------------------------------------------------------------