From 816f9d826107d3df83780f52530ed40d5365a130 Mon Sep 17 00:00:00 2001 From: codecademydev Date: Sun, 29 Dec 2024 13:05:53 +0000 Subject: [PATCH 01/31] =?UTF-8?q?=F0=9F=A4=96=20update=20concept=20of=20th?= =?UTF-8?q?e=20week?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- bin/concept-of-the-week.txt | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/bin/concept-of-the-week.txt b/bin/concept-of-the-week.txt index d1c5b89855e..310bf96da85 100644 --- a/bin/concept-of-the-week.txt +++ b/bin/concept-of-the-week.txt @@ -1 +1 @@ -content/c/concepts/user-input/user-input.md \ No newline at end of file +content/general/concepts/jit-compilation/jit-compilation.md \ No newline at end of file From 37bb0d5e7fade8b2077f7f3d3e9d108a9f79edbb Mon Sep 17 00:00:00 2001 From: Pragati Verma Date: Thu, 2 Jan 2025 16:13:57 +0530 Subject: [PATCH 02/31] [Concept Entry] Python: Packages (#5831) * Add package entry * Update content/python/concepts/packages/packages.md --------- --- content/python/concepts/packages/packages.md | 104 +++++++++++++++++++ 1 file changed, 104 insertions(+) create mode 100644 content/python/concepts/packages/packages.md diff --git a/content/python/concepts/packages/packages.md b/content/python/concepts/packages/packages.md new file mode 100644 index 00000000000..dd80476b349 --- /dev/null +++ b/content/python/concepts/packages/packages.md @@ -0,0 +1,104 @@ +--- +Title: 'Packages' +Description: 'Packages are a way to organize related modules into a directory hierarchy in Python.' +Subjects: + - 'Computer Science' + - 'Data Science' +Tags: + - 'Command Line' + - 'Packages' +CatalogContent: + - 'learn-python-3' + - 'paths/computer-science' +--- + +In Python, **packages** are a way to organize related modules into a directory hierarchy. Packages allow for modular code organization, making projects more readable, reusable, and maintainable. A package is essentially a directory that contains a special `__init__.py` file and one or more modules (Python files). + +Packages are particularly useful for: + +- Grouping related functionality. +- Avoiding module name conflicts in larger codebases. +- Providing a clear project structure. + +## Syntax + +The structure of a Python package typically looks like this: + +```pseudo +project_name/ + package_name/ + __init__.py # Marks the directory as a package (can be empty or include initialization code) + module1.py # First module in the package + module2.py # Second module in the package + main.py # Main program +``` + +- The `__init__.py` file is required to make Python treat the directory as a package. +- Modules (`.py` files) inside the package can be imported and used in other parts of the project. + +### Importing a Package + +To use a package or its modules, the syntax is: + +```pseudo +import package_name.module_name + +# OR +from package_name import module_name + +# OR (import specific functions or classes) +from package_name.module_name import function_name, class_name +``` + +## Example + +Here’s an example that creates and uses a Python package: + +### Creating a Python Package + +Create a directory with following files: + +```shell +mypackage/ + __init__.py + module1.py + module2.py +``` + +- `__init__.py`: This file is used to indicate that the directory `mypackage` is a package. It can be empty or contain initialization code for the package. + +- `module1.py`: A module within the package that could contain functions or classes. + +```py +# module1.py +def greet(name): + return f"Hello, {name}!" +``` + +- `module2.py`: Another module within the package. + +```py +# module2.py +def farewell(name): + return f"Goodbye, {name}!" +``` + +### Using the Package + +The package and its modules can then be used in another Python script like this: + +```py +# test_package.py +import mypackage.module1 as m1 +import mypackage.module2 as m2 + +print(m1.greet("Alice")) +print(m2.farewell("Alice")) +``` + +The output of the above code will be as follows: + +```shell +Hello, Alice! +Goodbye, Alice! +``` From a6ff03d2c951270bbe34a6df4d6a253ef780e4ad Mon Sep 17 00:00:00 2001 From: Pragati Verma Date: Thu, 2 Jan 2025 16:44:37 +0530 Subject: [PATCH 03/31] [Concept Entry] Pandas: Pivot Tables (#5830) * Add pandas pivot table entry * Minor edits * Add codebyte example * Update content/pandas/concepts/pivot-tables/pivot-tables.md * Update content/pandas/concepts/pivot-tables/pivot-tables.md * Update content/pandas/concepts/pivot-tables/pivot-tables.md * Update content/pandas/concepts/pivot-tables/pivot-tables.md --------- --- .../concepts/pivot-tables/pivot-tables.md | 153 ++++++++++++++++++ 1 file changed, 153 insertions(+) create mode 100644 content/pandas/concepts/pivot-tables/pivot-tables.md diff --git a/content/pandas/concepts/pivot-tables/pivot-tables.md b/content/pandas/concepts/pivot-tables/pivot-tables.md new file mode 100644 index 00000000000..65baedcf1ca --- /dev/null +++ b/content/pandas/concepts/pivot-tables/pivot-tables.md @@ -0,0 +1,153 @@ +--- +Title: 'Pivot Tables' +Description: 'Pivot tables are a data summarization tool in Pandas that allow reshaping and aggregating tabular data for analysis.' +Subjects: + - 'Computer Science' + - 'Data Science' +Tags: + - 'Data Structures' + - 'Pandas' +CatalogContent: + - 'learn-python-3' + - 'paths/data-science' +--- + +**Pivot tables** in [Pandas](https://www.codecademy.com/resources/docs/pandas) are a data summarization tool that perform operations such as aggregation, grouping, and reshaping of tabular data based on specific criteria, making it easier to derive meaningful insights. + +## Syntax + +The general syntax for creating a pivot table in Pandas is: + +```pseudo +pandas.pivot_table(data, values=None, index=None, columns=None, aggfunc='mean', fill_value=None, margins=False, dropna=True, margins_name='All') +``` + +- `data`: The input DataFrame. +- `values`: The column(s) to aggregate. +- `index`: Column(s) to group data by (rows). +- `columns`: Column(s) to group data by (columns). +- `aggfunc`: The aggregation function(s) (default is `mean`). +- `fill_value`: Value to replace `NaN`s. +- `margins`: Add subtotals (row/column totals). +- `margins_name`: Name for row/column totals. +- `dropna`: Whether to drop columns with `NaN` values. + +## Example + +Consider the following DataFrame: + +```py +import pandas as pd + +data = { + 'Region': ['North', 'South', 'East', 'West', 'North', 'South'], + 'Category': ['A', 'A', 'B', 'B', 'A', 'B'], + 'Sales': [100, 150, 200, 130, 120, 180] +} + +df = pd.DataFrame(data) +print(df) +``` + +The output for the above code will be as follows: + +| Region | Category | Sales | +| ------ | -------- | ----- | +| North | A | 100 | +| South | A | 150 | +| East | B | 200 | +| West | B | 130 | +| North | A | 120 | +| South | B | 180 | + +### Pivoting Data + +To summarize total sales by **Region** and **Category**: + +```py +pivot = pd.pivot_table(df, values='Sales', index='Region', columns='Category', aggfunc='sum', fill_value=0) +print(pivot) +``` + +The output of the above code will be as follows: + +| Category | A | B | +| -------- | --- | --- | +| East | 0 | 200 | +| North | 220 | 0 | +| South | 150 | 180 | +| West | 0 | 130 | + +### Adding Margins for Totals + +To include row and column totals in the pivot table, set `margins=True`: + +```py +pivot = pd.pivot_table(df, values='Sales', index='Region', columns='Category', aggfunc='sum', fill_value=0, margins=True) +print(pivot) +``` + +The output of the above code will be as follows: + +| Category | A | B | All | +| -------- | --- | --- | --- | +| East | 0 | 200 | 200 | +| North | 220 | 0 | 220 | +| South | 150 | 180 | 330 | +| West | 0 | 130 | 130 | +| All | 370 | 510 | 880 | + +### Aggregating with Multiple Functions + +Multiple aggregation functions can be applied using a list: + +```py +pivot = pd.pivot_table(df, values='Sales', index='Region', columns='Category', aggfunc=['sum', 'mean'], fill_value=0) +print(pivot) +``` + +The output of the above code will be as follows: + +| | sum | | mean | | +| ------ | --- | --- | ----- | ----- | +| Region | A | B | A | B | +| East | 0 | 200 | 0.0 | 200.0 | +| North | 220 | 0 | 110.0 | 0.0 | +| South | 150 | 180 | 150.0 | 180.0 | +| West | 0 | 130 | 0.0 | 130.0 | + +## Codebyte Example + +Run the following example to see how pivot tables can be used to aggregate `Quantity` by `Category` and `Region`: + +```codebyte/python +import pandas as pd + +# Sample data +data = { + 'Category': ['Electronics', 'Electronics', 'Clothing', 'Clothing', 'Electronics', 'Clothing'], + 'Sub-Category': ['Phones', 'Laptops', 'Shirts', 'Shirts', 'Phones', 'Pants'], + 'Region': ['North', 'South', 'North', 'East', 'East', 'South'], + 'Quantity': [2, 3, 4, 1, 3, 2], + 'Discount': [0.1, 0.2, 0.15, 0.1, 0.25, 0.05] +} + +# Create a DataFrame +df = pd.DataFrame(data) + +print("Original DataFrame:") +print(df) + +# Create a pivot table to aggregate 'Quantity' by 'Category' and 'Region' +pivot_table = pd.pivot_table( + df, + values='Quantity', # Column to aggregate + index='Category', # Rows + columns='Region', # Columns + aggfunc=['sum', 'mean'], # Aggregation functions + fill_value=0 # Replace NaN with 0 +) + +print("\nPivot Table Aggregating 'Quantity' with Sum and Mean:") +print(pivot_table) +``` From 87f6b861add93c74e162f26435ad47dd47e2cc1f Mon Sep 17 00:00:00 2001 From: Dani Tellini Date: Thu, 2 Jan 2025 13:45:57 -0300 Subject: [PATCH 04/31] Concept Entry: Git - Amend (#5834) * metadata entered * draft amend entry - ready for pr * check fail fix * Update amend.md * Update amend.md minor fixes * Update amend.md --------- --- content/git/concepts/amend/amend.md | 91 +++++++++++++++++++++++++++++ 1 file changed, 91 insertions(+) create mode 100644 content/git/concepts/amend/amend.md diff --git a/content/git/concepts/amend/amend.md b/content/git/concepts/amend/amend.md new file mode 100644 index 00000000000..95b45f397b0 --- /dev/null +++ b/content/git/concepts/amend/amend.md @@ -0,0 +1,91 @@ +--- +Title: 'Amend' +Description: 'Modifies the most recent Git commit without creating a new one.' +Subjects: + - 'Bash/Shell' + - 'Developer Tools' +Tags: + - 'Command Line' + - 'Documentation' + - 'Error Handling' + - 'Git' +CatalogContent: + - 'learn-git' + - 'paths/computer-science' +--- + +**Amend** is a Git feature that allows developers to modify the most recent commit. It is commonly used to correct mistakes such as adding a missing file, fixing an incorrect commit message, or making minor adjustments without creating an entirely new commit. + +This feature is particularly helpful for maintaining a clean and concise commit history, ensuring that changes are logically grouped and easy to understand. + +## Syntax + +The syntax for using the amend feature in Git is: + +```pseudo +git commit --amend +``` + +To amend both the content of the commit and the commit message, the following would be used: + +```pseudo +git commit --amend -m "Your new commit message" +``` + +## Example 1 + +Suppose, the developer created and committed a feature, but forgot to include a file: + +```shell +# Original commit +echo "Initial code" > feature.txt +echo "Forgotten content" > forgotten-file.txt +git add feature.txt # Dev forgot to add forgotten-file.txt +git commit -m "Add initial code for the feature" +``` + +Here's the original commit history: + +```shell +git log --oneline +abc1234 Add initial code for the feature +``` + +The developer realized that he hasn't included a file in the original commit. So, he performs the amend operation to both include the file in that commit and change the commit message: + +```shell +# Amending the original commit +git add forgotten-file.txt +git commit --amend -m "Add initial code for the feature and forgotten file" +``` + +Here's the amended commit history: + +```shell +git log --oneline +def5678 Add initial code for the feature and forgotten file # Commit abc1234 has been replaced by def5678 +``` + +## Example 2 + +Suppose, the developer is going through another commit history: + +```shell +git log --oneline +abc1234 Original commit message +``` + +While going through it, the developer didn't like the above commit message. So, he decides to use the amend operation to only change the commit message without touching the contents of the commit: + +```shell +git commit --amend -m "Corrected commit message" +``` + +Here's the amended commit history: + +```shell +git log --oneline +abc1234 Corrected commit message +``` + +> **Note:** Use `git commit --amend` carefully if the commit has already been shared with others, as it rewrites history. From e7eed0b33b81e5e0d67c20510deb3167a4c878f3 Mon Sep 17 00:00:00 2001 From: codecademydev Date: Sun, 5 Jan 2025 13:06:17 +0000 Subject: [PATCH 05/31] =?UTF-8?q?=F0=9F=A4=96=20update=20concept=20of=20th?= =?UTF-8?q?e=20week?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- bin/concept-of-the-week.txt | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/bin/concept-of-the-week.txt b/bin/concept-of-the-week.txt index 310bf96da85..4829c2f3c48 100644 --- a/bin/concept-of-the-week.txt +++ b/bin/concept-of-the-week.txt @@ -1 +1 @@ -content/general/concepts/jit-compilation/jit-compilation.md \ No newline at end of file +content/r/concepts/built-in-functions/built-in-functions.md \ No newline at end of file From b7624d0e5404cfa093c248769bf7ee904bb50302 Mon Sep 17 00:00:00 2001 From: John Rood Date: Mon, 6 Jan 2025 16:24:44 -0600 Subject: [PATCH 06/31] Check to verify that there are not missing md files (#5553) * Github check to verify that there are not missing md files * linebreaks --- .github/scripts/validate-content-tree.js | 22 ++++++++++++++++++++++ .github/workflows/push.yml | 2 +- package.json | 3 ++- 3 files changed, 25 insertions(+), 2 deletions(-) create mode 100644 .github/scripts/validate-content-tree.js diff --git a/.github/scripts/validate-content-tree.js b/.github/scripts/validate-content-tree.js new file mode 100644 index 00000000000..98386de582a --- /dev/null +++ b/.github/scripts/validate-content-tree.js @@ -0,0 +1,22 @@ +const { readdirSync } = require('node:fs'); + +let exitCode = 0; + +const next = ['concepts', 'terms']; + +function checkPath(path, i) { + for (const entry of readdirSync(path)) { + const entryDir = readdirSync(`${path}/${entry}`); + if (!entryDir.includes(`${entry}.md`)) { + console.error(`\n${path}/${entry} should contain a ${entry}.md file\n`); + exitCode = 1; + } + if (i < 2 && entryDir.includes(next[i])) { + checkPath(`${path}/${entry}/${next[i]}`, i + 1); + } + } +} + +checkPath('content', 0); + +process.exit(exitCode); diff --git a/.github/workflows/push.yml b/.github/workflows/push.yml index c666a7e3c87..10609797248 100644 --- a/.github/workflows/push.yml +++ b/.github/workflows/push.yml @@ -11,7 +11,7 @@ jobs: strategy: fail-fast: false matrix: - command: ["compile", "format:verify", "lint:js", "lint:md", "test"] + command: ["compile", "format:verify", "lint:js", "lint:md", "test", "validate-content-tree"] on: push: diff --git a/package.json b/package.json index d1c0b64275a..25ccb7da153 100644 --- a/package.json +++ b/package.json @@ -36,7 +36,8 @@ "lint:md": "markdownlint \"./content/**/*.md\"", "lint": "yarn lint:md && yarn lint:js", "test": "jest", - "prepare": "husky install" + "prepare": "husky install", + "validate-content-tree": "node .github/scripts/validate-content-tree.js" }, "license": "UNLICENSED", "version": "1.0.0" From f5d5c1b80b8aa327efe46ea9cf76e5934ff1888a Mon Sep 17 00:00:00 2001 From: Nil-Morah <172632764+Nil-Morah@users.noreply.github.com> Date: Tue, 7 Jan 2025 07:14:29 +0100 Subject: [PATCH 07/31] Volatile variables (#5721) * volatile-variables file created and filled, examples pending * Created volatile variable term for cpp variables * File has been added. * File has been modified. * minor changes * Fixes --------- --- .../volatile-variables/volatile-variables.md | 59 +++++++++++++++++++ 1 file changed, 59 insertions(+) create mode 100644 content/cpp/concepts/variables/terms/volatile-variables/volatile-variables.md diff --git a/content/cpp/concepts/variables/terms/volatile-variables/volatile-variables.md b/content/cpp/concepts/variables/terms/volatile-variables/volatile-variables.md new file mode 100644 index 00000000000..7501d2e6819 --- /dev/null +++ b/content/cpp/concepts/variables/terms/volatile-variables/volatile-variables.md @@ -0,0 +1,59 @@ +--- +Title: 'Volatile Variables' +Description: 'Ensures variables avoid compiler optimization, allowing correct access when their values may change due to external factors.' +Subjects: + - 'Computer Science' + - 'Code Foundations' +Tags: + - 'Memory' + - 'Variables' + - 'Variable Types' +CatalogContent: + - 'learn-c-plus-plus' + - 'paths/computer-science' +--- + +**Volatile variables** in C++ are not optimized or cached by the compiler. Marking a variable as volatile is appropriate when its value may be altered by external factors beyond the program's control. This instructs the compiler to read the most recent value from memory instead of a potentially outdated cached version. However, it's important to note that declaring a variable as volatile does not ensure atomicity or synchronize memory between threads; it solely prevents compiler optimization, which is particularly crucial in multithreaded environments. + +## Syntax + +To declare a variable as volatile, the `volatile` keyword needs to be placed before the variable type: + +```pseudo +volatile data_type variable_name; +``` + +## Example + +A volatile variable signals a worker thread to stop running and performing tasks in the following example. The `volatile` keyword prevents the compiler from optimizing away, continuously checking the variable while in the loop. The worker thread will continue until the `isRunning` variable is false. + +```cpp +#include +#include +#include +class VolatileExample { +private: + // 'volatile' tells the compiler not to optimize this variable, ensuring that each iteration of the following loop fetches the latest value. + volatile bool isRunning = true; +public: + void runTask() { + while (isRunning) { + std::cout << "Task is running..." << std::endl; + std::this_thread::sleep_for(std::chrono::seconds(1)); + } + std::cout << "Task has stopped." << std::endl; + } + void stopTask() { + isRunning = false; // Changing 'isRunning' to false to stop the task. + } +}; +int main() { + VolatileExample example; + std::thread workerThread(&VolatileExample::runTask, &example); + // The task runs for a while before stopping it. + std::this_thread::sleep_for(std::chrono::seconds(5)); + example.stopTask(); // Stop the task + workerThread.join(); // Waits for the thread to finish. + return 0; +} +``` From 70c3df1c02f260bf46dbd62d6524a6629980331f Mon Sep 17 00:00:00 2001 From: Tommaso Berti <152935267+tommaso-berti@users.noreply.github.com> Date: Tue, 7 Jan 2025 07:39:00 +0100 Subject: [PATCH 08/31] feat: [Concept Entry] Git Checkout (#5748) (#5769) * feat: [Concept Entry] Git Checkout (#5748) * Update content/git/concepts/checkout/checkout.md Co-authored-by: Pragati Verma * Update content/git/concepts/checkout/checkout.md Co-authored-by: Pragati Verma * Update content/git/concepts/checkout/checkout.md Co-authored-by: Pragati Verma * Update content/git/concepts/checkout/checkout.md Co-authored-by: Pragati Verma * Update content/git/concepts/checkout/checkout.md Co-authored-by: Pragati Verma * Update content/git/concepts/checkout/checkout.md Co-authored-by: Pragati Verma * Update content/git/concepts/checkout/checkout.md Co-authored-by: Pragati Verma * Apply suggestions from code review Co-authored-by: Pragati Verma * feat: [Concept Entry] Git Checkout (#5748): added optional flags * Update options syntax * Update checkout.md * fix: [Bug/Error] Java Map: .replaceAll() (Codecademy#5748) * revert wrong commit on feat branch * Minor fixes * Formatting fixes --------- --- content/git/concepts/checkout/checkout.md | 76 +++++++++++++++++++++++ 1 file changed, 76 insertions(+) create mode 100644 content/git/concepts/checkout/checkout.md diff --git a/content/git/concepts/checkout/checkout.md b/content/git/concepts/checkout/checkout.md new file mode 100644 index 00000000000..b023674d34d --- /dev/null +++ b/content/git/concepts/checkout/checkout.md @@ -0,0 +1,76 @@ +--- +Title: 'Checkout' +Description: 'The git checkout command switches, creates and restores branches in the working directory to a specific state.' +Subjects: + - 'Bash/Shell' + - 'Developer Tools' +Tags: + - 'Git' + - 'GitHub' +CatalogContent: + - 'learn-git' + - 'learn-the-command-line' + - 'paths/computer-science' +--- + +The **`git checkout`** command switches, creates and restores branches in the working directory to a specific state. The `git checkout` command also allows switching to a specific commit without changing branches. + +## Syntax + +Checkout with branches: + +```pseudo +git checkout [options] +``` + +- `` specifies the name of the branch to switch to or create. +- `[options]` optional flags that can be used with the checkout command. Here are some of the most commonly used options: + - `-b` creates a new branch with the specified name and switches to it immediately. + - `-` returns to the previously checked-out branch. This flag does not need the ``. + - `-f` (--force) forces the checkout, discarding any local changes in the working directory. + +Checkout to a specific commit: + +```pseudo +git checkout +``` + +## Switch to an existing branch + +The following command will switch to an already existing branch, created previously with the [git branch](https://www.codecademy.com/resources/docs/git/branch) command: + +```pseudo +git checkout existing-branch +``` + +> **Note**: From Git 2.23, the new specific `git switch` command has been introduced to switch branches, making it clearer and safer than `git checkout` because it avoids the ambiguity of the latter's multi-purpose nature. + +## Create and switch to a new branch + +It is possible to create and switch to a new branch with a single command using the `-b` option: + +```pseudo +git checkout -b new-branch +``` + +## Restore a file from a specific commit + +`git checkout` also allows to restore a file from a specific commit using its hash: + +```pseudo +git checkout -- example.txt +``` + +## Examine a Previous Commit + +`git checkout` also allows temporarily moving to a specific commit without changing branches. This state is called **detached `HEAD` state**: + +```pseudo +git checkout +``` + +The detached `HEAD` state allows to: + +- Examine the state of the repository at that specified commit. +- Create new branches if the developer needs to start from that point. +- Any code changes made in this state will not be associated with any existing branch unless a new branch is created. From 934f2b9f4ebe989f733d7063ee047f16530c6e00 Mon Sep 17 00:00:00 2001 From: John Rood Date: Tue, 7 Jan 2025 09:26:26 -0600 Subject: [PATCH 09/31] Update post-merge copy (#5922) --- .github/workflows/post-merge-messages.yml | 3 +-- 1 file changed, 1 insertion(+), 2 deletions(-) diff --git a/.github/workflows/post-merge-messages.yml b/.github/workflows/post-merge-messages.yml index 3355c834b32..202ee23781a 100644 --- a/.github/workflows/post-merge-messages.yml +++ b/.github/workflows/post-merge-messages.yml @@ -43,7 +43,6 @@ jobs: ${{ env.urls }} Please note it may take a little while for changes to become visible. - If you're appearing as anonymous and want to be credited, see [here](https://discuss.codecademy.com/t/my-contribution-is-live-but-im-not-being-shown-as-a-contributor-why-is-this/758036). + If you're appearing as anonymous and want to be credited, visit the [linked accounts](https://www.codecademy.com/account/linked_accts) page and ensure that your GitHub account is linked. issuesClosed: | 🌸 Thanks for closing this Issue! - Please head over to the [Docs Forum](https://discuss.codecademy.com/c/community/community-docs/2205) if you have any questions about Docs, or reply to the thread on [Possible Content Discussion](https://discuss.codecademy.com/t/find-a-starting-point-possible-content-discussion/745868) to share ideas and collaborate with other contributors, maintainers, or super users to determine good future issues that will help expand Docs! From 6cf99d185e3cf39fe032c19b7f531fc9ee74b73f Mon Sep 17 00:00:00 2001 From: Valeriy Anysenko <168164564+vlrnsnk@users.noreply.github.com> Date: Tue, 7 Jan 2025 12:56:41 -0500 Subject: [PATCH 10/31] Update json.md (#5891) Remove trailing commas on pseudocode JSON --- content/general/concepts/json/json.md | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/content/general/concepts/json/json.md b/content/general/concepts/json/json.md index 6758ebe3c9c..f05f1e055da 100644 --- a/content/general/concepts/json/json.md +++ b/content/general/concepts/json/json.md @@ -36,7 +36,7 @@ More can be learned about JSON by visiting [json.org](https://www.json.org/). { "propertyOne": "valueOne", "propertyTwo": "valueTwo", - "propertyThree": "valueThree", + "propertyThree": "valueThree" } ``` @@ -60,12 +60,12 @@ Multiple JSON objects can be collected in an array-like sequence: { "propertyOne": "valueOne", "propertyTwo": "valueTwo", - "propertyThree": "valueThree", + "propertyThree": "valueThree" }, { "propertyA": "valueA", "propertyB": "valueB", - "propertyC": "valueC", + "propertyC": "valueC" } ] ``` From 6d2f3d2d517053f323334cda23b445985dfafd32 Mon Sep 17 00:00:00 2001 From: Savi Dahegaonkar <124272050+SaviDahegaonkar@users.noreply.github.com> Date: Wed, 8 Jan 2025 12:00:00 +0530 Subject: [PATCH 11/31] [Term Entry] Python statsmodels: anova_lm() (#5907) * New file has been added. * Update user-input.md * Update user-input.md * File has been modified. * Update anova-lm.md major fixes in meta data and some content * Update anova-lm.md --------- --- .../statsmodels/terms/anova-lm/anova-lm.md | 63 +++++++++++++++++++ 1 file changed, 63 insertions(+) create mode 100644 content/python/concepts/statsmodels/terms/anova-lm/anova-lm.md diff --git a/content/python/concepts/statsmodels/terms/anova-lm/anova-lm.md b/content/python/concepts/statsmodels/terms/anova-lm/anova-lm.md new file mode 100644 index 00000000000..e63d6e6bc7f --- /dev/null +++ b/content/python/concepts/statsmodels/terms/anova-lm/anova-lm.md @@ -0,0 +1,63 @@ +--- +Title: 'anova_lm' +Description: 'Performs an analysis of variance (ANOVA) on one or more fitted linear models to assess their goodness-of-fit and compare their explanatory power.' +Subjects: + - 'Data Science' + - 'Machine Learning' +Tags: + - 'Python' + - 'Statsmodels' +CatalogContent: + - 'learn-python-3' + - 'paths/data-science' +--- + +**`anova_lm()`** is the function in Python's [`statsmodels`](https://www.codecademy.com/resources/docs/python/statsmodels) library that produces an ANOVA table for one or more fitted linear models. ANOVA (Analysis of Variance) is a statistical method used to determine whether there are significant differences between the means of three or more groups. Researchers and analysts can use `anova_lm()` to evaluate the effects of categorical variables on a continuous outcome and compare nested linear models to assess their relative explanatory power. + +## Syntax + +```pseudo +statsmodels.stats.anova.anova_lm(*args, **kwargs) +``` + +- `*args`: One or more fitted model results (e.g., instances of `OLS` model results) to perform ANOVA on. +- `**kwargs`: Optional keyword arguments to customize the ANOVA test, such as: + - `scale`: Specifies the scale parameter. + - `test`: Type of test (e.g., 'F' for F-test). + - `typ`: Specifies the type of sum of squares to calculate (e.g., Type I, II, or III). + - `robust`: If `True`, performs a robust ANOVA. + +## Example + +This example demonstrates how to use the `anova_lm()` function in the `statsmodels` library to perform analysis of variance on a fitted linear model: + +```py +import statsmodels.api as sm +from statsmodels.formula.api import ols +from statsmodels.stats.anova import anova_lm +import pandas as pd + +# Load example data +data = sm.datasets.get_rdataset('iris').data + +# Rename columns to make them Python-friendly +data.rename(columns=lambda x: x.replace('.', '_'), inplace=True) + +# Fit a linear regression model using Ordinary Least Squares (OLS) +model = ols('Sepal_Length ~ Petal_Length + Petal_Width', data=data).fit() + +# Perform ANOVA on the fitted model +anova_results = anova_lm(model, typ=2) + +# Print the ANOVA table +print(anova_results) +``` + +The ANOVA table produced shows the sum of squares, degrees of freedom, F-statistics, and p-values, helping to evaluate the significance of each predictor in the model: + +```shell + sum_sq df F PR(>F) +Petal_Length 9.934196 1.0 61.150938 9.414477e-13 +Petal_Width 0.644340 1.0 3.966300 4.827246e-02 +Residual 23.880694 147.0 NaN NaN +``` From 583a11f3030c1c5c02d50f1beff6290993090574 Mon Sep 17 00:00:00 2001 From: Sudharshanan <71761488+Maverick073@users.noreply.github.com> Date: Wed, 8 Jan 2025 12:38:22 +0530 Subject: [PATCH 12/31] Added docs for javascript spread operator - #5802 (#5827) * Added docs for javascript spread operator * Update spread-operator.md fixes done * Update spread-operator.md * Update content/javascript/concepts/spread-operator/spread-operator.md * Update content/javascript/concepts/spread-operator/spread-operator.md * Update content/javascript/concepts/spread-operator/spread-operator.md --------- --- .../spread-operator/spread-operator.md | 91 +++++++++++++++++++ 1 file changed, 91 insertions(+) create mode 100644 content/javascript/concepts/spread-operator/spread-operator.md diff --git a/content/javascript/concepts/spread-operator/spread-operator.md b/content/javascript/concepts/spread-operator/spread-operator.md new file mode 100644 index 00000000000..d69bfef4d62 --- /dev/null +++ b/content/javascript/concepts/spread-operator/spread-operator.md @@ -0,0 +1,91 @@ +--- +Title: 'Spread Operator' +Description: 'Expands elements of an array, object, or iterable in JavaScript.' +Subjects: + - 'Computer Science' + - 'Web Development' +Tags: + - 'Arrays' + - 'Functions' + - 'Objects' + - 'Spread Operator' +CatalogContent: + - 'introduction-to-javascript' + - 'paths/front-end-engineer-career-path' +--- + +The **Spread Operator** in JavaScript, represented by three dots (`...`), is used to expand or unpack elements of arrays, objects, or other iterables into individual elements. + +The spread operator performs a shallow copy, meaning that for nested objects or arrays, changes in the copied object/array might reflect in the original. + +## Syntax + +The syntax of spread operator for arrays is as follows: + +```pseudo +const nums = [...nums1 , ...nums2] // arrays +``` + +The syntax of spread operator for objects is as follows: + +```pseudo +const obj = {...obj1, ...obj2} // objects +``` + +- `nums1` and `nums2` are arrays. They represent any two arrays that need to be merged into a single array. +- `obj1` and `obj2` are objects. They represent two objects that should be combined into one. + +## Example + +The following example demonstrates how to use the spread operator: + +```js +const nums1 = [1, 2, 3]; +const nums2 = [4, 5, 6]; +const nums = [...nums1, ...nums2]; +console.log(nums); + +const obj1 = { name: 'Subro' }; +const obj2 = { age: 22 }; +const obj = { ...obj1, ...obj2 }; +console.log(obj); +``` + +This example results in the following output: + +```shell +[1, 2, 3, 4, 5, 6] +{ name: 'Subro', age: 22 } +``` + +## Codebyte Example + +Run the codebyte example below to understand how the spread operator works: + +```codebyte/javascript +function sum(a, b, c) { + return a + b + c; +} + +const numbers = [1, 2, 3]; +console.log(sum(...numbers)); + +// Original object with nested data +const originalObj = { + name: 'Subro', + address: { + city: 'Lalaland', + zip: '12345' + } +}; + +// Creating a shallow copy using the spread operator +const shallowCopyObj = { ...originalObj }; + +// Modifying the nested object in the copy +shallowCopyObj.address.city = 'Wonderland'; + +console.log('Shallow Copy:', shallowCopyObj); +console.log('Original Object:', originalObj); +// The nested 'address' object is shared between the original and the shallow copy, so modifying it affects both objects. +``` From 7340800a504df225c17b7c2abc59c00ccc242f19 Mon Sep 17 00:00:00 2001 From: ebikatsudon <99709771+ebikatsudon@users.noreply.github.com> Date: Tue, 7 Jan 2025 23:44:29 -0800 Subject: [PATCH 13/31] [Edit] Combine Duplicate Focus Group Entries (#5829) * merged conflicting focus group entries into one * updated to fix formatting errors * Revert yarn.lock changes * Revert yarn.lock changes * Revert yarn.lock changes * Revert yarn.lock changes * Update focus-group.md * Update focus-group.md * Update focus-group.md * Update focus-group.md --------- --- .../uiux/concepts/focus-group/focus-group.md | 57 +++++++++++-------- .../concepts/focus-groups/focus-groups.md | 29 ---------- 2 files changed, 34 insertions(+), 52 deletions(-) delete mode 100644 content/uiux/concepts/focus-groups/focus-groups.md diff --git a/content/uiux/concepts/focus-group/focus-group.md b/content/uiux/concepts/focus-group/focus-group.md index eb4139d180a..9569f48dad8 100644 --- a/content/uiux/concepts/focus-group/focus-group.md +++ b/content/uiux/concepts/focus-group/focus-group.md @@ -1,10 +1,10 @@ --- Title: 'Focus Group' -Description: 'A qualitative attitudinal research method used to anticipate user needs and wants through direct interaction with possible users.' +Description: 'A qualitative research method that involves asking questions to a small group of users to obtain feedback on a topic, product, or design.' Subjects: - 'Web Design' Tags: - - 'Methods' + - 'Design' - 'UI' - 'UX' CatalogContent: @@ -12,32 +12,43 @@ CatalogContent: - 'paths/front-end-engineer-career-path' --- -The **Focus Group** is a powerful method used in Human-Computer Interaction (HCI) and User Experience (UX) design for User Research. It serves as a means to gather insights from users before and after the development of the product. As focus groups are a self-reported method of user research, they only help gauge users' perspectives of their wants, needs, and actions. So, they are an inaccurate representation of users' actions and thoughts. Focus groups follow the following pattern: +**Focus groups** are a [user research method](https://www.codecademy.com/resources/docs/uiux/user-research) in which a moderator guides a group of participants (typically 4-12 users) through a series of questions about a topic, product, or design. These questions help researchers understand the in-depth motivations and thought processes behind the user experience. Because the data is self-reported by users, focus groups are also considered an [attitudinal research method](https://www.codecademy.com/resources/docs/uiux/attitudinal-research). Some fields of study that utilize focus groups are market research, Human-Computer Interaction (HCI), and [User Experience (UX) Design](https://www.codecademy.com/resources/docs/uiux/ux-design). -## Steps in Focus Groups +Focus groups can be more cost- and time-efficient compared to one-on-one [interviews](https://www.codecademy.com/resources/docs/uiux/interviews), as researchers can gather feedback from a diverse group of participants all at once. The real-time group dynamic of focus groups may also encourage participants to open up and share their thoughts more than they would with other methodologies, such as [surveys](https://www.codecademy.com/resources/docs/uiux/surveys). -A typical focus group involves: +The following are some examples of qualitative data that can be obtained through focus groups: -- **Selection of Participants:** Carefully select a diverse group of participants representing the target user demographic. -- **Preparation of Materials:** Prepare prototypes, wireframes, or design concepts for participants to evaluate. -- **Facilitation:** A skilled facilitator guides the discussion, encouraging participants to express their thoughts, opinions, and concerns. -- **Observation:** Designers and stakeholders observe the session, taking notes on participant reactions and comments. -- **Post-Session Analysis:** Analyze the collected data to derive actionable insights for design improvements. +- **User Perspectives:** How users interact with or think about a product or service. +- **User Feedback:** Direct feedback on design elements, usability, and overall user experience. +- **Pain Points:** Any challenges or difficulties users may face when using a product. +- **Design Improvements:** User-driven suggestions on how a product or concept could be improved. -## About Focus Groups +## Focus Group Methodology -The purpose of focus groups is given below: +A typical focus group involves the following steps: -- **Understand User Perspectives:** Gain a deeper understanding of how users interact with a product or service. -- **Collect Feedback:** Obtain direct feedback on design elements, usability, and overall user experience. -- **Identify Pain Points:** Identify pain points and challenges users may face during interaction. -- **Generate Ideas:** Stimulate creative thinking and generate new design ideas. -- **Validate Design Decisions:** Validate design decisions through user opinions and preferences. +1. **Participant Selection:** Researchers select a diverse group of users representing the target demographic, usually through a screening process. +2. **Preparation of Materials:** Researchers prepare materials such as prototypes, wireframes, or design concepts for evaluation. +3. **Facilitation:** During the focus group, a moderator guides the discussion and encourages participants to express their thoughts, opinions, and concerns. +4. **Observation:** Researchers observe the session, noting participants' reactions and feedback. +5. **Post-Session Analysis:** Researchers analyze the collected data to derive actionable insights for design improvements. -The best practices to follow while conducting focus groups are: +A focus group may also integrate activities like collaging, drawing, brainstorming with sticky notes, card-sorting, or role-playing to increase participant engagement and break away from the standard question-and-answer format. -- **Diversity Matters:** Ensure participants represent diverse demographics, including age, gender, and technological proficiency. -- **Clear Objectives:** Define clear objectives for the focus group to guide discussions effectively. -- **Neutral Facilitation:** The facilitator should remain neutral, encouraging open and honest feedback. -- **Use of Prototypes:** Whenever possible, utilize prototypes or interactive elements to simulate the user experience. -- **Incorporate User Stories:** Use real-life scenarios or user stories to contextualize discussions. +## Best Practices for Focus Groups + +Some principles to keep in mind when conducting a focus group are: + +- **Diversity:** Select participants who represent a range of demographics, including age, gender, and technological proficiency. +- **Clear Objectives:** Clearly define the goals of the focus group for effective discussions. +- **Neutral Facilitation:** Emphasize neutral moderation and encourage honest feedback. +- **User Interactivity:** Incorporate prototypes or interactive elements to enhance user engagement. +- **User-centric Storytelling:** Contextualize discussions with real-life scenarios or user stories. + +## Additional Focus Group Resources + +- [User Interviews: Focus Groups](https://www.userinterviews.com/ux-research-field-guide-chapter/focus-groups) +- [Interaction Design Foundation: How to Conduct Focus Groups](https://www.interaction-design.org/literature/article/how-to-conduct-focus-groups) +- [Nielsen Norman Group: The Use and Misuse of Focus Groups](https://www.nngroup.com/articles/focus-groups/) +- [UX Matters: Do’s and Don’ts for Focus Groups](https://www.uxmatters.com/mt/archives/2011/07/dos-and-donts-for-focus-groups.php) +- [Adobe XD: Why Focus Groups Benefit the Web Design Process](https://xd.adobe.com/ideas/process/user-research/why-focus-groups-benefit-web-design-process/) diff --git a/content/uiux/concepts/focus-groups/focus-groups.md b/content/uiux/concepts/focus-groups/focus-groups.md deleted file mode 100644 index aa39eee5885..00000000000 --- a/content/uiux/concepts/focus-groups/focus-groups.md +++ /dev/null @@ -1,29 +0,0 @@ ---- -Title: 'Focus Groups' -Description: 'Focus groups are a user research method where a researcher guides a group of 3 to 10 participants through a series of questions about a topic, product, or design.' -Subjects: - - 'Web Design' -Tags: - - 'UI' - - 'UX' - - 'Design' -CatalogContent: - - 'intro-to-ui-ux' - - 'paths/front-end-engineer-career-path' ---- - -**Focus groups** are a [user research](https://www.codecademy.com/resources/docs/uiux/user-research) method where a researcher guides a group of 3 – 10 participants through a series of questions about a topic, product, or design. Focus groups can be conducted either remotely or in-person. - -Because focus groups rely on self-reported user data, they are considered an [attitudinal research method](https://www.codecademy.com/resources/docs/uiux/attitudinal-research). Focus groups are considered a [qualitative research method](https://www.codecademy.com/resources/docs/uiux/qualitative-research) since they focus on the in-depth motivations and thought processes behind the user experience. [Interviews](https://www.codecademy.com/resources/docs/uiux/interviews) are typically one-on-one, while focus groups collect qualitative feedback from a group of participants. - -Focus groups are commonly used in market research to collect feedback about a product or brand. In UX research, they can be used to collect data or feedback that may be difficult to collect in a typical interview or [survey](https://www.codecademy.com/resources/docs/uiux/surveys). Unlike a survey or one-on-one interview, a focus group has a social dynamic that may facilitate participants opening up and sharing their thoughts. - -Before conducting a focus group, the moderator will need to prepare a discussion guide to focus the conversation. Adding activities like collaging, drawing, brainstorming with sticky notes, card sorting, or role-playing can help engage participants and break away from a standard question-and-answer format. - -## Focus Resources - -- [User Interviews: Focus Groups](https://www.userinterviews.com/ux-research-field-guide-chapter/focus-groups) -- [Interaction Design Foundation: How to Conduct Focus Groups](https://www.interaction-design.org/literature/article/how-to-conduct-focus-groups) -- [Nielsen Norman Group: The Use and Misuse of Focus Groups](https://www.nngroup.com/articles/focus-groups/) -- [UX Matters: Do’s and Don’ts for Focus Groups](https://www.uxmatters.com/mt/archives/2011/07/dos-and-donts-for-focus-groups.php) -- [Adobe XD: Why Focus Groups Benefit the Web Design Process](https://xd.adobe.com/ideas/process/user-research/why-focus-groups-benefit-web-design-process/) From 148c7d5627aca565777ae595a2ad7884782e2374 Mon Sep 17 00:00:00 2001 From: Savi Dahegaonkar <124272050+SaviDahegaonkar@users.noreply.github.com> Date: Wed, 8 Jan 2025 17:09:25 +0530 Subject: [PATCH 14/31] [Concept Entry] Rust: Ownership (#5880) * New file has been added. * Update user-input.md * Update user-input.md * File has been modified. * Update content/rust/concepts/ownership/ownwership.md * Update content/rust/concepts/ownership/ownwership.md * Update content/rust/concepts/ownership/ownwership.md * Rename ownwership.md to ownership.md fixed minor issues and corrected file name spelling * Update content/rust/concepts/ownership/ownership.md * Update ownership.md * Update ownership.md --------- --- content/rust/concepts/ownership/ownership.md | 78 ++++++++++++++++++++ 1 file changed, 78 insertions(+) create mode 100644 content/rust/concepts/ownership/ownership.md diff --git a/content/rust/concepts/ownership/ownership.md b/content/rust/concepts/ownership/ownership.md new file mode 100644 index 00000000000..ca691a6b799 --- /dev/null +++ b/content/rust/concepts/ownership/ownership.md @@ -0,0 +1,78 @@ +--- +Title: 'Ownership' +Description: 'A compile-time system enforcing strict memory safety rules.' +Subjects: + - 'Code Foundations' + - 'Computer Science' + - 'Developer Tools' +Tags: + - 'Alias' + - 'Const' + - 'Memory' +CatalogContent: + - 'rust-for-programmers' + - 'paths/computer-science' +--- + +**Ownership** in Rust is one of the core memory management concepts that ensures every value has a single owner responsible for it. This system avoids memory leaks and data races without needing a garbage collector. Ownership features include move semantics, where the ownership is transferred between variables, borrowing, and the borrow checker, by which these rules are checked at compile time to keep memory safe. + +## Syntax + +Here's the syntax for the ownership concept in Rust: + +```pseudo +let variable1 = value; +let variable2 = variable1; +// 'variable1' is no longer valid and cannot be accessed. +``` + +- `variable1`: First owner of the value. +- `value`: The value or data to be owned initially. +- `variable2`: New owner of `value` after the ownership transfer. + +## Example + +This example demonstrates how ownership works, ensuring that only one variable owns the data at a time: + +```rust +fn main() { + let s1 = String::from("Hello, Welcome to Codecademy!"); + println!("s1: {}", s1); + let s2 = take_ownership(s1); + // println!("s1: {}", s1); // Uncommenting this line would result in a compile-time error because 's1' no longer owns the value. + println!("s2: {}", s2); // Prints: s2: Hello, Welcome to Codecademy! +} + +fn take_ownership(s: String) -> String { // Function takes ownership of the passed value + println!("Taking ownership: {}", s); // Prints: Taking ownership: Hello, Welcome to Codecademy! + s // Ownership is returned to the caller, moving it back to the caller. +} +``` + +In this example, the ownership of the string s1 is moved to s2, and s1 is no longer valid. After moving, s2 holds the ownership of the string "Hello, Welcome to Codecademy!": + +The example will result in the following output: + +```shell +s1: Hello, Welcome to Codecademy! +Taking ownership: Hello, Welcome to Codecademy! +s2: Hello, Welcome to Codecademy! +``` + +### Unsafe Code Example + +Rust’s ownership system prevents operations that could lead to unsafe memory access, like accessing data after ownership is moved, at compile time : + +```rust +fn main() { + let s1 = String::from("Hello"); + let s2 = take_ownership(s1); + // println!("{}", s1); // Uncommenting this line would cause a compile-time error: use of moved value +} + +fn take_ownership(s: String) -> String { + s +} +``` + +In this unsafe scenario, the ownership of `s1` is moved to `s2`, and attempting to access `s1` after the move results in a compile-time error. From acf7d5bc3dd503c58b85cb647d078768a983f899 Mon Sep 17 00:00:00 2001 From: hitomiyamamoto Date: Wed, 8 Jan 2025 16:49:35 +0100 Subject: [PATCH 15/31] [Concept Entry] JavaScript: Nullish Coalescing * Initial commit * removed extra information and modified grammar mistakes * Update nullish-coalescing.md minor fixes * Minor changes --------- --- .../nullish-coalescing/nullish-coalescing.md | 53 +++++++++++++++++++ 1 file changed, 53 insertions(+) create mode 100644 content/javascript/concepts/nullish-coalescing/nullish-coalescing.md diff --git a/content/javascript/concepts/nullish-coalescing/nullish-coalescing.md b/content/javascript/concepts/nullish-coalescing/nullish-coalescing.md new file mode 100644 index 00000000000..d7523d3c534 --- /dev/null +++ b/content/javascript/concepts/nullish-coalescing/nullish-coalescing.md @@ -0,0 +1,53 @@ +--- +Title: 'Nullish Coalescing' +Description: 'Returns the right-hand operand in case the left-hand operand is null or undefined. Otherwise, it returns the left-hand operand.' +Subjects: + - 'Web Development' + - 'Computer Science' +Tags: + - 'Comparison' + - 'Logical' + - 'Operators' +CatalogContent: + - 'introduction-to-javascript' + - 'paths/front-end-engineer-career-path' +--- + +In JavaScript, the **nullish coalescing** (`??`) operator is a logical operator that evaluates the left-hand operand and returns it if it is not nullish (i.e., not `null` or `undefined`). Otherwise, it returns the right-hand operand. + +## Syntax + +```pseudo +value1 ?? value2 +``` + +- `value1`: The first operand to check if it is nullish (`null` or `undefined`). +- `value2`: The second operand that acts as the default value, returned only if `value1` is nullish. + +## Example + +The following example demonstrates the use of the nullish coalescing operator to return `18` as a default or fallback value when the variable `age` is `null` or `undefined`: + +```js +const age = undefined; +const defaultAge = 18; + +console.log(age ?? defaultAge); +``` + +The above code produces the following output: + +```shell +18 +``` + +## Codebyte Example + +The following codebyte example uses the nullish coalescing operator (`??`) to return `"Guest"` as a fallback value when `name` is `null`: + +```codebyte/javascript +const name = null; +const defaultName = "Guest"; + +console.log(name ?? defaultName); +``` From aeba50536608a2198563ef759a35f109f6a63267 Mon Sep 17 00:00:00 2001 From: Savi Dahegaonkar <124272050+SaviDahegaonkar@users.noreply.github.com> Date: Thu, 9 Jan 2025 12:16:39 +0530 Subject: [PATCH 16/31] [Concept Entry] Sklearn: Ensembles * New file has been added. * Update user-input.md * Update user-input.md * File has been added. * Minor changes --------- --- .../sklearn/concepts/ensembles/ensembles.md | 134 ++++++++++++++++++ 1 file changed, 134 insertions(+) create mode 100644 content/sklearn/concepts/ensembles/ensembles.md diff --git a/content/sklearn/concepts/ensembles/ensembles.md b/content/sklearn/concepts/ensembles/ensembles.md new file mode 100644 index 00000000000..0880b40f7e9 --- /dev/null +++ b/content/sklearn/concepts/ensembles/ensembles.md @@ -0,0 +1,134 @@ +--- +Title: 'Ensembles' +Description: 'A machine learning technique that incorporates predictions from multiple models to enhance accuracy and reliability.' +Subjects: + - 'AI' + - 'Data Science' +Tags: + - 'Classification' + - 'Data' + - 'Machine Learning' + - 'Scikit-learn' +CatalogContent: + - 'paths/intermediate-machine-learning-skill-path' + - 'paths/data-science' +--- + +**Ensembles** are machine learning techniques that combine the predictions from multiple models in order to increase accuracy, robustness, and reliability in classification and regression tasks. Scikit-learn provides tools to build these sophisticated predictive systems effectively. +Some of the ensemble techniques include _Bagging_ and _Boosting_. + +## Bagging (Bootstrap Aggregating) + +Bagging refers to training multiple models in parallel on different subsets of the data generated using bootstrapping or random sampling with replacement. The predictions from the models are combined. + +This approach reduces the variance and prevents overfitting. Some popular algorithms that can be classified under bagging are `Random Forest` and `Bagging Classifier`. + +## Boosting + +Boosting creates models sequentially, where each new model corrects the mistakes of the previous one by focusing on the harder instances that the former model failed to predict. Well-known boosting algorithms include `AdaBoost`, `Gradient Boosting`, and `XGBoost`. + +## Syntax + +Sklearn offers the `BaggingClassifier` for performing classification tasks: + +```pseudo +BaggingClassifier(estimator=None, n_estimators=10, max_samples=1.0, max_features=1.0, bootstrap=True, bootstrap_features=False, oob_score=False, warm_start=False, n_jobs=None, random_state=None, verbose=0) +``` + +- `estimator` (`None`, default=`None`): The base estimator to fit on random subsets of the dataset. If `None`, the algorithm uses a decision tree as the default estimator. +- `n_estimators` (int, default=`10`): Number of estimators in the ensemble. +- `max_samples` (float, default=`1.0`): The fraction of samples for fitting each estimator, must be between `0` and `1`. +- `max_features` (float, default=`1.0`): The fraction of features for fitting each estimator, must be between `0` and `1`. +- `bootstrap` (bool, default=`True`): Whether to use bootstrap sampling (sampling with replacement) for creating datasets for each estimator. +- `bootstrap_features` (bool, default=`False`): Determines whether to sample features with replacement for each estimator. +- `oob_score` (bool, default=`False`): Determines whether to use out-of-bag samples for estimating the generalization error. +- `warm_start` (bool, default=`False`): If `True`, the fit method adds more estimators to the existing ensemble instead of starting from scratch. +- `n_jobs` (int, default=`None`): The number of jobs to run in parallel for fitting the base estimators. `None` means using `1` core, `-1` uses all available cores. +- `random_state` (int, default=`None`): Controls the randomness of the estimator fitting process, ensuring reproducibility. +- `verbose` (int, default=`0`): Controls the verbosity level of the fitting process, with higher values producing more detailed output. + +## Example + +This example code demonstrates the use of the `BaggingClassifier` to build an ensemble of `Decision Trees` and examine its performance on the Iris dataset: + +```py +# Import all the necessary libraries +from sklearn.ensemble import BaggingClassifier +from sklearn.tree import DecisionTreeClassifier +from sklearn.datasets import load_iris +from sklearn.model_selection import train_test_split +from sklearn.metrics import accuracy_score + +# Load the Iris dataset +data = load_iris() +X = data.data +y = data.target + +# Split the dataset into training and testing sets +X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.3, random_state=42) + +# Initialize a BaggingClassifier with a DecisionTreeClassifier as the base estimator +bagging_clf = BaggingClassifier(estimator=DecisionTreeClassifier(), + n_estimators=50, + max_samples=0.8, + max_features=0.8, + bootstrap=True, + random_state=42) + +# Train the BaggingClassifier +bagging_clf.fit(X_train, y_train) + +# Predict on the test set +y_pred = bagging_clf.predict(X_test) + +# Evaluate accuracy +accuracy = accuracy_score(y_test, y_pred) +print(f"Accuracy: {accuracy:.2f}") +``` + +The code results in the following output: + +```shell +Accuracy: 1.00 +``` + +## Codebyte Example + +This is an example that demonstrates the use of a `VotingClassifier` to combine multiple classifiers (`Decision Tree`, `Support Vector Classifier`, and `K-Nearest Neighbors`) for a classification task on the Iris dataset: + +```codebyte/python +# Import all the necessary libraries +from sklearn.ensemble import VotingClassifier +from sklearn.tree import DecisionTreeClassifier +from sklearn.svm import SVC +from sklearn.neighbors import KNeighborsClassifier +from sklearn.datasets import load_iris +from sklearn.model_selection import train_test_split +from sklearn.metrics import accuracy_score + +# Load the Iris dataset +data = load_iris() +X = data.data +y = data.target + +# Split the dataset into training and testing sets +X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.3, random_state=42) + +# Initialize individual classifiers +dt_clf = DecisionTreeClassifier(random_state=42) +svc_clf = SVC(probability=True, random_state=42) +knn_clf = KNeighborsClassifier() + +# Create a VotingClassifier that combines the classifiers +voting_clf = VotingClassifier(estimators=[('dt', dt_clf), ('svc', svc_clf), ('knn', knn_clf)], voting='soft') + +# Train the VotingClassifier +voting_clf.fit(X_train, y_train) + +# Predict on the test set +y_pred = voting_clf.predict(X_test) + +# Evaluate accuracy +accuracy = accuracy_score(y_test, y_pred) +print(f"VotingClassifier Accuracy: {accuracy:.2f}") +``` From 28ca408ca0d5cb4f155fa1656834ca15aa3d2cd6 Mon Sep 17 00:00:00 2001 From: Jonathan Hill Date: Thu, 9 Jan 2025 07:15:58 -0800 Subject: [PATCH 17/31] [Edit] Fix typo in CSS Overflow entry (#5917) * Add colon for consistancy in formatting * Update overflow.md Fixed the description. It was too long. * Update overflow.md fixed lint issue * Update overflow.md fixing issues --------- --- content/css/concepts/overflow/overflow.md | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/content/css/concepts/overflow/overflow.md b/content/css/concepts/overflow/overflow.md index 140e9411c5e..aea41c7c0ea 100644 --- a/content/css/concepts/overflow/overflow.md +++ b/content/css/concepts/overflow/overflow.md @@ -1,6 +1,6 @@ --- Title: 'Overflow' -Description: 'The overflow property controls what happens to content that spills, or overflows, outside its box. The most commonly used values are: - hidden When set to this value, any content that overflows will be hidden from view. - scroll: When set to this value, a scrollbar will be added to the element’s box so that the rest of the content can be viewed by scrolling. - visible: When set to this value, the overflow content will be displayed outside of the containing element. Note, this is the default value. css p {' +Description: 'The overflow property controls what happens to content that spills, or overflows, outside its box.' Subjects: - 'Web Development' - 'Web Design' @@ -16,7 +16,7 @@ The `overflow` property controls what happens to content that spills, or overflo The most commonly used values are: -- `hidden` When set to this value, any content that overflows will be hidden from view. +- `hidden`: When set to this value, any content that overflows will be hidden from view. - `scroll`: When set to this value, a scrollbar will be added to the element’s box so that the rest of the content can be viewed by scrolling. - `visible`: When set to this value, the overflow content will be displayed outside of the containing element. Note, this is the default value. From 2fd341e99d5fcc50ff4c48f960d76c2331b2bb6f Mon Sep 17 00:00:00 2001 From: Melek Nur Date: Thu, 9 Jan 2025 19:56:05 +0300 Subject: [PATCH 18/31] Updated doc for python strftime module (#5835) * Add documentation for python strftime() method * Updated doc for python strftime module * New term entries for Python: Dates * Updated doc for python strftime module * Update content/python/concepts/dates/terms/strftime/strftime.md * Update content/python/concepts/dates/terms/strftime/strftime.md * Update content/python/concepts/dates/terms/strftime/strftime.md * Update content/python/concepts/dates/terms/strftime/strftime.md * Changes implemented on the file. * Update content/python/concepts/dates/terms/strftime/strftime.md --------- --- .../concepts/dates/terms/strftime/strftime.md | 60 +++++++++++++++++++ 1 file changed, 60 insertions(+) create mode 100644 content/python/concepts/dates/terms/strftime/strftime.md diff --git a/content/python/concepts/dates/terms/strftime/strftime.md b/content/python/concepts/dates/terms/strftime/strftime.md new file mode 100644 index 00000000000..248030c7364 --- /dev/null +++ b/content/python/concepts/dates/terms/strftime/strftime.md @@ -0,0 +1,60 @@ +--- +Title: '.strftime()' +Description: 'Format time and date objects into readable strings based on specified patterns.' +Subjects: + - 'Computer Science' + - 'Data Science' +Tags: + - 'Date' + - 'Time' +CatalogContent: + - 'learn-python-3' + - 'paths/computer-science' +--- + +The **`datetime.strftime()`** method formats time and `datetime` objects into readable strings on specified format codes. + +## Syntax + +```pseudo +datetime.strftime(format) +``` + +Here are some commonly used format codes: + +| Directive | Meaning | Example | +| --------- | -------------------------------------- | ---------------------------------------- | +| `%a` | Abbreviated name of days | Sun, Mon, …, Sat | +| `%d` | Day of the month | 01, 02, …, 31 | +| `%b` | Abbreviated name of months | Jan, Feb, …, Dec | +| `%Y` | Year | 0001, 0002, …, 2013, 2014, …, 9998, 9999 | +| `%m` | Month | 01, 02, …, 12 | +| `%I` | Hour (12-hour clock) | 01, 02, …, 12 | +| `%M` | Minute | 00, 01, …, 59 | +| `%p` | Locale’s equivalent of either AM or PM | AM, PM | + +For a complete list, refer to the [Python documentation](https://docs.python.org/3/library/datetime.html#strftime-strptime-behavior). + +## Example + +The formatted time can be retrieved and stored in a variable as shown in this example: + +```py +import datetime + +#Assign current time +now = datetime.datetime.now() + +#Format the current date and time +formatted_date = now.strftime('%a %d %b %Y, %I:%M%p') + +print(formatted_date) +``` + +This example results in the following output which displays the current date and time in specific format: + +```shell +Mon 06 Jan 2025, 09:01PM +``` + +> **Note:** The actual output will vary depending on the current date and time when the script is executed. From 46df91d59f79c392f53e81bc92e6fbd03ce97ebb Mon Sep 17 00:00:00 2001 From: Goodluck Somadina Chukwuemeka <105865699+Good-Soma@users.noreply.github.com> Date: Fri, 10 Jan 2025 12:39:07 +0100 Subject: [PATCH 19/31] The document for Mixedlm entry. (#5794) * Create deg2rad.md * statsmodel * Delete content/python/concepts/statsmodel * terms * Delete content/python/concepts/statsmodel directory * Create mixedlm.md * Update and rename deg2rad.md to deg2rad.md format * Delete content/numpy/concepts/math-methods/terms/deg2rad/deg2rad.md * Update mixedlm.md fixes * Update mixedlm.md Please, I have done the correction and also added the note as you specified. I will still need to exemplify that the three models can be combined in an operation, but that will be later. I just want you to work on the aspect that is important to you and that I have already completed, then later I will do that. Review the changes, and if you think I didn't still get some things right, always feel free to reach out. Thanks * Update mixedlm.md * Fix file path --------- --- .../statsmodels/terms/mixedlm/mixedlm.md | 156 ++++++++++++++++++ 1 file changed, 156 insertions(+) create mode 100644 content/python/concepts/statsmodels/terms/mixedlm/mixedlm.md diff --git a/content/python/concepts/statsmodels/terms/mixedlm/mixedlm.md b/content/python/concepts/statsmodels/terms/mixedlm/mixedlm.md new file mode 100644 index 00000000000..6ba7e764488 --- /dev/null +++ b/content/python/concepts/statsmodels/terms/mixedlm/mixedlm.md @@ -0,0 +1,156 @@ +--- +Title: 'MixedLM' +Description: 'MixedLM in Statsmodels is a class for fitting linear mixed-effects models, which account for both fixed and random effects in data.' +Subjects: + - 'Data Science' + - 'Machine Learning' +Tags: + - 'Linear Regression' + - 'Machine Learning' + - 'Python' + - 'Statistics' + - 'Supervised Learning' +CatalogContent: + - 'learn-python-3' + - paths/data-science +--- + +**MixedLM** in Python's [Statsmodels](https://www.codecademy.com/resources/docs/python/statsmodels) library is a tool for fitting mixed-effects models, combining fixed and random effects to analyze data. It captures fixed effects (predictable factors) and random effects (unpredictable factors), defining mixed-effect modeling. Fixed effects explain the trend, while random effects account for variability across groups. + +## Application of mixedlm model + +- **Random Intercept Model**: Captures group-level variability in the intercept while keeping the slope fixed. +- **Random Slope Model**: Allows the slope to vary across groups to account for differences in trends. +- **Variance Components Model**: Decomposes variance into different components to understand variability sources. + +## Syntax + +### Using Formula API (`from_formula`) + +The formula API is the recommended approach for specifying mixed-effects models. It simplifies model definition using a string formula. + +```pseudo +from statsmodels.api import MixedLM + +model = MixedLM.from_formula(formula, data, groups, re_formula=None) +result = model.fit() +``` + +**Parameters**: + +- `formula`: A string specifying the fixed-effects model (e.g., "Y ~ X1 + X2"). +- `data`: A Pandas DataFrame containing the dataset. +- `groups`: A column in the DataFrame that defines the grouping for random effects. +- `re_formula` (Optional): A string specifying the random-effects model. Defaults to a random intercept model. + +> **Note**: The Formula API (`from_formula`) is typically easier to use and more intuitive for specifying models, especially for developers familiar with R-style formulas. + +### Using Direct API + +```pseudo +from statsmodels.api import MixedLM + +model = MixedLM(endog, exog, groups, exog_re=None) +result = model.fit() +``` + +**Parameters**: + +- `endog`: Dependent variable (response variable as a NumPy array or Pandas Series). +- `exog`: Design matrix for fixed effects (NumPy array or Pandas DataFrame). +- `groups`: A grouping variable for random effects (e.g., a column name or array-like object). +- `exog_re` (Optional): Design matrix for random effects. Defaults to a random intercept model. + +> **Note**: The Direct API provides greater flexibility and control but requires manually constructing the design matrices, which can be cumbersome for complex models. + +## Examples + +In this example, a mixed-effects model is fitted to NBA team performance data, with `'Minutes'` as a fixed effect and `'Team'` as a random effect to analyze points scored: + +### Using Formula API + +``` +import pandas as pd +from statsmodels.api import MixedLM + +# Sample data +data = pd.DataFrame({ + 'Points': [10, 25, 35, 30, 22, 14, 24, 28, 32, 27], + 'Minutes': [35, 40, 30, 38, 33, 32, 34, 39, 41, 36], + 'Team': ['TeamG', 'TeamG', 'TeamR', 'TeamR', 'TeamG', 'TeamG', 'TeamR', 'TeamR', 'TeamG', 'TeamR'] +}) + +# Fit the model using formula API +model = MixedLM.from_formula("Points ~ Minutes", data, groups="Team") +result = model.fit() + +# Display the results +print(result.summary()) +``` + +The code generates the output as follows: + +```shell + Mixed Linear Model Regression Results +====================================================== +Model: MixedLM Dependent Variable: Points +No. Observations: 10 Method: REML +No. Groups: 2 Scale: 45.7191 +Min. group size: 5 Log-Likelihood: -30.8931 +Max. group size: 5 Converged: Yes +Mean group size: 5.0 +------------------------------------------------------ + Coef. Std.Err. z P>|z| [0.025 0.975] +------------------------------------------------------ +Intercept 1.759 22.753 0.077 0.938 -42.835 46.353 +Minutes 0.641 0.624 1.027 0.304 -0.582 1.863 +Team Var 28.935 8.542 +====================================================== +``` + +### Using Direct API + +```py +import pandas as pd +import numpy as np +from statsmodels.api import MixedLM + +# Sample data +data = pd.DataFrame({ + 'Points': [10, 25, 35, 30, 22, 14, 24, 28, 32, 27], + 'Minutes': [35, 40, 30, 38, 33, 32, 34, 39, 41, 36], + 'Team': ['TeamG', 'TeamG', 'TeamR', 'TeamR', 'TeamG', 'TeamG', 'TeamR', 'TeamR', 'TeamG', 'TeamR'] +}) + +# Define variables +endog = data['Points'] +exog = sm.add_constant(data['Minutes']) # Adding constant for intercept +groups = data['Team'] + +# Fit the model using direct API +model = MixedLM(endog, exog, groups) +result = model.fit() + +# Display the results +print(result.summary()) +``` + +The code generates the output as follows: + +```shell + Mixed Linear Model Regression Results +====================================================== +Model: MixedLM Dependent Variable: Points +No. Observations: 10 Method: REML +No. Groups: 2 Scale: 45.7191 +Min. group size: 5 Log-Likelihood: -30.8931 +Max. group size: 5 Converged: Yes +Mean group size: 5.0 +------------------------------------------------------ + Coef. Std.Err. z P>|z| [0.025 0.975] +------------------------------------------------------ +Intercept 1.759 22.753 0.077 0.938 -42.835 46.353 +Minutes 0.641 0.624 1.027 0.304 -0.582 1.863 +Team Var 28.935 8.542 +====================================================== +``` From 38d8bbc9523a276cbeb583c2d99f3461a5840253 Mon Sep 17 00:00:00 2001 From: Timothy Charteris Date: Sun, 12 Jan 2025 07:34:15 +0000 Subject: [PATCH 20/31] [Edit] Python: Errors * add custom exceptions * Update content/python/concepts/errors/errors.md * Update content/python/concepts/errors/errors.md * Update content/python/concepts/errors/errors.md * Minor changes --------- --- content/python/concepts/errors/errors.md | 58 ++++++++++++++++++++++++ 1 file changed, 58 insertions(+) diff --git a/content/python/concepts/errors/errors.md b/content/python/concepts/errors/errors.md index 59e031d28d4..eae58060dc9 100644 --- a/content/python/concepts/errors/errors.md +++ b/content/python/concepts/errors/errors.md @@ -100,3 +100,61 @@ File "script.py", line 1, in ratio = 100 / 0 ZeroDivisionError: division by zero ``` + +## Custom Exceptions + +Custom exceptions can be used to define and handle application-specific errors. This can be done by creating a sub-class of the built-in `Exception` class. + +Custom exceptions help provide clear feedback to users about unexpected behavior, aid in debugging, and can be used throughout the program. + +### Defining Custom Exceptions + +To define a custom exception, a new class can be created by inheriting `Exception` and the constructor can be optionally overridden to provide additional information: + +```pseudo +# Custom exception for invalid age input +class InvalidAgeError(Exception): + def __init__(self, message, age=None): + super().__init__(message) + self.age = age +``` + +### Using Custom Exceptions + +Once a custom exception has been created, it can raise custom error messages for invalid inputs. For example, the following function raises an error if the user inputs an age not between 0 and 130: + +```pseudo +def validate_age(age): + if not isinstance(age, int): + raise InvalidAgeError("Age must be an integer.", age) + if age < 0 or age > 130: + raise InvalidAgeError(f"{age} is not a valid age. Please choose an age between 0 and 130.", age) +``` + +### Example + +Once the custom exception is defined, it can be used to handle errors in a `try-except` block. The following example demonstrates how to raise the custom exception when an invalid age is provided: + +```py +class InvalidAgeError(Exception): + def __init__(self, message, age=None): + super().__init__(message) + self.age = age + +def validate_age(age): + if not isinstance(age, int): + raise InvalidAgeError("Age must be an integer.", age) + if age < 0 or age > 130: + raise InvalidAgeError(f"{age} is not a valid age. Please choose an age between 0 and 130.", age) + +try: + validate_age(-5) +except InvalidAgeError as e: + print(f"Error: {e}") +``` + +Here is the output: + +```shell +Error: -5 is not a valid age. Please choose an age between 0 and 130. +``` From 75fe50ff14263ff6a35cc7e57bd75bde2d615a67 Mon Sep 17 00:00:00 2001 From: EduardoGallego94 Date: Sun, 12 Jan 2025 08:50:53 +0100 Subject: [PATCH 21/31] [Term Entry] Python Dates: .strptime() * Add strptime.md file * Update content/python/concepts/dates/terms/strptime/strptime.md Co-authored-by: Mamta Wardhani * Update content/python/concepts/dates/terms/strptime/strptime.md Co-authored-by: Mamta Wardhani * Update content/python/concepts/dates/terms/strptime/strptime.md Co-authored-by: Mamta Wardhani * Update content/python/concepts/dates/terms/strptime/strptime.md Co-authored-by: Mamta Wardhani * Update content/python/concepts/dates/terms/strptime/strptime.md Co-authored-by: Mamta Wardhani * Update content/python/concepts/dates/terms/strptime/strptime.md Co-authored-by: Mamta Wardhani * strptime updated * Update strptime.md minor fixes * Minor changes --------- --- .../concepts/dates/terms/strptime/strptime.md | 69 +++++++++++++++++++ 1 file changed, 69 insertions(+) create mode 100644 content/python/concepts/dates/terms/strptime/strptime.md diff --git a/content/python/concepts/dates/terms/strptime/strptime.md b/content/python/concepts/dates/terms/strptime/strptime.md new file mode 100644 index 00000000000..2cef73d78e8 --- /dev/null +++ b/content/python/concepts/dates/terms/strptime/strptime.md @@ -0,0 +1,69 @@ +--- +Title: '.strptime()' +Description: 'Returns a datetime object that represents the parsed date and time from the given string, based on the specified format.' +Subjects: + - 'Python' + - 'Computer Science' +Tags: + - 'Date' + - 'Time' + - 'Strings' +CatalogContent: + - 'learn-python-3' + - 'paths/computer-science' +--- + +The **`.strptime()`** is a method included in the [`datetime`](https://www.codecademy.com/resources/docs/python/dates) module. It is used to parse a string representing a date and/or time and convert it into a `datetime` object using a specified format. + +## Syntax + +```pseudo +from datetime import datetime + +datetime.strptime(date_string, format) +``` + +- `date_string`: The string representing the date and/or time to be parsed. +- `format`: A string that defines the structure of `date_string` using format codes from the `datetime` module (e.g., `%Y` for a four-digit year, `%m` for a two-digit month). + +It returns a `datetime` object, which represents the parsed date and time from the provided `date_string` according to the specified `format`. + +## Example + +In the following example, the `.strptime()` method is used to parse a date-time string into a `datetime` object based on the specified format: + +```py +from datetime import datetime + +# Define the date-time string and format +datetime_string = "27/12/2024 15:30:00" +datetime_format = "%d/%m/%Y %H:%M:%S" + +# Parse the string into a datetime object +dt_object = datetime.strptime(datetime_string, datetime_format) + +print(dt_object) +``` + +The code above produces an output as: + +```shell +2024-12-27 15:30:00 +``` + +## Codebyte Example + +Run the following codebyte example to understand the use of the `.strptime()` method: + +```codebyte/python +from datetime import datetime + +# Define the date string and format +date_string = "2025-01-08" +date_format = "%Y-%m-%d" + +# Parse the string into a datetime object +dt_object = datetime.strptime(date_string, date_format) + +print(dt_object) +``` From 48cf7eb89a95062cca78971a3bb3c76f10659074 Mon Sep 17 00:00:00 2001 From: DenisFlorin66 <62358650+DenisFlorin66@users.noreply.github.com> Date: Sun, 12 Jan 2025 09:56:52 +0200 Subject: [PATCH 22/31] [Term Entry] PyTorch Tensor Operations: .swapaxes() * [Term Entry] PyTorch Tensor Operations: .swapaxes() * Update swapaxes.md minor fixes * Minor changes --------- --- .../terms/swapaxes/swapaxes.md | 66 +++++++++++++++++++ 1 file changed, 66 insertions(+) create mode 100644 content/pytorch/concepts/tensor-operations/terms/swapaxes/swapaxes.md diff --git a/content/pytorch/concepts/tensor-operations/terms/swapaxes/swapaxes.md b/content/pytorch/concepts/tensor-operations/terms/swapaxes/swapaxes.md new file mode 100644 index 00000000000..ff495f2b4ea --- /dev/null +++ b/content/pytorch/concepts/tensor-operations/terms/swapaxes/swapaxes.md @@ -0,0 +1,66 @@ +--- +Title: '.swapaxes()' +Description: 'Swaps two specified axes (dimensions) of a tensor, effectively rearranging its shape.' +Subjects: + - 'Computer Science' + - 'Machine Learning' +Tags: + - 'AI' + - 'Data Types' + - 'Deep Learning' + - 'Functions' +CatalogContent: + - 'intro-to-py-torch-and-neural-networks' + - 'paths/data-science' +--- + +In PyTorch, the **`.swapaxes()`** function swaps two specified axes (dimensions) of a tensor. + +## Syntax + +```pseudo +torch.swapaxes(input, axis0, axis1) +``` + +- `input`: The input tensor. +- `axis0`: The first axis to be swapped. +- `axis1`: The second axis to be swapped. + +## Example + +The following example demonstrates the usage of the `.swapaxes()` function: + +```py +import torch + +# Create a tensor +x = torch.tensor([[[0, 1], [2, 3]], [[4, 5], [6, 7]]]) + +# Swap the axes (0 and 1) +swapped1 = torch.swapaxes(x, 0, 1) +print("After swapping axes 0 and 1:") +print(swapped1) + +# Swap the axes (0 and 2) +swapped2 = torch.swapaxes(x, 0, 2) +print("\nAfter swapping axes 0 and 2:") +print(swapped2) +``` + +The output of the above code is as follows: + +```shell +After swapping axes 0 and 1: +tensor([[[0, 1], + [4, 5]], + + [[2, 3], + [6, 7]]]) + +After swapping axes 0 and 2: +tensor([[[0, 4], + [2, 6]], + + [[1, 5], + [3, 7]]]) +``` From 5adc9fcb18fcaf6451df4e15140db3b3f3ce54b1 Mon Sep 17 00:00:00 2001 From: codecademydev Date: Sun, 12 Jan 2025 13:06:10 +0000 Subject: [PATCH 23/31] =?UTF-8?q?=F0=9F=A4=96=20update=20concept=20of=20th?= =?UTF-8?q?e=20week?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- bin/concept-of-the-week.txt | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/bin/concept-of-the-week.txt b/bin/concept-of-the-week.txt index 4829c2f3c48..ba6b63ae17c 100644 --- a/bin/concept-of-the-week.txt +++ b/bin/concept-of-the-week.txt @@ -1 +1 @@ -content/r/concepts/built-in-functions/built-in-functions.md \ No newline at end of file +content/ruby/concepts/sets/sets.md \ No newline at end of file From e77b33609e7cd028b9826fc4c40ea91a12c267f0 Mon Sep 17 00:00:00 2001 From: Pragati Verma Date: Mon, 13 Jan 2025 09:07:42 +0530 Subject: [PATCH 24/31] [Concept Entry] How to use loops in SQL (#5836) * Add loops concept entry * Update loops.md * Update loops.md * Update loops.md --------- --- content/sql/concepts/loops/loops.md | 114 ++++++++++++++++++++++++++++ 1 file changed, 114 insertions(+) create mode 100644 content/sql/concepts/loops/loops.md diff --git a/content/sql/concepts/loops/loops.md b/content/sql/concepts/loops/loops.md new file mode 100644 index 00000000000..aad6d9fa72c --- /dev/null +++ b/content/sql/concepts/loops/loops.md @@ -0,0 +1,114 @@ +--- +Title: 'Loops' +Description: 'Loops are used to repeatedly execute a block of code as long as a certain condition is met.' +Subjects: + - 'Computer Science' + - 'Data Science' +Tags: + - 'Loops' + - 'Database' + - 'Queries' + - 'Tables' +CatalogContent: + - 'learn-sql' + - 'paths/analyze-data-with-sql' +--- + +In SQL, **loops** are used to repeatedly execute a block of code as long as a certain condition is met. These loops can be useful when performing operations that require repetition, such as processing a set of rows or performing iterative calculations. + +## Types of Loops + +### 1. WHILE Loop + +The `WHILE` loop is the most common loop in SQL and is used to execute a block of SQL statements as long as a given condition remains true. + +The syntax for `WHILE` loop is as follows: + +```pseudo +WHILE condition +BEGIN + -- SQL statements to execute +END +``` + +Here's an example to print the value of `@counter` from 1 to 5 using a `WHILE` loop: + +```sql +DECLARE @counter INT = 1; + +WHILE @counter <= 5 +BEGIN + PRINT 'Counter: ' + CAST(@counter AS VARCHAR); + SET @counter = @counter + 1; +END +``` + +### 2. FOR Loop + +In SQL, a `FOR` loop is often used for iterating over a specific range of values. It is more common in Oracle databases than other SQL variants. + +The syntax for `FOR` loop is as follows: + +```pseudo +FOR counter IN lower_bound..upper_bound +LOOP + -- SQL statements to execute +END LOOP; +``` + +Here's an example to print the value of `counter` from 1 to 5 using a `FOR` loop: + +```sql +BEGIN + FOR counter IN 1..5 LOOP + DBMS_OUTPUT.PUT_LINE('Counter: ' || counter); + END LOOP; +END; +``` + +### 3. LOOP + +The `LOOP` structure in SQL is a powerful tool for executing a block of statements repeatedly until a specific condition is met. Unlike other loop types, a `LOOP` does not inherently depend on an initial condition. Instead, it runs unconditionally and requires an explicit exit condition within the loop body to stop execution. This flexibility makes it highly versatile but demands careful implementation to avoid infinite loops. + +The syntax for using `LOOP` is as follows: + +```pseudo +LOOP + -- SQL statements + IF condition THEN + EXIT; + END IF; +END LOOP; +``` + +Here's an example to print the value of `counter` from 1 to 5 using a `LOOP`: + +```sql +DECLARE + counter INT := 1; +BEGIN + LOOP + EXIT WHEN counter > 5; + DBMS_OUTPUT.PUT_LINE('Counter: ' || counter); + counter := counter + 1; + END LOOP; +END; +``` + +## Infinite Loops + +Loops without a properly defined exit condition can lead to infinite loops, where the code continues executing indefinitely. This often occurs when the condition in a `WHILE` or `LOOP` structure is never met or incorrectly updated. + +Here is an example of an infinite loop in SQL: + +```sql +DECLARE @counter INT = 1; + +WHILE @counter > 0 +BEGIN + PRINT 'This loop will run indefinitely'; + -- No exit condition or update to @counter +END +``` + +> **Note**: Be cautious of creating infinite loops, especially if the exit condition is not correctly defined, as it can lead to system performance degradation. From 978e922b3cc966dfc9e22b1bd3b357e315a4b99c Mon Sep 17 00:00:00 2001 From: Pragati Verma Date: Mon, 13 Jan 2025 09:12:11 +0530 Subject: [PATCH 25/31] [Concept Entry] Optimizing SQL queries (#5837) * Add optimizing SQL queries entry * Update optimizing-queries.md * Fix lint errors * Updating --------- --- .../optimizing-queries/optimizing-queries.md | 178 ++++++++++++++++++ 1 file changed, 178 insertions(+) create mode 100644 content/sql/concepts/optimizing-queries/optimizing-queries.md diff --git a/content/sql/concepts/optimizing-queries/optimizing-queries.md b/content/sql/concepts/optimizing-queries/optimizing-queries.md new file mode 100644 index 00000000000..e68656210e1 --- /dev/null +++ b/content/sql/concepts/optimizing-queries/optimizing-queries.md @@ -0,0 +1,178 @@ +--- +Title: 'Optimizing Queries' +Description: 'Optimizing SQL queries is the process of improving the efficiency of SQL statements to reduce execution time, minimize resource consumption, and enhance overall database performance.' +Subjects: + - 'Computer Science' + - 'Data Science' +Tags: + - 'Database' + - 'Queries' + - 'MySQL' + - 'PostgreSQL' + - 'SQLite' +CatalogContent: + - 'learn-sql' + - 'paths/analyze-data-with-sql' +--- + +**Optimizing SQL queries** is the process of improving the efficiency of SQL statements to reduce execution time, minimize resource consumption, and enhance overall database performance. + +This involves using techniques such as indexing, query restructuring, execution plan analysis, and proper use of SQL constructs to ensure that queries retrieve or manipulate data most effectively. Optimisation aims to handle large datasets, complex joins, or frequent transactions efficiently while maintaining accuracy and scalability. + +## Common Techniques for Query Optimization + +### **Use Indexes Effectively** + +Indexes are essential for speeding up data retrieval. They act as pointers to the rows in a table, allowing the database to locate data without scanning the entire table. + +#### Tips + +- Create indexes on columns frequently used in `WHERE`, `JOIN`, `GROUP BY`, or `ORDER BY` clauses. +- Avoid over-indexing, as it can slow down `INSERT`, `UPDATE`, and `DELETE` operations. +- Use composite indexes for queries that filter on multiple columns. + +To add an index on `last_name` in a SQL query: + +Without an index: + +```sql +SELECT * +FROM employees +WHERE last_name = 'Smith'; +``` + +With an index: + +```sql +CREATE INDEX idx_last_name ON employees(last_name); + +SELECT * +FROM employees +WHERE last_name = 'Smith'; +``` + +### Avoid `SELECT *` + +Fetching all columns from a table increases data transfer time and memory usage. Specify only the columns needed for your query. + +Instead of: + +```sql +SELECT * +FROM employees; +``` + +Use: + +```sql +SELECT first_name, last_name +FROM employees; +``` + +### Filter Early with `WHERE` + +Reduce the number of rows processed by filtering data as early as possible in the query using the `WHERE` clause. + +Instead of: + +```sql +SELECT first_name, last_name +FROM employees +ORDER BY last_name; +``` + +Use: + +```sql +SELECT first_name, last_name +FROM employees +WHERE department = 'Sales' +ORDER BY last_name; +``` + +### Avoid Functions on Indexed Columns in `WHERE` Clauses + +When using functions on columns in the `WHERE` clause, the database cannot use an index on that column effectively, leading to a full table scan. Rewrite queries to avoid applying functions directly to indexed columns. + +Inefficient (function on indexed column): + +```sql +SELECT * +FROM employees +WHERE YEAR(hire_date) = 2023; +``` + +This query applies the `YEAR()` function to every row's `hire_date`, preventing the use of an index on the `hire_date` column. + +Efficient: + +```sql +SELECT * +FROM employees +WHERE hire_date BETWEEN '2023-01-01' AND '2023-12-31'; +``` + +By transforming the query, the index on `hire_date` can be used effectively, improving performance. + +### Use Joins Instead of Subqueries + +In many cases, joins perform better than subqueries because the database can optimize them more efficiently. + +Subquery: + +```sql +SELECT first_name, last_name +FROM employees +WHERE department_id = (SELECT id FROM departments WHERE name = 'Sales'); +``` + +Join: + +```sql +SELECT e.first_name, e.last_name +FROM employees e +JOIN departments d ON e.department_id = d.id +WHERE d.name = 'Sales'; +``` + +### Optimize `JOIN` + +- Ensure the joined columns are indexed. +- Use the appropriate join type (e.g., INNER `JOIN`, `LEFT JOIN`) for the specific use case. + +### Limit the Use of `DISTINCT` + +Using `DISTINCT` can be costly for performance, requiring sorting and deduplication. Use it only when absolutely necessary. + +Instead of: + +```sql +SELECT DISTINCT department +FROM employees; +``` + +Use: + +```sql +SELECT department +FROM employees +GROUP BY department; +``` + +### Partition Large Tables + +Partitioning divides a table into smaller, more manageable pieces based on column values, improving query performance for specific subsets of data. + +To partition a `sales` table by year: + +```sql +CREATE TABLE sales_2023 PARTITION OF sales FOR VALUES IN (2023); +``` + +### Use Caching + +Cache frequently executed queries to reduce database load. This can be done using a caching layer like Redis or in-memory caching. + +### Optimize Data Types + +Use appropriate data types for columns to minimize storage and processing overhead. For example, use `INT` instead of `BIGINT` when possible or `CHAR` instead of `VARCHAR` for fixed-length data. From 3a2392b81c2e80b979b45bc25f182228122cba9b Mon Sep 17 00:00:00 2001 From: Savi Dahegaonkar <124272050+SaviDahegaonkar@users.noreply.github.com> Date: Mon, 13 Jan 2025 09:23:05 +0530 Subject: [PATCH 26/31] [Concept Entry] Subject: performance tuning in sql (#5899) * New file has been added. * Update user-input.md * Update user-input.md * File has been added. --------- --- .../performance-tuning/performance-tuning.md | 49 +++++++++++++++++++ 1 file changed, 49 insertions(+) create mode 100644 content/sql/concepts/performance-tuning/performance-tuning.md diff --git a/content/sql/concepts/performance-tuning/performance-tuning.md b/content/sql/concepts/performance-tuning/performance-tuning.md new file mode 100644 index 00000000000..0e7139f90fe --- /dev/null +++ b/content/sql/concepts/performance-tuning/performance-tuning.md @@ -0,0 +1,49 @@ +--- +Title: 'Performance Tuning' +Description: 'Optimizes queries and database configurations to improve speed and resource efficiency.' +Subjects: + - 'Computer Science' + - 'Data Science' + - 'Developer Tools' +Tags: + - 'Algorithms' + - 'Collations' + - 'Database' + - 'MySQL' + - 'Queries' +CatalogContent: + - 'learn-sql' + - 'paths/analyze-data-with-sql' +--- + +**Performance Tuning** in SQL involves optimizing queries and database configurations to improve speed and resource efficiency. This process is essential for improving overall database performance. + +## Factors Affecting SQL Speed + +The execution speed of SQL queries is affected by several factors as follows: + +- `Query Complexity`: Queries with multiple joins or subqueries may take longer to execute. +- `Indexing`: Missing or lack of proper indexing can slow down query performance. +- `Data Volume`: Larger datasets generally require more time to process. +- `Server performance`: The CPU, memory, and disk I/O all impact query execution times. +- `Database Schema Design`: Poorly designed schema can lead to inefficient queries and slow performance. + +## Ways to Improve SQL Speed + +To improve the SQL speed, consider the following techniques: + +- `Optimize Queries`: Make complex queries and eliminate any unnecessary subqueries or joins. +- `Indexing`: Proper indexes should be built on frequently queried columns to improve data retrieval speed. +- `Use the EXPLAIN command`: Make use of the EXPLAIN command to analyze query execution plans and identify inefficiencies. +- `Partitioning`: Breaking up very large tables into smaller ones to speed up queries. +- `Caching`: Implement cache mechanisms to avoid redundant data retrieval operations. + +## Tools for SQL Performance Tuning + +Several tools that can help optimize SQL Performance Tuning are as follows: + +- `MySQL Query Profiler`: This tool monitors activity and tracks slow queries, helping to identify known performance bottlenecks across SQL databases. +- `EXPLAIN Command`: Visualizes the execution of SQL queries, which helps in performance analysis. +- `SQL Server Profiler`: This tool monitors activity and tracks slow queries and known performance bottlenecks across SQL Server. +- `pgAdmin (PostgreSQL)`: Tools for database management and analysis of database performance in PostgreSQL. +- `Database indexing tools`: Tools that help in automatically generate and maintain the indexes in order to ensure performance. From 5fbedfffabe451a0b83ddbf03c90f765ea708c26 Mon Sep 17 00:00:00 2001 From: arisdelacruz <115809819+arisdelacruz@users.noreply.github.com> Date: Mon, 13 Jan 2025 13:26:40 +0800 Subject: [PATCH 27/31] Create narrow copy entry for pytorch (#5904) * Create narrow copy entry for pytorch * Update narrow-copy.md * Update narrow-copy.md minor fixes * format fixes --------- --- .../terms/narrow-copy/narrow-copy.md | 61 +++++++++++++++++++ 1 file changed, 61 insertions(+) create mode 100644 content/pytorch/concepts/tensor-operations/terms/narrow-copy/narrow-copy.md diff --git a/content/pytorch/concepts/tensor-operations/terms/narrow-copy/narrow-copy.md b/content/pytorch/concepts/tensor-operations/terms/narrow-copy/narrow-copy.md new file mode 100644 index 00000000000..fa2c87188b9 --- /dev/null +++ b/content/pytorch/concepts/tensor-operations/terms/narrow-copy/narrow-copy.md @@ -0,0 +1,61 @@ +--- +Title: '.narrow_copy()' +Description: 'Creates a new tensor containing a narrowed subsection of data from the input tensor along a specified dimension.' +Subjects: + - 'Computer Science' + - 'Machine Learning' +Tags: + - 'Functions' + - 'Machine Learning' + - 'Methods' + - 'Python' +CatalogContent: + - 'intro-to-py-torch-and-neural-networks' + - 'paths/computer-science' +--- + +In Pytorch, **`.narrow_copy()`** is a function that creates a new tensor containing the same data as the input tensor but with a narrowed dimension. Unlike [`.narrow()`](https://www.codecademy.com/resources/docs/pytorch/tensor-operations/narrow), which returns a view of the original tensor, `.narrow_copy()` returns a new tensor. + +## Syntax + +```pseudo +torch.narrow_copy(input, dim, start, length) +``` + +- `input`: The input tensor to be narrowed. +- `dim`: The dimension along which the narrowing is applied. +- `start`: The index where the narrowing begins. This can be a positive integer, a negative integer (to index from the end of `dim`), or a 0-dimensional integer tensor. +- `length`: The number of elements to include from the starting position. + +## Example + +The following example demonstrates the usage of the `.narrow_copy()` function: + +```py +import torch + +# Create a 2D tensor +tensor_2d = torch.arange(1, 13).reshape(3, 4) +print(f"Original 2D Tensor:\n{tensor_2d}") + +# Narrow the tensor along rows and create a new tensor +narrowed_tensor = torch.narrow_copy(tensor_2d, 0, 1, 2) +print(f"Narrowed 2D Tensor:\n{narrowed_tensor}") +``` + +The above code produces the following output: + +```shell +Original 2D Tensor: +tensor([[ 1, 2, 3, 4], + [ 5, 6, 7, 8], + [ 9, 10, 11, 12]]) + +Narrowed 2D Tensor: +tensor([[ 5, 6, 7, 8], + [ 9, 10, 11, 12]]) +``` + +In this example, the `.narrow_copy()` function creates a new tensor by narrowing an input tensor along a specific dimension. In the given code, the input tensor is narrowed along rows (dimension 0), starting from index _1_ and including _2_ rows. + +The `.narrow_copy()` function is used to create a new tensor containing a subset of data from an existing tensor without modifying the original tensor. From d4a8fba09db6ce15ee75b918ac2c0db0a4eed77c Mon Sep 17 00:00:00 2001 From: guobyti Date: Mon, 13 Jan 2025 08:58:09 +0200 Subject: [PATCH 28/31] Adding Squash Documentation (#5883) * Create squash.md and squash directory * Update squash.md * Added title, description to squash.md * Implemented the changes. * Update content/git/concepts/squash/squash.md Co-authored-by: Savi Dahegaonkar <124272050+SaviDahegaonkar@users.noreply.github.com> * Update squash.md * Fix lint errors --------- --- content/git/concepts/squash/squash.md | 108 ++++++++++++++++++++++++++ 1 file changed, 108 insertions(+) create mode 100644 content/git/concepts/squash/squash.md diff --git a/content/git/concepts/squash/squash.md b/content/git/concepts/squash/squash.md new file mode 100644 index 00000000000..fb79ffa8cc0 --- /dev/null +++ b/content/git/concepts/squash/squash.md @@ -0,0 +1,108 @@ +--- +Title: 'Squash' +Description: 'Squashing in Git combines multiple commits into one to simplify and clean up the commit history.' +Subjects: + - 'Bash/Shell' + - 'Computer Science' + - 'Developer Tools' +Tags: + - 'Git' + - 'Command Line' + - 'Version Control' +CatalogContent: + - 'learn-the-command-line' + - 'learn-git' +--- + +Merging a series of smaller commits into a cohesive one can significantly clean up a project’s commit history. This practice, commonly known as "**squashing**", is particularly helpful when previous commits contain minor changes that clutter the commit history. + +Though Git doesn’t offer a straightforward `squash` command, it can be achieved through an **interactive rebase**. Below, we explore how to squash your commits for a tidier project history. + +## Syntax + +To squash commits using an _interactive rebase_, the following command can be used: + +```pseudo +git rebase -i HEAD~ +``` + +- `HEAD` refers to the latest commit on the current branch. +- `` specifies how many recent commits to include in the rebase. + +## Example + +Imagine working on a feature branch and generating several incremental commits. Before integrating these changes into the main branch, it’s best to `squash` your commits to maintain a clean history. + +The current commit log might look something like this: + +```shell +12345678 Initial commit +23456789 Added Santa's new address +87654321 Corrected grammar in the address +98765544 Updated house number for Santa +``` + +These last three commits relate to updates and corrections to the same component, and squashing them into a single commit will make the commit history more concise and meaningful. + +### Interactive Rebase: The path to squashing + +To squash the last three commits, initiate an interactive rebase with the following command: + +```shell +git rebase -i HEAD~3 +``` + +Executing the command will launch an editor displaying something similar to this: + +```shell +pick 23456789 Added Santa's new address +pick 87654321 Corrected grammar in the address +pick 98765544 Updated house number for Santa + +# Rebase +# +# Commands: +# p, pick = use commit +# r, reword = use commit, but edit the commit message +# e, edit = use commit, but stop for amending +# s, squash = use commit, but meld into previous commit +# f, fixup = like "squash", but discard this commit's log message +# x, exec = run command (the rest of the line) using shell +# +# These lines can be re-ordered; they are executed from top to bottom. +# +# If you remove a line here THAT COMMIT WILL BE LOST. +# +# However, if you remove everything, the rebase will be aborted. +# +# Note that empty commits are commented out +``` + +The goal is to combine the commits by replacing `pick` with `squash` (or `s`) for all but the first commit: + +```shell +pick 23456789 Added Santa`s new address +squash 87654321 Corrected grammar in the address +squash 98765544 Updated house number for Santa +``` + +After saving and closing the editor, `Git` will prompt the user to draft a new commit message: + +```shell +# This is a combination of 3 commits. +# The first commit's message is: +Added Santa's new address +# This is the 2nd commit message: +Corrected grammar in the address +# This is the 3rd commit message: +Updated house number for Santa +# Lines starting with '#' are ignored, and an empty message cancels the commit. +``` + +Now, create a clear, comprehensive message reflecting the changes these combined commits introduced. + +> **Note**: Remember, lines with `#` are comments and will be excluded. + +Squashing commits via an interactive rebase keeps the project history clean, concise, and easier to navigate. + +> **Note**: Caution is advised when squashing commits in a branch that has already been pushed to a remote repository, as it rewrites history and may cause conflicts. To avoid such issues, perform squashing locally before pushing changes. From ef344c1804460c20aa6f49e7817bee07383df5a5 Mon Sep 17 00:00:00 2001 From: Maria <155121699+MariaRoDigital@users.noreply.github.com> Date: Mon, 13 Jan 2025 07:42:09 -0700 Subject: [PATCH 29/31] fix grammar in Javascript iterator.md (#5941) --- content/javascript/concepts/iterators/iterators.md | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/content/javascript/concepts/iterators/iterators.md b/content/javascript/concepts/iterators/iterators.md index 56e4ad25bae..2a287502c84 100644 --- a/content/javascript/concepts/iterators/iterators.md +++ b/content/javascript/concepts/iterators/iterators.md @@ -26,7 +26,7 @@ The **iterator protocol**, by definition, implements the `next()` method and ret ## Example -This range-based iterator, loops through a collection of integers and satisfies the iteration protocols. +This range-based iterator loops through a collection of integers and satisfies the iteration protocols. ```js function createRangeIterator(min = 0, max = Infinity, step = 1) { @@ -76,7 +76,7 @@ This will output: ## Codebyte Example -Run the below codebyte example to see how an iterator works with a string: +Run the codebyte example below to see how an iterator works with a string: ```codebyte/javascript const str = "Hello"; From 30f61d724ed7e475b96c6b9332e5acaa74a0eca7 Mon Sep 17 00:00:00 2001 From: Virachai Wongsena Date: Mon, 13 Jan 2025 22:25:26 +0700 Subject: [PATCH 30/31] [Term Entry] Python scipy integrate odeint (#5910) * Explanation for using scipy.integrate.odeint() to solve ODEs * Add documentation for odeint() function in SciPy for solving ODEs * Enhance .odeint() function description Refined the description of the .odeint() function to emphasize its role in solving ordinary differential equations using the LSODA method. The updated description highlights its capability to automatically handle both stiff and non-stiff problems. A big thank you to @mamtawardhani for the valuable suggestions! Co-authored-by: Mamta Wardhani * Add hyperlink to .odeint() function description Included a hyperlink in the description of the .odeint() function to provide direct access to the SciPy integrate module documentation. This update improves the usability of the documentation. A big thank you to @mamtawardhani for the valuable suggestion! Co-authored-by: Mamta Wardhani * Update code block language to pseudo for .odeint() Changed the code block language from python to pseudo in the .odeint() function documentation to accurately reflect the content. Thank you so much to @mamtawardhani for the helpful suggestion! Co-authored-by: Mamta Wardhani * Clarify parameter descriptions for .odeint() documentation Improved the parameter descriptions for the .odeint() function documentation by adding detailed explanations and clarifications. This update enhances the overall clarity and usability of the documentation. Thank you so much to @mamtawardhani for the insightful suggestions! Co-authored-by: Mamta Wardhani * Enhance return description for .odeint() documentation Updated the return description for the .odeint() function documentation to specify that it returns a 2D NumPy array, with each row corresponding to the solution at a specific time point in t. Thanks to @mamtawardhani for the helpful suggestion! Co-authored-by: Mamta Wardhani * Update plotting code for .odeint() documentation Modified the plotting code in the .odeint() function documentation to correctly index the solution array and retrieve the actual y values. A big thank you to @mamtawardhani for the valuable suggestion! Co-authored-by: Mamta Wardhani * Update code block language to py for .odeint() documentation Changed the code block language from python to py in the .odeint() function documentation for improved readability and consistency. Many thanks to @mamtawardhani for the suggestion! Co-authored-by: Mamta Wardhani * Add explanation for odeint usage and output image Added a brief explanation of the code and the usage of odeint, emphasizing its role in solving differential equations numerically. Included an output visualization as an image stored under the media folder in the docs directory for better understanding. * Attach the image of the output * explanation of the code and how is odeint used in it moved explanation * Update odeint.md minor fixes * Update content/scipy/concepts/scipy-integrate/terms/odeint/odeint.md * Update content/scipy/concepts/scipy-integrate/terms/odeint/odeint.md * Update content/scipy/concepts/scipy-integrate/terms/odeint/odeint.md * Update content/scipy/concepts/scipy-integrate/terms/odeint/odeint.md * Update content/scipy/concepts/scipy-integrate/terms/odeint/odeint.md * Update content/scipy/concepts/scipy-integrate/terms/odeint/odeint.md * Update content/scipy/concepts/scipy-integrate/terms/odeint/odeint.md * Update odeint.md * Update odeint.md * fix lint errors --------- --- .../scipy-integrate/terms/odeint/odeint.md | 76 ++++++++++++++++++ media/odeint_solution_plot.png | Bin 0 -> 21936 bytes 2 files changed, 76 insertions(+) create mode 100644 content/scipy/concepts/scipy-integrate/terms/odeint/odeint.md create mode 100644 media/odeint_solution_plot.png diff --git a/content/scipy/concepts/scipy-integrate/terms/odeint/odeint.md b/content/scipy/concepts/scipy-integrate/terms/odeint/odeint.md new file mode 100644 index 00000000000..121057fec77 --- /dev/null +++ b/content/scipy/concepts/scipy-integrate/terms/odeint/odeint.md @@ -0,0 +1,76 @@ +--- +Title: '.odeint()' +Description: 'Solves ordinary differential equations in SciPy using the LSODA method, automatically handling stiff and non-stiff problems.' +Subjects: + - 'Computer Science' + - 'Data Science' +Tags: + - 'Data' + - 'Math' + - 'Python' +CatalogContent: + - 'learn-python-3' + - 'paths/computer-science' +--- + +The **`odeint()`** function from SciPy's [`integrate`](https://www.codecademy.com/resources/docs/scipy/scipy-integrate) module is a powerful tool for solving initial value problems for _Ordinary Differential Equations (ODEs)_. + +It integrates a system of ordinary differential equations using the LSODA method from the FORTRAN library `odepack`, which automatically switches between stiff and non-stiff methods based on the problem's characteristics. + +## Syntax + +The general syntax for using `odeint()` is as follows: + +```pseudo +from scipy.integrate import odeint + +solution = odeint(func, y0, t, args=(), Dfun=None, col_deriv=0, full_output=0, ml=None, mu=None, rtol=None, atol=None, tcrit=None, h0=0.0, hmax=0.0, hmin=0.0, ixpr=0, mxstep=500, mxhnil=10, mxordn=12, mxords=5) +``` + +- `func`: A callable that defines the derivative of the system, ({dy}/{dt} = f(y, t, ...)). +- `y0`: Initial condition(s) (array-like). Represents the initial state of the system. +- `t`: Array of time points at which the solution is to be computed (1D array-like). +- `args` (Optional): Tuple of extra arguments to pass to `func`. + +Other parameters are optional and control solver behavior, precision, and output verbosity. + +It returns a 2D [NumPy](https://www.codecademy.com/resources/docs/numpy) array, where each row corresponds to the solution at a specific time point in `t`. + +## Example + +The code below numerically solves a first-order ordinary differential equation using `odeint`. The model function defines the ODE, and `odeint` integrates it over specified time points starting from the initial condition, and the results are plotted to visualize the solution: + +```py +import numpy as np +from scipy.integrate import odeint +import matplotlib.pyplot as plt + +def model(y, t): + dydt = -2 * y + 3 + return dydt + +# Initial condition +y0 = 5 + +# Time points +t = np.linspace(0, 5, 100) + +# Solve ODE +solution = odeint(model, y0, t) + +# Plot results (indexing the solution to get the actual y values) +plt.plot(t, solution[:, 0]) Since solution is a 2D array, we index its first column to extract the solution values. +plt.title('Solution of dy/dt = -2y + 3') +plt.xlabel('Time (t)') +plt.ylabel('y(t)') +plt.grid() +plt.show() +``` + +The output plot shows the numerical solution of the ODE, illustrating how `y(t)` evolves over time: + +![A plot showing the solution of an ODE using odeint, with time on the x-axis and y(t) on the y-axis.](https://raw.githubusercontent.com/Codecademy/docs/main/media/odeint_solution_plot.png) + +`odeint()` is ideal for many scientific and engineering applications due to its robustness and flexibility. + +> For more advanced control or alternative solvers, consider using `scipy.integrate.solve_ivp()`, which offers a more modern API. diff --git a/media/odeint_solution_plot.png b/media/odeint_solution_plot.png new file mode 100644 index 0000000000000000000000000000000000000000..80457bb94e7a67fa697176512a383364d75c9ca0 GIT binary patch literal 21936 zcmdqJbzD{5wm!aS1O*I0L_j2@QAtrk0g>*M5R{fKX-rf^6h)Bk4iUC=C?ZPN25AuK z7B;=%Hx{0I&bjw{?l1oRy`OX57Zz*HHRoJ&K4Xk$JYzo7P*XTUaf$*#kRysW)6Hp&Nowo1_0H$dt~oMG##kMY*dw_hJ`@ zy!~`=Rr@O&&38UJ$y_^jhCSC@Xx{Dvg+S1ajy1iz9Un_Qh;l4&ran8`uPBUgXLaXH zlXNMrQDPeDUZ>q{JWIhvPJT%F82Kwn_BZcWci7lz-pB;Kzx1PdZtGq%+xsQIw)bs* z$Lj``E=~FJJuyE?h#)~DAEHg5V@PEPLXIG#*5pC(OTd%=AN?XDBy#6F%@Kx+U-NdZ zxKF?0qYIgAem~xWFCX|b(S*%VXCWaYYqBWhl9t{N|CAu%kqviPKNlMFM@F@dA_Rhc zWo{XZm8)tT930%@;sy=_pRnyovbaA@g1%MnyjLe@(jra&Z10rU{djZEqu0cXo1I;* zpn5xdZ@r|3n~$$~&g07Z&)c&dDGeM>Vz<8?<~RKK6;EQ4UKdPl-(PH7zCD|RO_ryu z|N7PD`zzM%-*42L1@f*oykzQX3s@IQOHJiEd-hsKM+bVNh}WVq!xM8)ZHdb+16p z$T741?Z|lF#Y<@!8T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00:00:00 2001 From: Sachiko Ponpon <150808503+sachyko@users.noreply.github.com> Date: Tue, 14 Jan 2025 00:49:33 +0900 Subject: [PATCH 31/31] Specifying data types (#5893) * add documentation for specifying data types in Pytorch tensors * Updated tags.md and added new directory for specifying data types * add main file to the branch * Update specifying-data-types.md minor fixes * Update yarn.lock * Update content/pytorch/concepts/tensor-operations/terms/specifiying-data-types/specifying-data-types.md * Update content/pytorch/concepts/tensor-operations/terms/specifiying-data-types/specifying-data-types.md * Update content/pytorch/concepts/tensor-operations/terms/specifiying-data-types/specifying-data-types.md * Update content/pytorch/concepts/tensor-operations/terms/specifiying-data-types/specifying-data-types.md * Fix file path --------- --- .../specifying-data-types.md | 69 +++++++++++++++++++ documentation/tags.md | 1 + 2 files changed, 70 insertions(+) create mode 100644 content/pytorch/concepts/tensor-operations/terms/specifying-data-types/specifying-data-types.md diff --git a/content/pytorch/concepts/tensor-operations/terms/specifying-data-types/specifying-data-types.md b/content/pytorch/concepts/tensor-operations/terms/specifying-data-types/specifying-data-types.md new file mode 100644 index 00000000000..7d77c8f1ff3 --- /dev/null +++ b/content/pytorch/concepts/tensor-operations/terms/specifying-data-types/specifying-data-types.md @@ -0,0 +1,69 @@ +--- +Title: 'Specifying Data Types' +Description: 'Determines how tensors are stored and processed, impacting precision, memory usage, and computation speed.' +Subjects: + - 'Data Science' + - 'Machine Learning' + - 'Deep Learning' +Tags: + - 'Pytorch' + - 'Tensor' + - 'Data Types' +CatalogContent: + - 'learn-Intro-to-PyTorch-and-Neural-Networks' + - 'paths/data-science' +--- + +In PyTorch, specifying the data types for [`tensors`](https://www.codecademy.com/resources/docs/pytorch/tensors) is crucial as they are the core data structures used to store and process data. Each tensor's data type (`dtype`) defines the kind of values it holds (e.g., `integer`, `float`, `boolean`), ensuring precision, improving performance, and maintaining compatibility during computations. + +## Syntax + +To specify a data type in a PyTorch tensor, use the `dtype` parameter when creating a tensor or the `.to()` method for converting an existing one. + +### For specifying `dtype` when creating a tensor + +```pseudo +torch.tensor(data, dtype=torch.) +``` + +- `data`: The input data used to create the tensor. This can be a list, NumPy array, or another tensor. +- `dtype`: Specifies the data type of the tensor. Common data types include: + - `torch.float32` (default): 32-bit floating-point + - `torch.float64`: 64-bit floating-point + - `torch.int32`: 32-bit integer + - `torch.int64`: 64-bit integer + - `torch.bool`: Boolean + +### For converting an existing tensor to a different data type + +```pseudo +tensor.to(torch.) +``` + +## Example + +In the example below a tensor is created with a specified data type, another with a different type, and one tensor is converted to a new data type: + +```py +import torch + +# Creating a float32 tensor +float_tensor = torch.tensor([1.0, 2.0, 3.0], dtype=torch.float32) +print(float_tensor) + +# Creating an int64 tensor +int_tensor = torch.tensor([1, 2, 3], dtype=torch.int64) +print(int_tensor) + +# Converting a tensor to a different data type +converted_tensor = float_tensor.to(torch.int64) +print(converted_tensor) +``` + +The code above generates the output as: + +```shell +tensor([1., 2., 3.]) +tensor([1, 2, 3]) +tensor([1, 2, 3]) +``` diff --git a/documentation/tags.md b/documentation/tags.md index 3a68d0a5742..9d798b7ca7c 100644 --- a/documentation/tags.md +++ b/documentation/tags.md @@ -336,6 +336,7 @@ Tags Target Technical Interviews Templates +Tensor TensorFlow Text-To-Image Text Processing