diff --git a/bin/concept-of-the-week.txt b/bin/concept-of-the-week.txt index a71a382e779..a47e69cb203 100644 --- a/bin/concept-of-the-week.txt +++ b/bin/concept-of-the-week.txt @@ -1 +1 @@ -content/uiux/concepts/logo/logo.md \ No newline at end of file +content/rust/concepts/conditionals/conditionals.md \ No newline at end of file diff --git a/content/ai/concepts/machine-learning/machine-learning.md b/content/ai/concepts/machine-learning/machine-learning.md index 5483d546047..887f6a2e80d 100644 --- a/content/ai/concepts/machine-learning/machine-learning.md +++ b/content/ai/concepts/machine-learning/machine-learning.md @@ -1,6 +1,6 @@ --- Title: 'Machine Learning' -Description: 'Machine learning (ML) is a discipline of computer science that relates to using data and algorithms to develop computer programs that improve their performance at tasks without being explicitly programmed to do so.' +Description: 'Machine learning is a branch of computer science that uses data and algorithms to create programs that enhance performance at tasks without explicit programming.' Subjects: - 'Machine Learning' - 'Data Science' @@ -16,7 +16,7 @@ CatalogContent: - 'paths/data-science' --- -**Machine learning (ML)** is a discipline of computer science that relates to using data and algorithms to develop computer programs that improve their performance at tasks without being explicitly programmed to do so. Machine Learning is considered a branch of Artificial Intelligence as some machine learning algorithms are designed to imitate the way that humans learn and interact with their environment. +**Machine learning (ML)** is a discipline of computer science that uses data and algorithms to develop computer programs that improve their performance at tasks without being explicitly programmed to do so. Machine Learning is considered a branch of Artificial Intelligence, as some machine learning algorithms are designed to imitate the way that humans learn and interact with their environment. ## Branches of Machine Learning @@ -38,13 +38,13 @@ Machine Learning algorithms that receive unlabeled data as input and produce a g - Clustering: Recognize patterns and structures in unlabeled data by grouping them into clusters. - K-Means: Categorizes data points into clusters based on their proximity to cluster centroids. - - Hierarchical Agglomerative Clustering: Groups data points into clusters based on various measures of similarity such as smallest average distance between all points, minimal variance between data points, or smallest maximum distance between data points. -- Dimensionality Reduction: Scale down the dimensions in the dataset from a high-dimensional space into a low-dimensional space, while maintaining the maximum amount of relevant information. + - Hierarchical Agglomerative Clustering: Groups data points into clusters based on various measures of similarity, such as the smallest average distance between all points, minimal variance between data points, or smallest maximum distance between data points. +- Dimensionality Reduction: Scale down the dimensions in the dataset from a high-dimensional space into a low-dimensional space while maintaining the maximum amount of relevant information. - Principal Component Analysis (PCA): Reduces the dimensionality of a dataset to the 'n' number of principal dimensions that contain the most valuable information. ### Reinforcement Learning -Machine learning algorithms that act as agents in an environment, which receive a current state, environment, reward, and goal as input and produce a policy of best action relative to the stated goal as output. +Machine learning algorithms that act as agents in an environment receive a current state, environment, reward, and goal as input and produce a policy of best action relative to the stated goal as output. - Model-Free: Act as trial-and-error algorithms that use only real samples of the environment to calculate optimal actions instead of the transition probability distribution to create a model of the environment. - Model-Based: Create models of the environment to generate predictions of the next state and reward to calculate optimal actions. @@ -52,7 +52,7 @@ Machine learning algorithms that act as agents in an environment, which receive Some methods used in reinforcement learning include: - Markov Decision Processes (MDPs): Use a model of the environment based on their state transition probability and reward functions to create a policy of optimal action and satisfy the Markov property. -- Monte-Carlo methods: Model-Free randomized algorithms that learn from episodes of experience whether continuous or terminal to calculate the value for a state based on the average return from those experiences. +- Monte-Carlo methods: Model-Free randomized algorithms that learn from episodes of experience, whether continuous or terminal, to calculate the value for a state based on the average return from those experiences. - Q-Learning/Deep Q-Learning: Model-Free algorithms that focus on maximizing the expected value of reward using q-tables, or artificial neural networks. ## Machine Learning vs. Deep Learning @@ -70,6 +70,6 @@ Based on the evaluation results, the model's user might modify the model's hyper ## Evaluation -There are several methods to accurately evaluate the performance of ML algorithms. Methods vary based on which algorithm is being evaluated, and for which purpose. For classifiers such as Logistic Regression, confusion matrices inform analysts of the number of true and false positives as well as negatives to calculate values such as recall, precision, and F1 scores. +There are several methods to accurately evaluate the performance of ML algorithms. Methods vary based on which algorithm is being evaluated and for which purpose. For classifiers such as Logistic Regression, confusion matrices inform analysts of the number of true and false positives as well as negatives to calculate values such as recall, precision, and F1 scores. These values help analysts understand if their models are underfitting or overfitting, which is critical to improving and maintaining their performance. diff --git a/content/ai/concepts/neural-networks/terms/gaussian-activation-function/gaussian-activation-function.md b/content/ai/concepts/neural-networks/terms/gaussian-activation-function/gaussian-activation-function.md index 02a5e15055e..dc12b2e2718 100644 --- a/content/ai/concepts/neural-networks/terms/gaussian-activation-function/gaussian-activation-function.md +++ b/content/ai/concepts/neural-networks/terms/gaussian-activation-function/gaussian-activation-function.md @@ -1,6 +1,6 @@ --- Title: 'Gaussian Activation Function' -Description: 'The Gaussian activation function takes the input and transforms it into a Gaussian or Normal Distribution curve, with the output values varying depending on the specific implementation and parameters.' +Description: 'The Gaussian activation function shapes the output of a neuron into a bell-shaped curve that is symmetric about its unique peak.' Subjects: - 'Machine Learning' - 'Data Science' @@ -19,7 +19,7 @@ A **Gaussian activation function** is a mathematical function known as the norma ## Gaussian Function -Characterized by its bell-shaped graph, where most data points are near the middle (average), and the likelihood of getting values decreases as you move away from the average. This curve is symmetric, meaning that the probabilities of getting values above the average are the same as getting values below the average. +The Gaussian function is characterized by its bell-shaped graph, where most data points are near the middle (average), and the likelihood of getting values decreases as you move away from the average. This curve is symmetric, meaning that the probabilities of getting values above the average are the same as getting values below the average. ![Gaussian function](https://raw.githubusercontent.com/Codecademy/docs/main/media/gaussian-function-1d.png) @@ -27,21 +27,21 @@ Characterized by its bell-shaped graph, where most data points are near the midd ### Advantages -- Smooth and Continuous: The Gaussian activation function is smooth and continuous everywhere, making it fully differentiable with a consistent gradient. This property simplifies the process for optimization algorithms to find the best solution. -- Non-Linear Properties: It introduces non-linearity to the neural network, enabling the network to capture complex relationships between inputs and outputs. +- **Smooth and Continuous**: The Gaussian activation function is smooth and continuous everywhere, making it fully differentiable with a consistent gradient. This property simplifies the process for optimization algorithms to find the best solution. +- **Non-Linear Properties**: It introduces non-linearity to the neural network, enabling the network to capture complex relationships between inputs and outputs. ### Disadvantages -- Risk of Overfitting: A more complex network can lead to overfitting, where the model overly specializes in the training data and fails to generalize to new, unseen data. -- Increased Network Complexity: Implementing the Gaussian function can add complexity to the neural network, often requiring more computational power and time for training. -- Potential for Local Minima Traps: The Gaussian function may increase the likelihood of the network getting trapped in local minima during the optimization process. This can hinder the achievement of the most optimal solutions. +- **Risk of Overfitting**: A more complex network can lead to overfitting, where the model overly specializes in the training data and fails to generalize to new, unseen data. +- **Increased Network Complexity**: Implementing the Gaussian function can add complexity to the neural network, often requiring more computational power and time for training. +- **Potential for Local Minima Traps**: The Gaussian function may increase the likelihood of the network getting trapped in local minima during the optimization process. This can hinder the achievement of the most optimal solutions. -## Practical Uses for Gaussian Activation Functions +## Practical Uses for the Gaussian Activation Function -Gaussian activation function plays a pivotal role in various AI and machine learning applications across different industries, such as: +The Gaussian activation function plays a pivotal role in various AI and machine learning applications across different industries, such as: -- Image Processing and Computer Vision: In image processing, Gaussian functions are used for smoothing or blurring images. This is crucial in pre-processing steps to reduce noise and improve the quality of feature extraction, which is vital in computer vision tasks like object detection, face recognition, and image segmentation. Additionally, Gaussian functions are used for applications like earth observation, weather forecasting, and environmental monitoring. -- Regression Analysis: Gaussian functions are foundational in Gaussian Processes, a powerful tool for regression analysis in machine learning. They provide a probabilistic approach to modeling uncertainties in predictions, which is important in fields like financial modeling, environmental modeling, and robotics. For instance, they help in modeling stock price variations and market trends, allowing financial analysts to predict future movements and manage risks more effectively. -- Pattern Recognition and Classification: Gaussian functions are often used in algorithms for pattern recognition and classification tasks. In these scenarios, they help to model the distribution of data points, allowing the system to differentiate between various categories or classes effectively. For example, in retail and e-commerce, Gaussian functions aid in customer behavior analysis and sales forecasting in the retail sector. By modeling customer purchase patterns, businesses can predict future sales trends, optimize inventory management, and enhance personalized marketing strategies. -- Natural Language Processing (NLP): In NLP, Gaussian distributions can be used in probabilistic models like Gaussian Mixture Models (GMMs) for clustering or classifying text data. They help in understanding the underlying structure of language data, which is essential for applications like sentiment analysis, topic modeling, and language generation. -- Reinforcement Learning: In reinforcement learning, especially in continuous action spaces, Gaussian functions are used to model the probability distribution of actions. This assists in the exploration-exploitation trade-off, where the algorithm needs to decide between exploring new actions and exploiting known rewarding actions. +- **Image Processing and Computer Vision**: In image processing, Gaussian functions are used for smoothing or blurring images. This is crucial in pre-processing steps to reduce noise and improve the quality of feature extraction, which is vital in computer vision tasks like object detection, face recognition, and image segmentation. Additionally, Gaussian functions are used for applications like earth observation, weather forecasting, and environmental monitoring. +- **Regression Analysis**: Gaussian functions are foundational in Gaussian Processes, a powerful tool for regression analysis in machine learning. They provide a probabilistic approach to modeling uncertainties in predictions, which is important in fields like financial modeling, environmental modeling, and robotics. For instance, they help model stock price variations and market trends, allowing financial analysts to predict future movements and manage risks more effectively. +- **Pattern Recognition and Classification**: Gaussian functions are often used in algorithms for pattern recognition and classification tasks. In these scenarios, they help to model the distribution of data points, allowing the system to differentiate between various categories or classes effectively. For example, in retail and e-commerce, Gaussian functions aid customer behavior analysis and sales forecasting. By modeling customer purchase patterns, businesses can predict future sales trends, optimize inventory management, and enhance personalized marketing strategies. +- **Natural Language Processing (NLP)**: In NLP, Gaussian distributions can be used in probabilistic models like Gaussian Mixture Models (GMMs) for clustering or classifying text data. They help in understanding the underlying structure of language data, which is essential for applications like sentiment analysis, topic modeling, and language generation. +- **Reinforcement Learning**: In reinforcement learning, especially in continuous action spaces, Gaussian functions are used to model the probability distribution of actions. This assists in the exploration-exploitation trade-off, where the algorithm needs to decide between exploring new actions and exploiting known rewarding actions. diff --git a/content/ai/concepts/neural-networks/terms/stochastic-gradient-descent/stochastic-gradient-descent.md b/content/ai/concepts/neural-networks/terms/stochastic-gradient-descent/stochastic-gradient-descent.md new file mode 100644 index 00000000000..85877803682 --- /dev/null +++ b/content/ai/concepts/neural-networks/terms/stochastic-gradient-descent/stochastic-gradient-descent.md @@ -0,0 +1,182 @@ +--- +Title: 'Stochastic Gradient Descent' +Description: 'Stochastic Gradient Descent is an optimizer algorithm that minimizes the loss function in machine learning and deep learning models.' +Subjects: + - 'Machine Learning' + - 'Computer Science' +Tags: + - 'AI' + - 'Neural Networks' +CatalogContent: + - 'paths/computer-science' + - 'paths/data-science' +--- + +**Stochastic Gradient Descent** (SGD) is an optimization algorithm used to minimize the loss function in machine learning and deep learning models. It is a variant of the traditional **Gradient Descent** (GD) algorithm. SGD updates the weights and biases of a model, such as those in an Artificial Neural Network (ANN), during the backpropagation process. + +The term `stochastic` refers to the randomness involved in the algorithm. Instead of using the entire dataset to compute gradients as in batch `gradient descent`, SGD uses a randomly selected data point (or a small mini-batch) to perform each update. For instance, if the dataset contains 500 rows, SGD will update the model parameters 500 times in one epoch, each time using a different randomly chosen data point (or small batch). + +This approach significantly reduces computation time, especially for large datasets, making SGD faster and more scalable. SGD is used for training models like neural networks, support vector machines (SVMs), and logistic regression. However, it introduces more noise into the learning process, which can lead to less stable convergence but also helps escape local minima, making it suitable for non-convex problems. + +## Algorithms Step + +- At each iteration, a random sample is selected from the training dataset. +- The gradient of the cost function with respect to the model parameters is computed based on the selected sample. +- The model parameters are updated using the computed gradient and the learning rate. +- The process is repeated for multiple iterations until convergence or a specified number of epochs. + +## Formula + +$$ +\large \theta = \theta - \alpha \cdot \nabla J(\theta ; x_i, y_i) +$$ + +Where: + +- `θ` represents the model parameter (weight or bias) being updated. +- `α` is the learning rate, a hyperparameter that controls the step size of the update. +- `∇J(θ;xi,yi)` is the gradient of the cost or loss function `J` with respect to the model parameter `θ`, computed based on a single training sample `(xi,yi)`. + +## Advantages + +- **Faster convergence:** SGD updates parameters more frequently hence it takes less time to converge especially for large datasets. +- **Reduced Computation Time:** SGD takes only a subset of dataset or batch for each update. This makes it easy to handle large datasets and compute faster. +- **Avoid Local Minima:** The noise introduced by updating parameters with individual data points or small batches can help escape local minima.This can potentially lead to better solutions in complex, non-convex optimization problems. +- **Online Learning:** SGD can be used in scenarios where data is arriving sequentially (online learning).- It allows models to be updated continuously as new data comes in. + +## Disadvantages + +- **Noisy Updates:** Updates are based on a single data point or small batch, which introduces variability in the gradient estimates.This noise can cause the algorithm to converge more slowly or oscillate around the optimal solution. +- **Convergence Issues:** The noisy updates can lead to less stable convergence and might make it harder to reach the exact minimum of the loss function.Fine-tuning the learning rate and other hyperparameters becomes crucial to achieving good results. +- **Hyperparameter Sensitivity:** - SGD's performance is sensitive to the choice of learning rate and other hyperparameters.Finding the right set of hyperparameters often requires experimentation and tuning. + +## Example + +The following code demonstrates **Stochastic Gradient Descent** (SGD) to fit a line to data points. Starting with initial guesses for the slope (`m`) and intercept (`b`), it updates these values iteratively by calculating the gradients of the **Mean Squared Error** (MSE) loss. The parameters are adjusted step-by-step based on the gradients, reducing the error between predicted and actual values: + +```python +import numpy as np + +# Data points (x, y) where the true line is y = 2x +x = np.array([1, 2, 3, 4, 5]) +y = np.array([2, 4, 6, 8, 10]) + +# Initial guess for parameters (slope, intercept) +params = np.array([0.0, 0.0]) + +# Learning rate and epochs +learning_rate = 0.01 +epochs = 1000 + +# Model: y = mx + b +def model(params, x): + m, b = params + return m * x + b + +# MSE loss function +def loss(pred, actual): + return np.mean((pred - actual) ** 2) # Using mean instead of sum + +# Compute gradients (partial derivatives) +def gradients(params, x, y): + m, b = params + pred = model(params, x) + grad_m = 2 * (pred - y) * x # Gradient for m + grad_b = 2 * (pred - y) # Gradient for b + return np.array([grad_m, grad_b]) + +# Training history +history = [] + +# SGD: Update parameters +for epoch in range(epochs): + total_loss = 0 + # Shuffle data + indices = np.random.permutation(len(x)) + x_shuffled = x[indices] + y_shuffled = y[indices] + + for i in range(len(x)): + # Forward pass + pred = model(params, x_shuffled[i]) + loss_value = loss(pred, y_shuffled[i]) + + # Compute gradients + grads = gradients(params, x_shuffled[i], y_shuffled[i]) + + # Update parameters + params -= learning_rate * grads + total_loss += loss_value + + # Store loss for plotting + avg_loss = total_loss / len(x) + history.append(avg_loss) + + if epoch % 100 == 0: # Print loss every 100 epochs + print(f"Epoch {epoch}, Loss: {avg_loss:.6f}") + +print(f"Final parameters: m = {params[0]:.4f}, b = {params[1]:.4f}") +``` + +The output of the code is as follows: + +```shell +Epoch 0, Loss: 22.414958 +Epoch 100, Loss: 0.001293 +Epoch 200, Loss: 0.000037 +Epoch 300, Loss: 0.000001 +Epoch 400, Loss: 0.000000 +Epoch 500, Loss: 0.000000 +Epoch 600, Loss: 0.000000 +Epoch 700, Loss: 0.000000 +Epoch 800, Loss: 0.000000 +Epoch 900, Loss: 0.000000 +Final parameters: m = 2.0000, b = 0.0000 +``` + +> **Note**: The output may vary depending on factors like the initial parameter values, learning rate, and number of epochs. + +## codebyte Example + +Here’s a Python code snippet demonstrating how to implement SGD for linear regression: + +```codebyte/python +import numpy as np + +# Generate synthetic data +np.random.seed(42) +X = 2 * np.random.rand(100, 1) +y = 4 + 3 * X + np.random.randn(100, 1) + +# Add a bias term (X0 = 1) to the input data +X_b = np.c_[np.ones((100, 1)), X] # Add a column of ones for the intercept term + +# Initialize parameters +m, n = X_b.shape +theta = np.random.randn(n, 1) # Initial weights +learning_rate = 0.01 +n_iterations = 1000 + +# Stochastic Gradient Descent function +def stochastic_gradient_descent(X, y, theta, learning_rate, n_iterations): + m = len(y) + for iteration in range(n_iterations): + # Shuffle the data + indices = np.random.permutation(m) + X_shuffled = X[indices] + y_shuffled = y[indices] + + # Update weights for each sample + for i in range(m): + xi = X_shuffled[i:i+1] + yi = y_shuffled[i:i+1] + gradient = 2 * xi.T.dot(xi.dot(theta) - yi) + theta -= learning_rate * gradient + + return theta + +# Perform SGD +theta_final = stochastic_gradient_descent(X_b, y, theta, learning_rate, n_iterations) + +print("Optimized weights:", theta_final) +``` diff --git a/content/ai/concepts/search-algorithms/terms/a-star-search/a-star-search.md b/content/ai/concepts/search-algorithms/terms/a-star-search/a-star-search.md index 7673cd2c82f..f1d7e46eb5c 100644 --- a/content/ai/concepts/search-algorithms/terms/a-star-search/a-star-search.md +++ b/content/ai/concepts/search-algorithms/terms/a-star-search/a-star-search.md @@ -88,14 +88,112 @@ Exploring **C**: ![a-star-6](https://raw.githubusercontent.com/Codecademy/docs/main/media/a-star-tree-6.png) -The next node in the open list is again **B**. However, because **B** has already been explored, meaning a shortest path to **B** has been found, it is not explored again and the algorithm continues to the next candidate. +The next node in the open list is again **B**. However, because **B** has already been explored, meaning the shortest path to **B** has been found, it is not explored again, and the algorithm continues to the next candidate. ![a-star-7](https://raw.githubusercontent.com/Codecademy/docs/main/media/a-star-tree-7.png) -The next node to be explored is the goal node **G**, meaning the shortest path to **G** has been found! The path is constructed by tracing the graph backward from **G** to **S**: +The next node to be explored is the goal node **G**, meaning the shortest path to **G** has been found! The path is constructed by tracing the graph backwards from **G** to **S**: ![a-star-8](https://raw.githubusercontent.com/Codecademy/docs/main/media/a-star-tree-8.png) ## Using the A\* Algorithm -This algorithm is guaranteed to find a shortest path if one exists. One of the main uses of this algorithm is route planning. However, there are many other uses. +This algorithm is guaranteed to find the shortest path if one exists. One of the main uses of this algorithm is route planning, but there are many other uses. + +## Example Code + +Here is an example of the A\* algorithm implemented in Python that solves the above example graph: + +```py +from heapq import heappop, heappush + +def a_star_search(graph: dict, start: str, goal: str, heuristic_values: dict) -> int: + ''' + A* search algorithm implementation. + + @param graph: The graph to search. + @param start: The starting node. + @param goal: The goal node. + @param heuristic_values: The heuristic values for each node. The goal node must be admissible, and the heuristic value must be 0. + @return: The path cost from the start node to the goal node. + ''' + + # A min heap is used to implement the priority queue for the open list. + # The heapq module from Python's standard library is utilized. + # Entries in the heap are tuples of the form (cost, node), ensuring that the entry with the lowest cost is always smaller during comparisons. + # The heapify operation is not required, as the heapq module maintains the heap invariant after every push and pop operation. + + # The closed list is implemented as a set for efficient membership checking. + + open_list, closed_list = [(heuristic_values[start], start)], set() + + while open_list: + cost, node = heappop(open_list) + + # The algorithm ends when the goal node has been explored, NOT when it is added to the open list. + if node == goal: + return cost + + if node in closed_list: + continue + + closed_list.add(node) + + # Subtract the heuristic value as it was overcounted. + cost -= heuristic_values[node] + + for neighbor, edge_cost in graph[node]: + if neighbor in closed_list: + continue + + # f(x) = g(x) + h(x), where g(x) is the path cost and h(x) is the heuristic. + neighbor_cost = cost + edge_cost + heuristic_values[neighbor] + heappush(open_list, (neighbor_cost, neighbor)) + + return -1 # No path found + +EXAMPLE_GRAPH = { + 'S': [('A', 4), ('B', 10), ('C', 11)], + 'A': [('B', 8), ('D', 5)], + 'B': [('D', 15)], + 'C': [('D', 8), ('E', 20), ('F', 2)], + 'D': [('F', 1), ('I', 20), ('H', 16)], + 'E': [('G', 19)], + 'F': [('G', 13)], + 'H': [('J', 2), ('I', 1)], + 'I': [('K', 13), ('G', 5), ('J', 5)], + 'J': [('K', 7)], + 'K': [('G', 16)] +} + +# Node heuristic values (admissible heuristic values for the nodes) +EXAMPLE_HEURISTIC_VALUES = { + 'S': 7, + 'A': 8, + 'B': 6, + 'C': 5, + 'D': 5, + 'E': 3, + 'F': 3, + 'G': 0, + 'H': 7, + 'I': 4, + 'J': 5, + 'K': 3 +} + +EXAMPLE_RESULT = a_star_search(EXAMPLE_GRAPH, 'S', 'G', EXAMPLE_HEURISTIC_VALUES) +print(EXAMPLE_RESULT) +``` + +The code above produces the following output: + +```shell +23 +``` + +## Complexity Analysis + +For time complexity, one might notice that each heappush corresponds to an edge, which would be the dominating complexity for most cases. Indeed, A\* is equivalent to Dijkstra's algorithm when the heuristic function is 0, and A\* is equivalent to Dijkstra's algorithm with reduced cost when the heuristic function is admissible i.e. `O(V+Elog(V))` time complexity. + +However, a good heuristic function can drastically decrease A*'s complexity. The idea here is we need to look at exponentially fewer nodes with a better heuristic. So the time and space complexity are actually `O(b1^d)`, where b1 is the effective branching factor, i.e., an empirical average of neighboring nodes not in the closed list, and d is the search depth, i.e., optimal path length. The large space complexity is the biggest disadvantage of the A* search, giving rise to other algorithm variations. diff --git a/content/c-sharp/concepts/conditionals/conditionals.md b/content/c-sharp/concepts/conditionals/conditionals.md index c093a0cad55..d0da743053a 100644 --- a/content/c-sharp/concepts/conditionals/conditionals.md +++ b/content/c-sharp/concepts/conditionals/conditionals.md @@ -132,3 +132,33 @@ string getInput1(int input1) => input1 === 10 ? "I returned true" : "I returned Console.WriteLine(getInput1(10)); // Output: "I returned true" Console.WriteLine(getInput1(5)); // Output: "I returned false" ``` + +## Codebyte Example + +Run the following codebyte example to understand how conditionals work in C#: + +```codebyte/csharp +using System; + +class Program +{ + static void Main() + { + int number = 10; + + // Using if-else conditional statements + if (number > 0) + { + Console.WriteLine("The number is positive."); + } + else if (number < 0) + { + Console.WriteLine("The number is negative."); + } + else + { + Console.WriteLine("The number is zero."); + } + } +} +``` diff --git a/content/c-sharp/concepts/deque/deque.md b/content/c-sharp/concepts/deque/deque.md index dad1bd08dc8..3f8b76227da 100644 --- a/content/c-sharp/concepts/deque/deque.md +++ b/content/c-sharp/concepts/deque/deque.md @@ -1,6 +1,6 @@ --- Title: 'Deque' -Description: 'A deque is a type of data structure that allows insert and delete elements at both ends.' +Description: 'Deque is a type of data structure that allows insertion and removal of elements from both the front and rear.' Subjects: - 'Computer Science' - 'Code Foundations' @@ -13,9 +13,11 @@ CatalogContent: - 'paths/computer-science' --- -A **deque** is a data structure that allows elements to be added or removed from both ends, making it more versatile than a traditional queue or stack. In `C#` there is no build-in `deque` but it can be impleted using `LinkedList` and `List` classes `C#`. +`Deque` (Double-Ended Queue) is a type of data structure that allows insertion and removal of elements from both the front and rear. In `C#`, it can be implemented using `LinkedList` and `List`. -## Implementing using LinkedList Class +## Creating a Deque using LinkedList Class + +To create a deque in `C#`, use `LinkedList`, where `T` defines the type of elements stored. ```pseudo LinkedList deque = new LinkedList(); @@ -23,7 +25,7 @@ LinkedList deque = new LinkedList(); - `T`: Specifies the element type. -## Example 1 +### Example The below example shows how to implement deque using `LinkedList`. @@ -65,7 +67,9 @@ Output: 3 ``` -## Implementing using List Class +## Creating a Deque using List Class + +To create a deque in `C#`, use `List`, where `T` defines the type of elements stored. ```pseudo List deque = new List(); @@ -73,7 +77,7 @@ List deque = new List(); - `T`: Specifies the element type. -## Example 2 +### Example The below example shows how to implement deque using `List`. @@ -107,3 +111,42 @@ class Program { } } ``` + +Output: + +```shell +1 +3 +``` + +## Codebyte Example + +Use this example to experiment with implementing a `Deque` using `LinkedList`. Enjoy coding! + +```codebyte/csharp +using System; +using System.Collections.Generic; + +public class Example +{ + public static void Main() + { + LinkedList deque = new LinkedList(); + + // Add elements to the front and rear + deque.AddLast(10); // Rear + deque.AddFirst(5); // Front + deque.AddLast(15); // Rear + + // Remove elements from front and rear + deque.RemoveFirst(); // Removes 5 (Front) + deque.RemoveLast(); // Removes 15 (Rear) + + // Display the remaining element + foreach (var item in deque) + { + Console.WriteLine(item); + } + } +} +``` diff --git a/content/c-sharp/concepts/math-functions/terms/asin/asin.md b/content/c-sharp/concepts/math-functions/terms/asin/asin.md index dec37ba8491..6d9159ee4f7 100644 --- a/content/c-sharp/concepts/math-functions/terms/asin/asin.md +++ b/content/c-sharp/concepts/math-functions/terms/asin/asin.md @@ -24,6 +24,36 @@ Math.Asin(value); Returns an angle measured in radians, of type `double`, whose sine is `value`. If an invalid value is passed to the function, or no value is passed at all, `NaN` is returned. +## Example + +The following example prints the results of the `Math.Asin()` method for three different values: + +```cs +using System; + +public class Example +{ + static void Main() + { + double a = Math.Asin(0.5); + double b = Math.Asin(1); + double c = Math.Asin(-2); + + Console.WriteLine(a); + Console.WriteLine(b); + Console.WriteLine(c); + } +} +``` + +This results in the following output: + +```shell +0.523598775598299 +1.5707963267949 +NaN +``` + ## Codebyte Example ```codebyte/csharp diff --git a/content/c-sharp/concepts/math-functions/terms/atan/atan.md b/content/c-sharp/concepts/math-functions/terms/atan/atan.md index 8a175f3d330..804715a1e9d 100644 --- a/content/c-sharp/concepts/math-functions/terms/atan/atan.md +++ b/content/c-sharp/concepts/math-functions/terms/atan/atan.md @@ -12,7 +12,7 @@ CatalogContent: - 'paths/computer-science' --- -**Math.Atan()** is a static method that calculates the inverse tangent of a given number, in radians. +**`Math.Atan()`** is a static method that calculates the inverse tangent of a given number, in radians. ## Syntax @@ -23,9 +23,36 @@ Math.Atan(x); - The `Math.Atan()` method takes one double as an argument and returns a double. - Using this method requires the `System` namespace. +## Example + +This example first uses the `Math.Atan()` method to compute the arctangent of an angle in radians and then converts it to degrees: + +```cs +using System; + +class sample +{ + public static void Main() + { + double value = 1.0; // The tangent of an angle + double angleInRadians = Math.Atan(value); + Console.WriteLine("The arctangent of the angle in radians: {0}",angleInRadians); + double angleInDegrees = angleInRadians * (180 / Math.PI); + Console.WriteLine("The arctangent of the angle in degrees: {0}",angleInDegrees); + } +} +``` + +The above code creates the following output: + +```shell +The arctangent of the angle in radians: 0.7853981633974483 +The arctangent of the angle in degrees: 45 +``` + ## Codebyte Example -The following example uses `Math.Atan()` to return the arctangent of a right angled triangle, where the side opposite the angle is equal to 7, and the side adjacent is 5. +The following example uses `Math.Atan()` to return the arctangent of a right angled triangle, where the side opposite the angle is equal to 7, and the side adjacent is 5: ```codebyte/csharp namespace AtanExample { diff --git a/content/c-sharp/concepts/math-functions/terms/tan/tan.md b/content/c-sharp/concepts/math-functions/terms/tan/tan.md index 94e32edf7c9..ca54086b595 100644 --- a/content/c-sharp/concepts/math-functions/terms/tan/tan.md +++ b/content/c-sharp/concepts/math-functions/terms/tan/tan.md @@ -28,6 +28,36 @@ The `Math.Tan()` method takes only one parameter, `angle`, an angle in radians o - `NegativeInfinity` - `PositiveInfinity` +## Example + +The following example converts 30 degrees to radians and then uses the `Math.Tan()` method to calculate the tangent of that angle. Finally, `Console.WriteLine()` outputs the result to the console: + +```cs +using System; + +public class Example { + public static void Main(string[] args) { + // Define an angle in degrees + double degrees = 30; + + // Convert the angle to radians + double radians = degrees * Math.PI/180; + + // Calculate the tangent of the angle + double tangent = Math.Tan(radians); + + // Display the result + Console.WriteLine("The tangent of " + degrees + " degrees is: " + tangent); + } +} +``` + +The above example will result in the following output: + +```shell +The tangent of 30 degrees is: 0.5773502691896257 +``` + ## Codebyte Example The following example is runnable and returns the tangent of the `angle` given in degrees: diff --git a/content/c-sharp/concepts/strings/terms/concat/concat.md b/content/c-sharp/concepts/strings/terms/concat/concat.md new file mode 100644 index 00000000000..f6ee8142195 --- /dev/null +++ b/content/c-sharp/concepts/strings/terms/concat/concat.md @@ -0,0 +1,72 @@ +--- +Title: '.Concat()' +Description: 'Combines two or more strings together into a single string.' +Subjects: + - 'Code Foundations' + - 'Computer Science' +Tags: + - 'Methods' + - 'Lists' + - 'Loops' + - 'Strings' +CatalogContent: + - 'learn-c-sharp' + - 'paths/computer-science' +--- + +The **`.Concat()`** [method](https://www.codecademy.com/resources/docs/c-sharp/methods) combines strings by appending one string to the end of another. This method is similar in function to using the `+` or `+=` [operator](https://www.codecademy.com/resources/docs/c-sharp/operators) to concatenate strings, though the compiler handles those operators differently for optimization in certain scenarios. + +## Syntax + +```pseudo +string.Concat(string1, string2, ...) +``` + +- `string1, string2, ...`: The strings that will be concatenated together. + +## Example + +The following example uses the `.Concat()` method to combine three strings: + +```cs +using System; + +public class ConcatMethod +{ + public static void Main() + { + string firstString = "Hello"; + string secondString = "World!"; + string fullSentence = string.Concat(firstString, " ", secondString); + Console.WriteLine(fullSentence); + } +} +``` + +This results in the following output: + +```shell +Hello World! +``` + +## Codebyte Example + +The below codebyte example demonstrates how `.Concat()` can be used with a `foreach` [loop](https://www.codecademy.com/resources/docs/c-sharp/loops) to iterate through a list and output multiple concatenated strings: + +```codebyte/csharp +using System; +using System.Collections.Generic; + +public class ConcatMethod +{ + public static void Main() + { + List usernames = new List { "Alice", "Bob", "Charlie" }; + foreach (string user in usernames) + { + string greeting = string.Concat("Hi there ", user, ", how can I help you?"); + Console.WriteLine(greeting); + } + } +} +``` diff --git a/content/c-sharp/concepts/strings/terms/contains/contains.md b/content/c-sharp/concepts/strings/terms/contains/contains.md index 0f834456426..37cf3e436ba 100644 --- a/content/c-sharp/concepts/strings/terms/contains/contains.md +++ b/content/c-sharp/concepts/strings/terms/contains/contains.md @@ -36,12 +36,12 @@ String.Contains(string, comparisonType) - `char` is a single character. - `string` is a sequence of characters. - `comparisonType` is an enumeration value that allows to add specific rules to compare strings such as culture, case, and sort. Passing as an additional argument: -- `CurrentCulture` determines whether strings match culture-sensitive criteria. -- `CurrentCultureIgnoreCase` same as above and ignores the case. -- `InvariantCulture` determines whether strings match culture-sensitive criteria and the invariant culture. -- `InvariantCultureIgnoreCase` same as above and ignores the case. -- `Ordinal` determines whether strings match using binary sort rules. -- `OrdinalIgnoreCase` same as above and ignores the case. + - `CurrentCulture` determines whether strings match culture-sensitive criteria using the current system culture for comparison. + - `CurrentCultureIgnoreCase` does the same as above and ignores the case. + - `InvariantCulture` determines whether strings match using a fixed, culture-independent set of rules that remain consistent across all systems and regions. + - `InvariantCultureIgnoreCase` does the same as above and ignores the case. + - `Ordinal` determines whether strings match using binary sort rules. This is the fastest comparison method, performing a simple byte-by-byte comparison of Unicode values. + - `OrdinalIgnoreCase` does the same as above and ignores the case. ## Example @@ -78,6 +78,42 @@ True False ``` +Now, let's see how we can use the `comparisonType` parameter to modify the comparison rules: + +```cs +using System; +using System.Globalization; + +public class Example +{ + public static void Main() + { + // Turkish culture handles 'i' and 'İ' differently + CultureInfo turkishCulture = new CultureInfo("tr-TR"); + string turkishString = "İstanbul"; + string searchText = "istanbul"; + + // Default culture comparison (typically en-US) + bool defaultResult = turkishString.Contains(searchText, StringComparison.CurrentCultureIgnoreCase); + + // Turkish culture comparison + CultureInfo.CurrentCulture = turkishCulture; + bool turkishResult = turkishString.Contains(searchText, + StringComparison.CurrentCultureIgnoreCase); + + Console.WriteLine($"Default culture result: {defaultResult}"); + Console.WriteLine($"Turkish culture result: {turkishResult}"); + } +} +``` + +Here is the output: + +```shell +Default culture result: True +Turkish culture result: False +``` + ## Codebyte Example The example below determines whether the word `helpful` is included in the particular string. diff --git a/content/c-sharp/concepts/strings/terms/remove/remove.md b/content/c-sharp/concepts/strings/terms/remove/remove.md new file mode 100644 index 00000000000..5adec1b5844 --- /dev/null +++ b/content/c-sharp/concepts/strings/terms/remove/remove.md @@ -0,0 +1,87 @@ +--- +Title: '.Remove()' +Description: 'Removes a specified number of characters from a string starting at a defined index and returns the modified string.' +Subjects: + - 'Code Foundations' + - 'Computer Science' +Tags: + - 'Elements' + - 'Methods' + - 'Strings' +CatalogContent: + - 'learn-c-sharp' + - 'paths/computer-science' +--- + +In C#, the **`.Remove()`** method removes characters from a specific position in a string, starting at a given index. The original string remains unchanged, and the modified string is returned. + +## Syntax + +```pseudo +// Removes characters from startIndex to the end of the string. +string.Remove(int startIndex); +``` + +Or, alternatively: + +```pseudo +// Removes a specified number of characters starting at startIndex. +string.Remove(int startIndex, int count); +``` + +- `startIndex`: The zero-based position in the string where removal begins. +- `count` (Optional): The number of characters to remove from the specified `startIndex`. + +## Example + +The following example shows how to use the `.Remove()` method: + +```cs +using System; + +public class RemoveExample +{ + public static void Main() + { + string baseStr = "ABCDEFGHIJ"; + + string newStr1 = baseStr.Remove(5); + string newStr2 = baseStr.Remove(2, 5); + + Console.WriteLine("New string1: " + newStr1); + Console.WriteLine("New string2: " + newStr2); + + } +} +``` + +This example results in the following output: + +```shell +New string1: ABCDE +New string2: ABHIJ +``` + +## Codebyte Example + +Run the following codebyte example to understand how the `.Remove()` method works: + +```codebyte/csharp +using System; + +class RemoveMethod { + + public static void Main(string[] args) + { + string baseStr1 = "Codecademy helps you grow"; + string baseStr2 = "Improve skills with Codecademy"; + + string removedStr1 = baseStr1.Remove(10); + Console.WriteLine("Removed string1: " + removedStr1); + + string removedStr2 = baseStr2.Remove(8, 7); + Console.WriteLine("Removed string2: " + removedStr2); + + } +} +``` diff --git a/content/c-sharp/concepts/variables/variables.md b/content/c-sharp/concepts/variables/variables.md index b57be167ce9..219219b3352 100644 --- a/content/c-sharp/concepts/variables/variables.md +++ b/content/c-sharp/concepts/variables/variables.md @@ -1,9 +1,9 @@ --- Title: 'Variables' -Description: 'A variable refers to a storage location in the computer’s memory that one can set aside to save, retrieve, and manipulate data.' +Description: 'Variables are used to store and manipulate data. In C#, each variable has a type that determines the values it can store.' Subjects: - - 'Computer Science' - 'Code Foundations' + - 'Computer Science' Tags: - 'Variables' - 'Data Types' @@ -12,44 +12,162 @@ CatalogContent: - 'paths/computer-science' --- -A **variable** is a storage location in the computer’s memory that is used to save, retrieve, and manipulate data. +**Variables** are used to store and manipulate data. In C#, each variable has a type that determines the values it can store. -## Syntax +## Types of variables + +In C#, there are five distinct types of variables: -Minimally, a variable is declared by specifying a data type and a name: +| Name | Description | +| ------------------ | -------------------------------------------------------------------------------------------------------------------------------- | +| Local variables | Variables declared within a method, constructor, or code block, accessible only within that scope. | +| Instance variables | Non-static fields in a class, storing data unique to each instance of the class. | +| Static Variables | Variables shared across all instances of a class, belonging to the class itself. | +| Constant Variables | Immutable values initialized at the time of declaration, typically declared with const and behaving similarly to static members. | +| Readonly Variables | Values that can be assigned during declaration or in a constructor but cannot be modified afterward. | + +## Syntax ```pseudo -type name; +type name = value; ``` -In this case, the variable will be initialized with the default value for its type: zero for numeric types, and `null` for reference types. +- `type`: The data type of a variable, defining the kind of data it can hold. +- `name`: The identifier for the variable, used to reference it in the code. +- `value`: An optional initial value for the variable. If omitted, it must be assigned a value before use. -A variable can also be initialized with a value when it is declared: +## Examples -```pseudo -type name = value; +### Local variables + +In this example, `localVariable` can only be used within the `MyMethod()` function: + +```cs +void MyMethod() +{ + int localVariable = 10; // This variable is only accessible inside MyMethod +} +``` + +### Instance variables + +The example demonstrates an instance variable (`name`) within a class (`Person`). Each instance of `Person` will have its own copy of `name`: + +```cs +class Person +{ + public string name; // Instance variable + + public Person(string personName) + { + name = personName; // Initialize instance variable + } +} ``` -In this case, the variable `name` will be set to the value `value`. +### Static Variables -> **Note:** `value` must be of type `type` or be able to be implicitly converted to `type`. +Here, `wheels` is a static variable, meaning it belongs to the `Car` class and is shared by all instances. Note that static variables can be modified unless marked as `const`: -## Example +```cs +class Car { + public static int wheels = 4; // Static variable +} +``` + +### Constant Variables + +In this example, `Pi` is a constant variable, meaning its value cannot be changed after declaration and is shared across all instances: ```cs +class Circle +{ + public const double Pi = 3.14159; // Constant variable + + public double CalculateArea(double radius) + { + return Pi * radius * radius; // Using the constant variable + } +} +``` + +### Readonly Variables + +In this example, `length` and `width` are readonly variables assigned in the `Rectangle` constructor. Their values cannot be changed after the instance is created: + +```cs +class Rectangle +{ + public readonly double length; // Readonly variable + public readonly double width; // Readonly variable + + public Rectangle(double l, double w) + { + length = l; // Assigning value in the constructor + width = w; // Assigning value in the constructor + } +} +``` + +## Codebyte Example + +Here’s an example showcasing the use of various types of variables: + +```codebyte/csharp using System; -public class Example +class Car { - public static void Main(string[] args) + // Instance variable + public string model; + + // Static variable + public static int wheels = 4; // Shared across all instances + + // Constant variable + public const string fuelType = "Gasoline"; // Cannot be changed + + // Readonly variable + public readonly string vin; // Must be assigned in constructor + + // Constructor to initialize instance and readonly variables + public Car(string model, string vin) { - int x = 1; - int y = x + 5; - long z = y; + this.model = model; + this.vin = vin; // Assigning the readonly variable + } + + public void DisplayInfo() + { + // Local variable + string message = $"Car Model: {model}, VIN: {vin}, Wheels: {wheels}, Fuel Type: {fuelType}"; + + // Displaying the message + Console.WriteLine(message); + } +} + +class Factory +{ + static void Main() + { + // Creating instances of Car + Car car1 = new Car("Toyota Camry", "1HGCM82633A123456"); + Car car2 = new Car("Honda Accord", "1HGCM82633A654321"); + + // Displaying info for each car + car1.DisplayInfo(); + car2.DisplayInfo(); + + // Modifying static variable + Car.wheels = 5; // All instances will see this change - Console.WriteLine("The int {0} can be implicitly converted to the long {1}.", y, z); + // Displaying info again to see the updated static variable + car1.DisplayInfo(); + car2.DisplayInfo(); - // Output: "The int 6 can be implicitly converted to the long 6." + // Trying to modify readonly variable (will cause compile-time error) + // car1.vin = "1HGCM82633A111111"; // Uncommenting this line will cause an error } } ``` diff --git a/content/cpp/concepts/deque/terms/clear/clear.md b/content/cpp/concepts/deque/terms/clear/clear.md new file mode 100644 index 00000000000..4e1a91cfbb4 --- /dev/null +++ b/content/cpp/concepts/deque/terms/clear/clear.md @@ -0,0 +1,99 @@ +--- +Title: '.clear()' +Description: 'Removes all elements from a given deque.' +Subjects: + - 'Computer Science' + - 'Game Development' +Tags: + - 'Classes' + - 'Containers' + - 'Deques' + - 'OOP' +CatalogContent: + - 'learn-c-plus-plus' + - 'paths/computer-science' +--- + +In C++, the **`.clear()`** [method](https://www.codecademy.com/resources/docs/cpp/methods) removes all elements from a given deque container, leaving the container with a size of 0. + +## Syntax + +```pseudo +dequeName.clear(); +``` + +- `dequeName`: The name of the deque container from which all elements will be removed. + +## Example + +The example below showcases the use of the `.clear()` method: + +```cpp +#include +#include + +int main() { + // Create a deque of integers + std::deque numbers; + + // Add elements to the deque + numbers.push_back(50); + numbers.push_back(100); + numbers.push_back(150); + numbers.push_back(200); + + // Display the elements of the deque before clearing + std::cout << "My deque contains: "; + for (int num : numbers) { + std::cout << num << " "; + } + + // Clear all elements from the deque + numbers.clear(); + std::cout << std::endl; + + numbers.push_back(200); + + // Display the elements of the deque after clearing and adding a new element + std::cout << "My deque contains: "; + for (int num : numbers) { + std::cout << num << " "; + } + + std::cout << std::endl; + + return 0; +} +``` + +The above code generates the following output: + +```shell +My deque contains: 50 100 150 200 +My deque contains: 200 +``` + +## Codebyte Example + +The following codebyte demonstrates the use of the `.clear()` method, which removes all elements from the deque before adding a new element: + +```codebyte/cpp +#include +#include +#include + +int main() { + std::deque myDeque; + + myDeque.push_back("A"); + myDeque.push_back("B"); + myDeque.push_back("C"); + + myDeque.clear(); + myDeque.push_back("D"); + + for (const auto& value : myDeque) { + std::cout << ' ' << value; + } +} +``` diff --git a/content/cpp/concepts/deque/terms/empty/empty.md b/content/cpp/concepts/deque/terms/empty/empty.md new file mode 100644 index 00000000000..de8df0e573b --- /dev/null +++ b/content/cpp/concepts/deque/terms/empty/empty.md @@ -0,0 +1,94 @@ +--- +Title: '.empty()' +Description: 'Checks if a given deque container is empty.' +Subjects: + - 'Computer Science' + - 'Game Development' +Tags: + - 'Classes' + - 'Containers' + - 'Deques' + - 'OOP' +CatalogContent: + - 'learn-c-plus-plus' + - 'paths/computer-science' +--- + +In C++, the **`.empty()`** [method](https://www.codecademy.com/resources/docs/cpp/methods) checks if a given deque container is empty (i.e., if its size is 0). The method returns `true` if it is empty and `false` otherwise. + +## Syntax + +```pseudo +dequeName.empty(); +``` + +- `dequeName`: The [variable](https://www.codecademy.com/resources/docs/cpp/variables) name of the deque being checked for emptiness. + +## Example + +The example below showcases the use of the `.empty()` method: + +```cpp +#include +#include + +int main() { + // Create a deque of integers + std::deque numbers; + + // Add elements to the deque + numbers.push_back(100); + numbers.push_back(150); + + std::cout << "Deque is empty: "; + if (numbers.empty()) { + std::cout << "True"; + } + else { + std::cout << "False"; + } + + std::cout << std::endl; + + return 0; +} +``` + +The above code generates the following output: + +```shell +Deque is empty: False +``` + +## Codebyte Example + +The following codebyte uses the **`.clear()`** method on a deque and checks its emptiness by outputting a boolean value using the `.empty()` method: + +```codebyte/cpp +#include +#include +#include + +int main() { + std::deque myDeque; + + myDeque.push_back("Car"); + myDeque.push_back("Bus"); + myDeque.push_back("Train"); + + // Display vehicles before clearing the deque + std::cout << "Vehicles before clearing:"; + for (const auto& value : myDeque) { + std::cout << ' ' << value; + } + std::cout << std::endl; + + // Clear all elements from the deque + myDeque.clear(); + + // Boolean output indicating if the deque is empty after clearing + std::cout << "Deque is empty after clearing: " << std::boolalpha << myDeque.empty() << std::endl; + + return 0; +} +``` diff --git a/content/cpp/concepts/deque/terms/insert/insert.md b/content/cpp/concepts/deque/terms/insert/insert.md new file mode 100644 index 00000000000..699c899fa4f --- /dev/null +++ b/content/cpp/concepts/deque/terms/insert/insert.md @@ -0,0 +1,97 @@ +--- +Title: '.insert()' +Description: 'Inserts an element at a specified position in the deque.' +Subjects: + - 'Computer Science' + - 'Game Development' +Tags: + - 'Classes' + - 'Containers' + - 'Deques' + - 'OOP' +CatalogContent: + - 'learn-c-plus-plus' + - 'paths/computer-science' +--- + +In C++, the **`.insert()`** [method](https://www.codecademy.com/resources/docs/cpp/methods) inserts an element at a specified position in the deque. + +## Syntax + +There are some variations in the syntax for the `.insert()` method: + +```pseudo +dequeName.insert(iterator position, const value_type& val) +deque_name.insert(iterator position, size_type n, const value_type& val) +deque_name.insert(iterator position, InputIterator first, InputIterator last) +``` + +- `position`: An iterator pointing to the location where the new element(s) should be inserted. +- `val`: The element to be added to the deque. It can be of any [data type](https://www.codecademy.com/resources/docs/cpp/data-types) that `deque_name` holds. +- `n`: Specifies the number of elements to insert into the deque, each initialized to a copy of `val`. +- `first`: An iterator pointing to the beginning of a range of elements to be inserted into the deque. +- `last`: An iterator pointing to one past the last element in the range to be inserted, indicating that all elements from `first` (inclusive) to `last` (exclusive) will be added. + +## Example + +The example below showcases the use of the `.insert()` method: + +```cpp +#include +#include + +int main() { + // Create a deque of integers + std::deque numbers; + + // Add elements to the deque + numbers.push_back(10); + numbers.push_back(30); + + // Insert 20 at index 1 using .insert() + numbers.insert(numbers.begin() + 1, 20); + + // Display the elements of the deque + std::cout << "Deque contents: "; + + for (int num : numbers) { + std::cout << num << " "; + } + + std::cout << std::endl; + + return 0; +} +``` + +The above code generates the following output: + +```shell +Deque contents: 10 20 30 +``` + +## Codebyte Example + +Run the following codebyte example to understand the use of the `.insert()` method: + +```codebyte/cpp +#include +#include +#include + +int main() { + std::deque myDeque; + + myDeque.push_back("A"); + myDeque.push_back("C"); + + // Insert B at index 1 + myDeque.insert(myDeque.begin() + 1, "B"); + + myDeque.push_back("D"); + + for (const auto& value : myDeque) { + std::cout << ' ' << value; + } +} +``` diff --git a/content/cpp/concepts/deque/terms/push-back/push-back.md b/content/cpp/concepts/deque/terms/push-back/push-back.md new file mode 100644 index 00000000000..975ea2dcdcd --- /dev/null +++ b/content/cpp/concepts/deque/terms/push-back/push-back.md @@ -0,0 +1,84 @@ +--- +Title: '.push_back()' +Description: 'Adds an element to the end of the deque.' +Subjects: + - 'Computer Science' + - 'Game Development' +Tags: + - 'Containers' + - 'OOP' + - 'Classes' + - 'Deques' +CatalogContent: + - 'learn-c-plus-plus' + - 'paths/computer-science' +--- + +In C++, the **`.push_back()`** [method](https://www.codecademy.com/resources/docs/cpp/methods) adds an element to the end of the deque. + +## Syntax + +```pseudo +dequeName.push_back(value); +``` + +- `value`: The element to be added to the back of the deque. It can be of any [data type](https://www.codecademy.com/resources/docs/cpp/data-types) that the `dequeName` holds. + +## Example + +The example below showcases the use of the `.push_back()` method: + +```cpp +#include +#include + +int main() { + // Create a deque of integers + std::deque numbers; + + // Use .push_back() to add elements to the deque + numbers.push_back(10); + numbers.push_back(20); + numbers.push_back(30); + + // Display the elements of the deque + std::cout << "Deque contents: "; + + for (int num : numbers) { + std::cout << num << " "; + } + + std::cout << std::endl; + + return 0; +} +``` + +The above code generates the following output: + +```shell +Deque contents: 10 20 30 +``` + +## Codebyte Example + +The following codebyte adds several values to `myDeque` with the `.push_back()` method: + +```codebyte/cpp +#include +#include +#include + +int main() { + std::deque myDeque; + + myDeque.push_back("A"); + myDeque.push_back("B"); + myDeque.push_back("C"); + myDeque.push_back("D"); + + for (const auto& value : myDeque) { + std::cout << ' ' << value; + } +} +``` diff --git a/content/cpp/concepts/enum/enum.md b/content/cpp/concepts/enum/enum.md index 5b628a1011d..04df8195a0b 100644 --- a/content/cpp/concepts/enum/enum.md +++ b/content/cpp/concepts/enum/enum.md @@ -1,6 +1,6 @@ --- -Title: 'Enums' -Description: 'In C++, an enumeration (enum) is a user defined type where a set of values are specified for a variable and the variable can only take one out of a small set of possible values.' +Title: 'Enum' +Description: 'Defines a variable with a limited set of predefined values.' Subjects: - 'Computer Science' - 'Game Development' @@ -102,3 +102,61 @@ LogResult logger_result = LogResult::Success; if (logger_result == LogResult::Success) {} // Because Success is scoped to LogResult, it doesn't collide with SocketResult::Success ``` + +## Enum to Int Conversion + +In C++, `enum` can be implicitly converted to integers, useful for numeric contexts like array indexing or bitwise operations: + +```cpp +#include +enum color { red, green, blue }; + +int main() { + color c = green; + int colorValue = c; // Implicit conversion to int + std::cout << "Color value: " << colorValue; +} +``` + +Here is the output: + +```shell +Color value: 1 +``` + +Converting an `enum` to `int` is easy, but converting `int` to `enum` is risky as no bounds check is done, leading to undefined behavior if the value is out of range. + +## Custom Underlying Types + +By default, an enum's type is `int`, but a smaller type like `unsigned char` can be specified to optimize memory usage: + +```cpp +#include +enum class Permission : unsigned char { + Read = 1, + Write = 2, + Execute = 4 +}; + +int main() { + Permission p = Permission::Write; + std::cout << static_cast(p); // Explicit cast to int +} +``` + +Here, the underlying type of `Permission` is `unsigned char`. The constants `Read`, `Write`, and `Execute` are stored using only 1 byte of memory. + +This example results in the following output: + +```shell +2 +``` + +## Best Practices + +Here are some best practices for using enums: + +1. Use `enum class` for strong typing: Scoped enums (C++11) prevent implicit int conversions, ensuring better type safety. +2. Explicit casting: Use `static_cast(enum_value)` for safe conversions. +3. Avoid magic numbers: Enums replace hardcoded numbers, improving readability. +4. Use underlying types wisely: Choose the underlying type carefully in memory-constrained environments. diff --git a/content/cpp/concepts/exceptions/exceptions.md b/content/cpp/concepts/exceptions/exceptions.md index 2414351fe40..08f02f785bf 100644 --- a/content/cpp/concepts/exceptions/exceptions.md +++ b/content/cpp/concepts/exceptions/exceptions.md @@ -1,20 +1,20 @@ --- Title: 'Exceptions' -Description: 'An Exception in C++ is the computers response to a problem that occurs while executing a programs code. If the code does not handle the exception, the program will stop running due to the error.' +Description: 'Exception is a runtime error that occurs during the execution of a program. If not handled, it stops the program execution.' Subjects: - 'Computer Science' - 'Game Development' Tags: - - 'Exceptions' - - 'Try' - 'Catch' - 'Errors' + - 'Exceptions' + - 'Try' CatalogContent: - 'learn-c-plus-plus' - 'paths/computer-science' --- -In C++, an **exception** is the computer's response to a problem that occurs while executing a program's code. The computer will create an exception, and if the code does not have a way to handle it, then the program will stop executing due to the error. +In C++, an **exception** is a runtime error that occurs during the execution of a program. If not handled, it stops the program execution. The computer will create an `exception`, and if the code does not have a way to handle it, then the program will stop executing due to the error. ## Catching an Exception diff --git a/content/cpp/concepts/files/files.md b/content/cpp/concepts/files/files.md index 8b2e3196616..436053e06ba 100644 --- a/content/cpp/concepts/files/files.md +++ b/content/cpp/concepts/files/files.md @@ -1,6 +1,6 @@ --- Title: 'Files' -Description: 'Computers use file systems to store and retrieve data. The fstream library, short for file stream, enables working with files in C++. The fstream library has three classes that are used to create, write, and read files: ofstream, ifstream, and fstream.' +Description: 'Computers use file systems to store and retrieve data. The fstream library, short for file stream, enables working with files in C++.' Subjects: - 'Computer Science' - 'Game Development' @@ -89,3 +89,60 @@ The output would be: Today is the greatest Day I've ever known ``` + +## Appending to a File + +In some cases, you may want to append text to an existing file instead of overwriting its content. To do this, you can open the file in append mode using the `std::ios::app` flag with `ofstream` or `fstream`. Here's an example: + +```cpp +#include +#include +int main() { + // Open the file in append mode + std::ofstream MyFile("journal.txt", std::ios::app); + // Append text to the file + MyFile << "\nSmashing Pumpkins lyrics\n"; + // Close the file + MyFile.close(); +} +``` + +The file `journal.txt` will now contain: + +```shell +Today is the greatest +Day I've ever known +Smashing Pumpkins lyrics +``` + +## Checking if a file exists + +Before opening a file, checking if the file exists is a good practice. This can prevent issues like reading a file that doesn't exist. You can use the `.is_open()` function for this: + +```cpp +#include +#include +int main() { + std::ifstream MyFile("journal.txt"); + // Check if the file opened successfully + if (MyFile.is_open()) { + std::cout << "File opened successfully.\n"; + } else { + std::cout << "File does not exist.\n"; + } + // Close the file + MyFile.close(); +} +``` + +If the file `journal.txt` exists, the output will be: + +```shell +File opened successfully. +``` + +If the file `journal.txt` does not exist, the output will be: + +```shell +File does not exist. +``` diff --git a/content/cpp/concepts/forward-list/forward-list.md b/content/cpp/concepts/forward-list/forward-list.md new file mode 100644 index 00000000000..7557f98b928 --- /dev/null +++ b/content/cpp/concepts/forward-list/forward-list.md @@ -0,0 +1,84 @@ +--- +Title: 'forward_list' +Description: 'Forward List is a sequence container that allows efficient insertions and deletions from the front of the list.' +Subjects: + - 'Computer Science' +Tags: + - 'Collections' + - 'Lists' + - 'Memory' +CatalogContent: + - 'learn-c-plus-plus' + - 'paths/computer-science' +--- + +A **`forward_list`** is a sequence container in C++ that allows efficient insertions and deletions at the front of the list. It stores a memory address to the first element, with each element containing data and a pointer to the next element. Compared to arrays, `forward_list` offers faster insertions and deletions at the front but lacks direct access to elements by index. + +## Syntax + +```pseudo +#include + +std::forward_list list_name; +``` + +- `type`: The type of the elements in the `forward_list`. This can be any data type, such as `int`, `std::string`, or user-defined types. +- `list_name`: The name of the `forward_list` object being declared. + +> **Note:** To use `std::forward_list`, the header `` must be included. + +## Example + +The following example shows how to create a `forward_list` and iterate over it: + +```cpp +#include +#include + +int main() { + std::forward_list list = {1,2,3,4,5}; + + std::cout << "Output:" << std::endl; + + for(auto it = list.begin(); it != list.end(); ++it) { + std::cout << *it << " "; + } + std::cout << std::endl; +} +``` + +The output of the above program will be: + +```shell +Output: +1 2 3 4 5 +``` + +> **Note:** Unlike arrays, `forward_list` does not support direct access to elements through indices. To access a specific element, all preceding elements must be iterated over. + +## Codebyte Example + +The following codebyte example demonstrates the use of `forward_list` in C++ by initializing a list with elements, inserting an element at the front, removing an element from the front, and iterating over the list to print the remaining elements: + +```codebyte/cpp +#include +#include + +int main() { + // Initialize a forward_list with some elements + std::forward_list list = {10, 20, 30}; + + // Insert an element at the front + list.push_front(5); + + // Remove an element from the front + list.pop_front(); + + // Iterate over the list and print each element + for (auto it = list.begin(); it != list.end(); ++it) { + std::cout << *it << " "; + } + + return 0; +} +``` diff --git a/content/cpp/concepts/functions/functions.md b/content/cpp/concepts/functions/functions.md index cd5bbe1f75d..465b7182e3f 100644 --- a/content/cpp/concepts/functions/functions.md +++ b/content/cpp/concepts/functions/functions.md @@ -1,6 +1,6 @@ --- Title: 'Functions' -Description: 'A function is a set of statements that are executed together when the function is called. Every function has a name, which is used to call the respective function. C++ has many built-in functions.' +Description: 'Functions are self-contained blocks of code designed to perform specific tasks, allowing for code reuse and modularity.' Subjects: - 'Computer Science' - 'Game Development' @@ -183,3 +183,32 @@ This will output: When add function is called with integer parameters: 20 When add function is called with string parameters: HelloWorld! ``` + +## Recursion + +Recursion is a technique that allows a function to call itself. In C++, the function that calls itself is called a recursive function: + +```cpp +#include +using namespace std; + +int sum(int m) { + if (m > 0) { + return m + sum(m - 1); // Recursive call + } else { + return 0; // Base case + } +} + +int main() { + int result = sum(5); + cout << result; + return 0; +} +``` + +This program will output the following result: + +```shell +15 +``` diff --git a/content/cpp/concepts/list/list.md b/content/cpp/concepts/list/list.md new file mode 100644 index 00000000000..9ec60a72256 --- /dev/null +++ b/content/cpp/concepts/list/list.md @@ -0,0 +1,102 @@ +--- +Title: 'List' +Description: 'List in C++ is a sequential container that stores elements in non-contiguous memory locations, allowing for efficient insertion and deletion at any position.' +Subjects: + - 'Game Development' + - 'Mobile Development' + - 'Machine Learning' +Tags: + - 'Data Structures' + - 'Doubly Linked Lists' + - 'Lists' +CatalogContent: + - 'learn-c-plus-plus' + - 'paths/computer-science' +--- + +**List** in C++ is a sequential container and part of the Standard Template Library (STL) that stores elements in non-contiguous memory locations. It is implemented as a doubly linked list, allowing efficient insertion and deletion of elements at any known position with average constant time complexity. + +## Syntax + +```pseudo +#include + +std::list name_of_list; +``` + +- `data-type`: Specifies the type of elements stored in the list, which can be any valid C++ type (e.g., `int`, `double`, or user-defined types). +- `name_of_list`: The variable name for the list instance, used to reference and manipulate the list within the code. + +## Example + +```cpp +#include + +#include + +int main() { + // Declare a list of integers + std::list myList; + + // Adding elements to the list + myList.push_back(10); + myList.push_back(20); + myList.push_front(5); + + // Displaying elements in the list + std::cout << "List elements: "; + for (const auto & value: myList) { + std::cout << value << " "; + } + std::cout << std::endl; + + // Removing an element + myList.remove(10); + + // Displaying the updated list + std::cout << "Updated list elements after deletion: "; + for (const auto & value: myList) { + std::cout << value << " "; + } + std::cout << std::endl; + return 0; +} +``` + +The output for the above code is: + +```shell +List elements: 5 10 20 +Updated list elements after deletion: 5 20 +``` + +## Codebyte Example + +Run the following codebyte example to understand how List works in C++: + +```codebyte/cpp +#include + +#include + +#include + +int main() { + // Create a list of strings + std::list fruits = { + "apple", + "banana", + "cherry" + }; + + // Add a fruit to the list + fruits.push_back("orange"); + + // Access elements in the list using an iterator + for (const auto & fruit: fruits) { + std::cout << fruit << std::endl; + } + + return 0; +} +``` diff --git a/content/cpp/concepts/maps/terms/count/count.md b/content/cpp/concepts/maps/terms/count/count.md new file mode 100644 index 00000000000..394d2e1d3bc --- /dev/null +++ b/content/cpp/concepts/maps/terms/count/count.md @@ -0,0 +1,98 @@ +--- +Title: '.count()' +Description: 'Checks whether a specified key exists in the map and returns the number of occurrences' +Subjects: + - 'Computer Science' + - 'Game Development' + - 'Machine Learning' +Tags: + - 'Objects' + - 'OOP' + - 'Classes' + - 'Map' +CatalogContent: + - 'learn-c-plus-plus' + - 'paths/computer-science' +--- + +The **`.count()`** method in C++ for `std::map` is used to determine the presence of a specific key in the map. Since all keys in a map are unique, the function returns: + +- _1_ if the key exists in the container. +- _0_ if the key does not exist. + +## Syntax + +```pseudo +mapName.count(key) +``` + +- `mapName`: Refers to the specific map being accessed. +- `key`: Represents the value that will be searched for in `mapName`. + +## Example + +In the following example, the `.count()` method is used to check whether the keys `"coconuts"` and `"strawberries"` exist in the `fruits` map: + +```cpp +#include +#include +#include + +int main() { + // Initializing map with items + std::map fruits {{"apples", 50}, {"bananas", 100}, {"coconuts", 20}, {"dates", 500}}; + + // Checking if "coconuts" exists + std::string key = "coconuts"; + + if (fruits.count(key) > 0) { + std::cout << "There are " << fruits[key] << " " << key << ".\n"; // If key exists, print the count + } else { + std::cout << "There are no " << key << ".\n"; // If key does not exist, print a message + } + + // Checking if "strawberries" exists + key = "strawberries"; + + if (fruits.count(key) > 0) { + std::cout << "There are " << fruits[key] << " " << key << ".\n"; // If key exists, print the count + } else { + std::cout << "There are no " << key << ".\n"; // If key does not exist, print a message + } + + return 0; +} +``` + +The above code produces the following output: + +```shell +There are 20 coconuts. +There are no strawberries. +``` + +## Codebyte Example + +The example below illustrates a scenario in which the `.count()` method is used to check whether an array of elements exists in a map: + +```codebyte/cpp +#include +#include +#include + +int main() { + std::map zoo_animals {{"hippos", 2}, {"lions", 4}, {"zebras", 6}, {"gorillas", 8}}; + + std::string animals_to_check[] = {"bats", "giraffes", "gorillas", "hippos", "zebras"}; + + for (const auto& animals : animals_to_check) { + if (zoo_animals.count(animals) > 0) { + std::cout << "The zoo has " << zoo_animals[animals] << " " << animals << ".\n"; + } else { + std::cout << "The zoo does not have " << animals << ".\n"; + } + } + + return 0; +} +``` diff --git a/content/cpp/concepts/maps/terms/empty/empty.md b/content/cpp/concepts/maps/terms/empty/empty.md new file mode 100644 index 00000000000..e74a6e98df1 --- /dev/null +++ b/content/cpp/concepts/maps/terms/empty/empty.md @@ -0,0 +1,90 @@ +--- +Title: '.empty()' +Description: 'Checks if a given map is empty.' +Subjects: + - 'Computer Science' + - 'Game Deelopment' +Tags: + - 'Data Structures' + - 'Documentation' + - 'Functions' + - 'Map' +CatalogContent: + - 'learn-c-plus-plus' + - 'paths/computer-science' +--- + +In the C++ Standard Template Library (STL), the **`.empty()`** [function](https://www.codecademy.com/resources/docs/cpp/functions) is a member function under the `std::map` [class](https://www.codecademy.com/resources/docs/cpp/classes) that checks if an STL map [object](https://www.codecademy.com/resources/docs/cpp/objects) contains any key-value pairs. It returns `true` if the map is empty and `false` otherwise. + +## Syntax + +```pseudo +myMap.empty(); +``` + +- `myMap`: The map to be checked. + +## Example + +The following example calls the `.empty()` function, stores its return value in a boolean [variable](https://www.codecademy.com/resources/docs/cpp/variables) and uses this value to display whether the map is empty or not: + +```cpp +#include +#include +using namespace std; + +int main(){ + // Create an empty STL map object + map emptyMap; + + // Check if the map is empty using the .empty() function and store the result + bool isEmpty = emptyMap.empty(); + + // Use the value stored in 'isEmpty' to display whether the map is empty or not + isEmpty ? printf("The map is empty.") : printf("The map is not empty."); + + return 0; +} +``` + +The code above produces the following output: + +```shell +The map is empty. +``` + +## Codebyte Example + +The following code creates two STL map objects with one left empty and the other initialized with elements. The `.empty()` function is then called on each map, returning a boolean indicating if the map is empty: + +```codebyte/cpp +#include +#include +using namespace std; + +int main() { + // Create an empty map + map emptyMap; + + // Create a non-empty map using an initializer list + map notEmptyMap{{1, 'a'}, {2, 'b'}, {3, 'c'}}; + + // Call the .empty() function on the empty map + printf("Testing if emptyMap is empty:\n"); + if (emptyMap.empty()) { + printf("The map is empty.\n"); + } else { + printf("The map is not empty.\n"); + } + + // Call the .empty() function on the map containing elements + printf("Testing if notEmptyMap is empty:\n"); + if (notEmptyMap.empty()) { + printf("The map is empty.\n"); + } else { + printf("The map is not empty.\n"); + } + + return 0; +} +``` diff --git a/content/cpp/concepts/maps/terms/size/size.md b/content/cpp/concepts/maps/terms/size/size.md new file mode 100644 index 00000000000..08ff43a5469 --- /dev/null +++ b/content/cpp/concepts/maps/terms/size/size.md @@ -0,0 +1,70 @@ +--- +Title: '.size()' +Description: 'Determines the number of elements in a map.' +Subjects: + - 'Computer Science' + - 'Game Development' +Tags: + - 'Elements' + - 'Map' + - 'OOP' + - 'Objects' +CatalogContent: + - 'learn-c-plus-plus' + - 'paths/computer-science' +--- + +In C++, the **`.size()`** [method](https://www.codecademy.com/resources/docs/cpp/methods) is used to determine the number of elements in a map. + +## Syntax + +```pseudo +mapName.size(); +``` + +- `mapName`: The map object for which the size is to be checked. + +## Example + +The following example uses `.size()` to get the number of elements in `myMap`: + +```cpp +#include +#include + +int main() { + std::map myMap; + myMap[1] = "apple"; + myMap[2] = "banana"; + myMap[3] = "cherry"; + + std::cout << "The map contains " << myMap.size() << " elements."; +} +``` + +The output of the above code will be: + +```shell +The map contains 3 elements. +``` + +## Codebyte Example + +The below example demonstrates the usage of the `.size()` method with two maps, `vehicles` and `fruits`: + +```codebyte/cpp +#include +#include +#include +using namespace std; + +int main() { + // Initializing maps with items + map vehicles {{1, "Car"}, {2, "Motorcycle"}, {3, "Bicycle"}, {4, "Bus"}, {5, "Airplane"}}; + map fruits{{1, "apple"}, {5, "banana"}, {6, "strawberry"}}; + + // Printing the size of each map + cout << "The number of vehicles: " << vehicles.size() << endl; + cout << "The number of fruits: " << fruits.size() << endl; +} +``` diff --git a/content/cpp/concepts/maps/terms/swap/swap.md b/content/cpp/concepts/maps/terms/swap/swap.md new file mode 100644 index 00000000000..3a05bee47da --- /dev/null +++ b/content/cpp/concepts/maps/terms/swap/swap.md @@ -0,0 +1,128 @@ +--- +Title: '.swap()' +Description: 'Exchanges the content of two maps.' +Subjects: + - 'Computer Science' + - 'Game Development' +Tags: + - 'Objects' + - 'OOP' + - 'Classes' +CatalogContent: + - 'learn-c-plus-plus' + - 'paths/computer-science' +--- + +In C++, **`.swap()`** function exchanges the contents of two maps in constant time, provided the maps are of the same type, though their sizes may differ. + +## Syntax + +```pseudo +map1.swap(map2); +``` + +- `map1`: The first map whose contents will be swapped. +- `map2`: The second map to exchange contents with `map1`. + +> **Note:** If `map1` and `map2` are not of the same type (i.e., they do not have the same key and value types), a compilation error will occur because `std::map::swap()` requires both maps to have the same type. + +## Example + +The following example shows how the `swap()` funcrion works: + +```cpp +#include +#include +using namespace std; + +int main() { + map map1{{1, "one"}, {2, "two"}, {3, "three"}}; + map map2{{4, "four"}, {5, "five"}, {6, "six"}}; + + cout << "Before swap Map1:\n"; + for(map::iterator it = map1.begin();it != map1.end();++it) { + cout << "Key: " << it->first<< ", Value: " << it->second << endl; + } + + cout << "Before swap Map2:\n"; + for(map::iterator it = map2.begin();it != map2.end();++it) { + cout << "Key: " << it->first<< ", Value: " << it->second << endl; + } + + // Swapping the contents of map1 and map2 + map1.swap(map2); + + cout << "After swap Map1:\n"; + for(map::iterator it = map1.begin();it != map1.end();++it) { + cout << "Key: " << it->first<< ", Value: " << it->second << endl; + } + + cout << "After swap Map2:\n"; + for(map::iterator it = map2.begin();it != map2.end();++it) { + cout << "Key: " << it->first<< ", Value: " << it->second << endl; + } + + return 0; +} +``` + +The output of the above code will be: + +```shell +Before swap Map1: +Key: 1, Value: one +Key: 2, Value: two +Key: 3, Value: three +Before swap Map2: +Key: 4, Value: four +Key: 5, Value: five +Key: 6, Value: six +After swap Map1: +Key: 4, Value: four +Key: 5, Value: five +Key: 6, Value: six +After swap Map2: +Key: 1, Value: one +Key: 2, Value: two +Key: 3, Value: three +``` + +## Codebyte Example + +Run the below codebyte example to know how the `.swap()` function works: + +```codebyte/cpp +#include +#include +using namespace std; + +int main() { + map map1{{"apple", 1}, {"banana", 2}, {"cherry", 3}}; + map map2{{"date", 4}, {"elderberry", 5}, {"fig", 6}}; + + cout << "Before swap Map1:\n"; + for(map::iterator it = map1.begin(); it != map1.end(); ++it) { + cout << "Key: " << it->first << ", Value: " << it->second << endl; + } + + cout << "Before swap Map2:\n"; + for(map::iterator it = map2.begin(); it != map2.end(); ++it) { + cout << "Key: " << it->first << ", Value: " << it->second << endl; + } + + // Swapping the contents of map1 and map2 + map1.swap(map2); + + cout << "After swap Map1:\n"; + for(map::iterator it = map1.begin(); it != map1.end(); ++it) { + cout << "Key: " << it->first << ", Value: " << it->second << endl; + } + + cout << "After swap Map2:\n"; + for(map::iterator it = map2.begin(); it != map2.end(); ++it) { + cout << "Key: " << it->first << ", Value: " << it->second << endl; + } + + return 0; +} +``` diff --git a/content/cpp/concepts/maps/terms/upper-bound/upper-bound.md b/content/cpp/concepts/maps/terms/upper-bound/upper-bound.md new file mode 100644 index 00000000000..9bbcdc57fc1 --- /dev/null +++ b/content/cpp/concepts/maps/terms/upper-bound/upper-bound.md @@ -0,0 +1,95 @@ +--- +Title: '.upper_bound()' +Description: 'Returns an iterator to the first element that is greater than the specified key.' +Subjects: + - 'Computer Science' + - 'Game Development' +Tags: + - 'Classes' + - 'Objects' + - 'OOP' +CatalogContent: + - 'learn-c-plus-plus' + - 'paths/computer-science' +--- + +The **`.upper_bound()`** function in a map returns an iterator pointing to the first element whose key is greater than the given key. If no such key exists, the iterator points to the map's `.end()`. + +## Syntax + +```pseudo +mapName.upper_bound(key); +``` + +- `key`: The key whose upper bound is needed. + +## Example + +The example below demonstrates using `.upper_bound()` to find the first student with a roll number greater than a specified value: + +```cpp +#include +#include + +int main() { + // Map with roll numbers as keys and student names as values + std::map students; + + students[101] = "John"; + students[103] = "Alice"; + students[105] = "Bob"; + + // Find the first student with a roll number greater than 102 + auto it = students.upper_bound(102); + + if (it != students.end()) { + std::cout << "The student with roll number greater than 102 is: " << it->second << " (Roll No: " << it->first << ")" << std::endl; + } else { + std::cout << "No student found with roll number greater than 102." << std::endl; + } + + return 0; +} +``` + +The code above produces the following output: + +```shell +The student with a roll number greater than 102 is: Alice (Roll No: 103) +``` + +## Codebyte Example + +The following codebyte example demonstrates how `.upper_bound()` works by returning iterators to keys greater than 11, 13, and 17 in a map of integers: + +```codebyte/cpp +#include +#include + +int main() { + // Initializing map + std::map mp; + + // Adding elements + mp.insert({12, 30}); + mp.insert({11, 10}); + mp.insert({15, 50}); + mp.insert({14, 40}); + + // Upper bound when the key is present + auto it = mp.upper_bound(11); + std::cout << "The upper bound of key 11 is " << it->first << " " << it->second << std::endl; + + // Upper bound when the key is absent + it = mp.upper_bound(13); + std::cout << "The upper bound of key 13 is " << it->first << " " << it->second << std::endl; + + // Upper bound when key exceeds maximum key + it = mp.upper_bound(17); + if (it == mp.end()) { + std::cout << "The upper bound of key 17 points to end()." << std::endl; + } + + return 0; +} +``` diff --git a/content/cpp/concepts/polymorphism/polymorphism.md b/content/cpp/concepts/polymorphism/polymorphism.md index 1e2b121b011..aeb232bfd40 100644 --- a/content/cpp/concepts/polymorphism/polymorphism.md +++ b/content/cpp/concepts/polymorphism/polymorphism.md @@ -1,6 +1,6 @@ --- Title: 'Polymorphism' -Description: 'Polymorphism is an important concept in object-oriented programming. It means more than one form — the same entity (function or operator) can behave differently in different scenarios.' +Description: 'Polymorphism allows a single function or operator to behave differently based on the context.' Subjects: - 'Computer Science' - 'Game Development' diff --git a/content/cpp/concepts/references/references.md b/content/cpp/concepts/references/references.md index d0abd380451..d859272d260 100644 --- a/content/cpp/concepts/references/references.md +++ b/content/cpp/concepts/references/references.md @@ -1,14 +1,13 @@ --- Title: 'References' -Description: 'A reference variable is an alias for another object. It is created using the & sign. Two things to note: Anything done to the reference also happens to the original and aliases cannot be changed to alias something else.' +Description: 'A reference variable is an alias for another object.' Subjects: - 'Computer Science' - 'Game Development' Tags: - - 'References' - - 'Pointers' - - 'Parameters' - 'Memory' + - 'Parameters' + - 'References' CatalogContent: - 'learn-c-plus-plus' - 'paths/computer-science' @@ -19,7 +18,7 @@ A **reference** variable is an alias for another object. It is created using the Two things to note: - Anything done to the reference also happens to the original. -- Aliases cannot be changed to alias something else. +- Aliases cannot be changed to alias or something else. ## Syntax @@ -37,7 +36,6 @@ It allows the ability to: - Avoid making copies of a variable/object for performance reasons. ```cpp - void swap_num(int &i, int &j) { int temp = i; i = j; @@ -50,8 +48,8 @@ int main() { swap_num(a, b); - std::cout << "A is " << a << "\n"; - std::cout << "B is " << b << "\n"; + std::cout << "A is " << a << "\n"; // Expected output: A is 200 + std::cout << "B is " << b << "\n"; // Expected output: B is 100 } ``` @@ -66,3 +64,53 @@ int triple(int const &i) { return i * 3; } ``` + +## References with Classes + +References can also be used with objects of classes. This allows object properties to be modified directly by passing them as reference parameters. + +```cpp +#include + +class Car { + public: + int speed; + Car(int spd) : speed(spd) {} + + void setSpeed(int &newSpeed) { speed = newSpeed; } +}; + +int triple(const int &i) { return i * 3; } + +int main() { + Car myCar(100); + int newSpeed = 200; + myCar.setSpeed(newSpeed); + + std::cout << "The new speed is: " << myCar.speed << "\n"; // The new speed is: 200 + std::cout << "Triple the speed: " << triple(myCar.speed) << "\n"; // Triple the speed: 600 + + return 0; +} +``` + +## Modifying Arrays Using References + +Passing arrays by reference is also useful for avoiding unnecessary copies, especially for large datasets. + +```cpp +void modifyArray(int (&arr)[5]) { + for (int i = 0; i < 5; i++) { + arr[i] = arr[i] * 2; + } +} + +int main() { + int myArr[5] = {1, 2, 3, 4, 5}; + modifyArray(myArr); + + for (int i = 0; i < 5; i++) { + std::cout << myArr[i] << " "; // 2 4 6 8 10 + } +} +``` diff --git a/content/cpp/concepts/unordered-map/terms/bucket/bucket.md b/content/cpp/concepts/unordered-map/terms/bucket/bucket.md new file mode 100644 index 00000000000..2c5e46be02e --- /dev/null +++ b/content/cpp/concepts/unordered-map/terms/bucket/bucket.md @@ -0,0 +1,74 @@ +--- +Title: '.bucket()' +Description: 'Returns the bucket number where an element is located in a C++ unordered map.' +Subjects: + - 'Computer Science' + - 'Game Development' +Tags: + - 'Map' + - 'Objects' +CatalogContent: + - 'learn-c-plus-plus' + - 'paths/computer-science' +--- + +The **`.bucket()`** function is part of the C++ [`unordered_map`](https://www.codecademy.com/resources/docs/cpp/unordered-map) container. It returns the bucket number (zero-indexed) where a specified element is located within the unordered map. Each element in the unordered map is assigned to a bucket based on its hash value, and this function helps determine which bucket a given key belongs to. + +## Syntax + +```pseudo +size_type bucket(const key_type& k) const; +``` + +- `key`: The key whose bucket number needs to be found in the unordered map. + +The function returns a `size_type` value, representing the zero-indexed bucket number where the specified key is stored. + +## Example + +In this example, the `bucket()` function is used to find the bucket number for the key `"banana"` in the unordered map: + +```cpp +#include +#include + +int main() { + std::unordered_map umap; + umap["apple"] = 1; + umap["banana"] = 2; + umap["cherry"] = 3; + + std::string key = "banana"; + std::cout << "The bucket for key '" << key << "' is: " << umap.bucket(key) << std::endl; + + return 0; +} +``` + +The above code generates the following output: + +```shell +The bucket for key 'banana' is: 4 +``` + +## Codebyte Example + +In this Codebyte, we are using the `bucket()` function to find the bucket for the key `"cherry"` in the unordered map: + +```codebyte/cpp +#include +#include + +int main() { + std::unordered_map umap; + umap["apple"] = 1; + umap["banana"] = 2; + umap["cherry"] = 3; + + // Check which bucket contains the key 'cherry' + std::string key = "cherry"; + std::cout << "The bucket for key '" << key << "' is: " << umap.bucket(key) << std::endl; + + return 0; +} +``` diff --git a/content/cpp/concepts/unordered-map/terms/count/count.md b/content/cpp/concepts/unordered-map/terms/count/count.md new file mode 100644 index 00000000000..9f258a3e38c --- /dev/null +++ b/content/cpp/concepts/unordered-map/terms/count/count.md @@ -0,0 +1,98 @@ +--- +Title: '.count()' +Description: 'Returns the number of elements with the specified key.' +Subjects: + - 'Computer Science' + - 'Game Development' +Tags: + - 'Classes' + - 'Objects' + - 'OOP' +CatalogContent: + - 'learn-c-plus-plus' + - 'paths/computer-science' +--- + +The **`.count()`** method checks if a key exists in an [unordered map](https://www.codecademy.com/resources/docs/cpp/unordered-map). It returns _1_ if the key exists and _0_ if it does not. + +## Syntax + +```pseudo +mapName.count(key); +``` + +- `mapName`: The name of the unordered map. +- `key`: The key to check for existence in the map. + +## Example + +The following example demonstrates the use of the `.count()` method with an unordered map to check for mammals and display their lifespans: + +```cpp +#include +#include + +int main() { + // Initializing unordered_map + std::unordered_map lifeSpan = { + {"Giraffe", 26}, + {"Goat", 15}, + {"Lion", 10}, + {"Tiger", 8} + }; + + // Checking the existence of elements using .count() + std::string mammals[] = {"Giraffe", "Elephant", "Lion", "Zebra"}; + + for (const auto& mammal : mammals) { + if (lifeSpan.count(mammal) > 0) { + std::cout << mammal << " exists in the map with an average lifespan of " << lifeSpan[mammal] << " years.\n"; + } else { + std::cout << mammal << " does not exist in the map.\n"; + } + } + + return 0; +} +``` + +This example results in the following output: + +```shell +Giraffe exists in the map with an average lifespan of 26 years. +Elephant does not exist in the map. +Lion exists in the map with an average lifespan of 10 years. +Zebra does not exist in the map. +``` + +## Codebyte Example + +The following codebyte example demonstrates the use of the `.count()` method with an unordered map to check for the presence of various fruits and their prices: + +```codebyte/cpp +#include +#include + +int main() { + // Initializing unordered_map with fruits and their prices + std::unordered_map fruitPrices = { + {"Apple", 0.99}, + {"Banana", 0.59}, + {"Cherry", 2.99}, + {"Date", 3.49} + }; + + // Checking the existence of fruits using .count() + std::string fruits[] = {"Apple", "Mango", "Cherry", "Pineapple"}; + + for (const auto& fruit : fruits) { + if (fruitPrices.count(fruit) > 0) { + std::cout << fruit << " is available at $" << fruitPrices[fruit] << " each.\n"; + } else { + std::cout << fruit << " is not available.\n"; + } + } + + return 0; +} +``` diff --git a/content/cpp/concepts/unordered-set/unordered-set.md b/content/cpp/concepts/unordered-set/unordered-set.md new file mode 100644 index 00000000000..1b4e4614cce --- /dev/null +++ b/content/cpp/concepts/unordered-set/unordered-set.md @@ -0,0 +1,107 @@ +--- +Title: 'Unordered Sets' +Description: 'Unordered sets are associative containers that store unique elements in no specific order, offering fast retrieval through a hash-based implementation.' +Subjects: + - 'Computer Science' + - 'Game Development' +Tags: + - 'Data Types' + - 'Elements' + - 'Hash Maps' + - 'Sets' +CatalogContent: + - 'learn-c-plus-plus' + - 'paths/computer-science' +--- + +In C++, **unordered sets** are associative containers that store unique elements in no particular order, offering fast look-ups, insertions, and deletions through a hash table. Unlike [`std::set`](https://www.codecademy.com/resources/docs/cpp/sets), which maintains elements in sorted order using a binary tree, unordered sets provide better performance with average constant time complexity for key operations. If elements are needed in a sorted order, `std::set` can be used, although it comes with higher overhead due to its tree-based structure. + +## Syntax + +```pseudo +#include +std::unordered_set set_name; +``` + +- `data_type`: The [data type](https://www.codecademy.com/resources/docs/cpp/data-types) of the elements to be stored in the unordered set (e.g., `int`, `string`). Each element in the unordered set will be of this type. +- `set_name`: The name of the unordered set being defined. + +## Example + +In this example, an unordered set is initiated and elements are inserted using the [`.insert()`](https://www.codecademy.com/resources/docs/cpp/sets/insert) method. The elements are then printed: + +```cpp +#include +#include + +int main() { + // Initiate an unordered set of elements (integers in this example) + std::unordered_set numSet; + + // Insert the elements + numSet.insert(10); + numSet.insert(20); + numSet.insert(30); + numSet.insert(40); + + // Print out the set elements + std::unordered_set :: iterator iter; + for (iter = numSet.begin(); iter != numSet.end(); iter++) { + std::cout<< *iter << " "; + } +} +``` + +The output would be: + +```shell +20 40 30 10 +``` + +> **Note**: The element order is not guaranteed to be consistent across executions. + +## Ordered vs Unordered Sets + +| Feature | Ordered Set (`std::set`) | Unordered Set (`std::unordered_set`) | +| ----------- | ----------------------------------------------- | ------------------------------------------------------------- | +| Order | Elements in sorted order | No particular order | +| Structure | Tree-based | Hash table | +| Time | O(log n) | O(1) | +| Memory | More efficient memory usage | Higher memory usage as a result of hashing | +| Performance | Consistent performance across all cases | Can degrade to O(n) if hashing is poor | +| Usage | Use when element ordering is useful or required | Use when efficiency is required and ordering is not important | + +> **Note**: Neither `std::set` nor `std::unordered_set` allows duplicate elements. + +## Codebyte Example + +This example builds on the previous example, adding a duplicate element to show it won't be included, and then checking if an element exists: + +```codebyte/cpp +#include +#include + +int main() { + // Initiate an unordered set of elements (integers in this example) + std::unordered_set numSet = {10, 20, 30, 40}; + + // Add a duplicate element + numSet.insert(20); + + // Print out the set elements + std::unordered_set :: iterator iter; + for (iter = numSet.begin(); iter != numSet.end(); iter++) { + std::cout<< *iter << " "; + } + + // Add a line break + std::cout << "\n"; + + // Check if an element exists + if (numSet.find(20) != numSet.end()) { + std::cout << "20 is in the set."; + } else { + std::cout << "20 is not in the set."; + } +} +``` diff --git a/content/cpp/concepts/user-input/terms/getline/getline.md b/content/cpp/concepts/user-input/terms/getline/getline.md index 591ba728b81..57de2c18570 100644 --- a/content/cpp/concepts/user-input/terms/getline/getline.md +++ b/content/cpp/concepts/user-input/terms/getline/getline.md @@ -91,3 +91,27 @@ int main() { // Output: My pet's name is Nimbus! } ``` + +## Codebyte Example + +Run the following codebyte to understand how the `getline()` function works: + +```codebyte/cpp +#include +#include + +using namespace std; + +int main() { + string myString; + + cout << "Enter your input: \n"; + // Input: Codeacademy is awesome + getline(cin, myString); + + cout << myString << "!"; + // Output: Codeacademy is awesome! +} +``` + +In the above example, using traditional `cin >> myString` would result in only capturing the first word, "Codeacademy." This is because `cin >>` reads input until it encounters a space or newline. To read an entire line, including spaces and tabs, we use `getline(cin, myString)`, which captures the full input line as a single string. diff --git a/content/cpp/concepts/variables/terms/constant-variables/constant-variables.md b/content/cpp/concepts/variables/terms/constant-variables/constant-variables.md new file mode 100644 index 00000000000..4837309ec1d --- /dev/null +++ b/content/cpp/concepts/variables/terms/constant-variables/constant-variables.md @@ -0,0 +1,68 @@ +--- +Title: 'Constant Variables' +Description: 'Defines variables in C++ whose values cannot be altered after they are set.' +Subjects: + - 'Code Foundations' + - 'Computer Science' +Tags: + - 'Const' + - 'OOP' + - 'Variables' +CatalogContent: + - 'learn-c-plus-plus' + - 'paths/computer-science' +--- + +**Constant variables** in C++ are variables whose values cannot be altered after they are set. By using the `const` keyword, a variable becomes read-only, preventing accidental modification. Constants are especially useful for defining values that should remain consistent throughout the program, such as mathematical constants (e.g., `PI`) or configuration settings. + +## Syntax + +```pseudo +const data_type variable_name = value; +``` + +- `data_type`: The type of the variable. +- `variable_name`: The name of the constant variable. +- `value`: The initial value assigned to the variable. Once set, this value cannot change. + +## Example + +This example demonstrates how to declare and use a constant variable in C++: + +```cpp +#include + +int main() { + const int max_attempts = 5; + std::cout << "Maximum allowed attempts: " << max_attempts << std::endl; + + // Uncommenting the following line would cause a compilation error + // max_attempts = 10; + + return 0; +} +``` + +This example results in the following output: + +```shell +Maximum allowed attempts: 5 +``` + +In this example, `max_attempts` is declared as a constant integer. Attempting to modify it later in the code would result in a compilation error, ensuring that its value remains consistent. + +## Codebyte Example + +```codebyte/cpp +#include + +int main() { + const float pi = 3.14159; + std::cout << "The value of pi is: " << pi << std::endl; + + // Uncommenting the following line would cause a compilation error + // pi = 3.14; + + return 0; +} +``` diff --git a/content/cpp/concepts/variables/terms/local-variables/local-variables.md b/content/cpp/concepts/variables/terms/local-variables/local-variables.md new file mode 100644 index 00000000000..c0ef3f9fee3 --- /dev/null +++ b/content/cpp/concepts/variables/terms/local-variables/local-variables.md @@ -0,0 +1,67 @@ +--- +Title: 'Local Variables' +Description: 'A variable defined inside a function body between braces is called a local variable.' +Subjects: + - 'Computer Science' + - 'Game Development' +Tags: + - 'Data Types' + - 'Variables' +CatalogContent: + - 'learn-c-plus-plus' + - 'paths/computer-science' +--- + +A **local variable** is a variable whose scope is limited to the function or block where it is defined. It exists only within that function and can only be accessed from there. + +## Syntax + +```pseudo +void local_variable(){ + int a_local_variable; +} +``` + +The variable `a_local_variable` is local to the `local_variable` function in which it is defined. It can only be accessed and used within that function. When the function `local_variable` exits, the life of `a_local_variable` ends, and its memory is released. + +## Example + +In the following example, the `a_local_variable` of integer data type is defined inside the function `local_variable()`: + +```cpp +#include +using namespace std; + +void local_variable(){ + int a_local_variable = 1; + cout < +using namespace std; + +void local(){ + int var = 0; + cout< +#include + +class Data { +public: + Data(std::string value) : data(value), accessCount(0) {} + + void displayData() const { + ++accessCount; // Modification allowed due to 'mutable' + std::cout << "Data: " << data << ", Access count: " << accessCount << std::endl; + } + +private: + std::string data; + mutable int accessCount; // Can be modified in constant methods +}; + +int main() { + Data d("Sample"); + d.displayData(); + d.displayData(); + return 0; +} +``` + +The above code produces the following output: + +```shell +Data: Sample, Access count: 1 +Data: Sample, Access count: 2 +``` + +Here, even though `displayData()` is a constant member function, `accessCount` can be incremented due to its `mutable` declaration. + +## Codebyte Example + +The following codebyte example demonstrates the usage of mutable variables: + +```codebyte/cpp +#include + +class Counter { +public: + Counter() : count(0) {} + + void increment() const { + ++count; // 'count' is mutable, so this modification is allowed in this constant method + } + + int getCount() const { + return count; + } + +private: + mutable int count; +}; + +int main() { + Counter counter; + counter.increment(); + counter.increment(); + std::cout << "Count: " << counter.getCount() << std::endl; + return 0; +} +``` diff --git a/content/cpp/concepts/variables/variables.md b/content/cpp/concepts/variables/variables.md index 7427b131431..21e0e7df5b0 100644 --- a/content/cpp/concepts/variables/variables.md +++ b/content/cpp/concepts/variables/variables.md @@ -1,6 +1,6 @@ --- Title: 'Variables' -Description: 'A variable refers to a storage location in the computer’s memory that one can set aside to save, retrieve, and manipulate data. To create a variable, the type must be specified and a value must be assigned to it.' +Description: 'A variable refers to a storage location in the computer’s memory that one can set aside to save, retrieve, and manipulate data.' Subjects: - 'Computer Science' - 'Game Development' @@ -12,11 +12,11 @@ CatalogContent: - 'paths/computer-science' --- -A **variable** refers to a storage location in the computer’s memory that one can set aside to save, retrieve, and manipulate data. +A **variable** refers to a storage location in the computer’s memory that one can set aside to save, retrieve, and manipulate data. Variables act as containers for storing information that can be changed or updated during the execution of a program. ## Declare a Variable -To create a variable, the type must be specified and a value must be assigned to it: +To declare a variable, the type of data the variable will hold must be specified, followed by the variable name. Optionally, a value can be assigned to the variable at the time of declaration: ```pseudo type name = value; @@ -46,8 +46,75 @@ The output would be: I am 30 years old. ``` +## Data Types in Variables + +Each variable in programming has a type, which defines the kind of data it can hold. Here are some common data types: + +- **int**: for integers (whole numbers), e.g., + +```cpp +int score = 10; +``` + +- **float**: A single-precision floating-point number, typically occupying 4 bytes (32 bits). It offers less precision and is used when memory efficiency is more important than accuracy, e.g., + +```cpp +float pi = 3.14159; +``` + +- **double**: A double-precision floating-point number, typically occupying 8 bytes (64 bits). It provides more precision and is the default choice when you need to store decimal numbers in C++. + +```cpp +double pi = 3.14159265358979323846; +``` + +- **char**: A single character, e.g., + +```cpp +char letter = 'A'; +``` + +- **bool**: for boolean values (true or false), e.g., + +```cpp +bool isAdmin = true; +``` + +## Example + +The below example shows the usage of variables: + +```cpp +#include + +int main() { + int age = 25; + double temperature = 36.6; + char initial = 'R'; + bool isSunny = true; + + std::cout << "Age: " << age << std::endl; + std::cout << "Temperature: " << temperature << "°C" << std::endl; + std::cout << "Initial: " << initial << std::endl; + std::cout << "Is it sunny? " << (isSunny ? "Yes" : "No") << std::endl; + + return 0; +} +``` + +The code above generates the following output: + +```shell +Age: 25 +Temperature: 36.6°C +Initial: R +Is it sunny? Yes +``` + ## Codebyte Example +Run the codebyte to understand how variables work: + ```codebyte/cpp #include diff --git a/content/cpp/concepts/vectors/terms/back/back.md b/content/cpp/concepts/vectors/terms/back/back.md new file mode 100644 index 00000000000..71e62e0dcb0 --- /dev/null +++ b/content/cpp/concepts/vectors/terms/back/back.md @@ -0,0 +1,64 @@ +--- +Title: '.back()' +Description: 'Used to access the last element in a vector.' +Subjects: + - 'Computer Science' + - 'Game Development' +Tags: + - 'Vectors' + - 'Programming' + - 'Data Structures' + - 'Methods' +CatalogContent: + - 'learn-c-plus-plus' + - 'paths/computer-science' +--- + +The C++ **`.back()`** method is used to access the last element in a vector. It views or modifies the element without removing it from the vector. This method is primarily used to access the most recently added element. + +## Syntax + +```pseudo +vectorName.back(); +``` + +## Example + +The below example shows the use of `.back()` method in c++ vectors, here `numbers` is a vector which has 5 elements in it and it displays the last element in the vector with the help of the `.back()` method, then the last element in the vector is modifies and the modified value is displayed. + +```cpp +#include +#include +//This is compulsory to include vectors while using vectors. + +int main(){ + std::vectornumbers = {10,20,40,50,60}; + std::cout<<"The last element in the vector is: "<< numbers.back()<< std::endl; + numbers.back() = 80; + std::cout <<"The last element in the vector after modification is: "< +#include +int main() { + std::vector numbers = {100, 90, 80, 70, 60}; + std::cout << numbers.back() << std::endl; + numbers.back() = 10; + std::cout << numbers.back() << std::endl; + return 0; +} +``` diff --git a/content/css/concepts/position/terms/absolute/absolute.md b/content/css/concepts/position/terms/absolute/absolute.md new file mode 100644 index 00000000000..13d57a83466 --- /dev/null +++ b/content/css/concepts/position/terms/absolute/absolute.md @@ -0,0 +1,129 @@ +--- +Title: 'absolute' +Description: 'Places an element relative to its nearest positioned ancestor or the browser window.' +Subjects: + - 'Web Design' + - 'Web Development' +Tags: + - 'CSS' + - 'Positioning' +CatalogContent: + - 'learn-css' + - 'paths/front-end-engineer-career-path' +--- + +Places an element relative to its nearest positioned ancestor or the browser window. If an element has `position: absolute`; declared, it is removed from the normal document flow, so it does not affect the layout of surrounding elements. + +## Syntax + +```css +position: absolute; +``` + +When an element is set to `position: absolute`, the `top`, `right`, `bottom`, and `left` properties can be used to offset it from its normal position: + +```css +selector { + position: absolute; + top: ; + right: ; + bottom: ; + left: ; +} +``` + +- A `` is a measurable property it can have values such as `2px`, `30em`, and `10pt`. + +## Example 1 + +This example shows how absolute positioning works when the element is positioned relative to its parent container. By setting `top: 0` and `left: 0`, the `.box` sticks to the top-left corner of its parent. The `top`, `left`, `right`, or `bottom` can be adjusted to move it anywhere within the parent. + +```html +
+
Absolutely Positioned
+
+``` + +```css +.container { + position: relative; /* Important: This makes .box position relative to .container */ + + /* Optional styles for the example */ + width: 500px; + height: 300px; + background-color: #e9ecef; + border-radius: 8px; + border: 1px solid #dee2e6; + margin: 100px auto; + box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1); +} + +.box { + position: absolute; + top: 0px; + left: 0px; + + /* Optional styles for the example */ + width: 200px; + height: 120px; + background-color: #495057; + color: #f8f9fa; + display: flex; + justify-content: center; + align-items: center; + font-size: 18px; + border-radius: 4px; + box-shadow: 0 4px 8px rgba(0, 0, 0, 0.2); +} +``` + +Here's what the above example's output would look like: + +![Box at top-left of parent](https://raw.githubusercontent.com/Codecademy/docs/main/media/css-position-absolute-ex1.png) + +## Example 2 + +In the below example the parent container doesn't have `position: relative` (or any positioning), so the element with `position: absolute` will stick to the browser window. + +```html +
+
Absolutely Positioned
+
+``` + +```css +.container { + /* position: relative; */ + + /* Optional styles for the example */ + width: 500px; + height: 300px; + background-color: #e9ecef; + border-radius: 8px; + border: 1px solid #dee2e6; + margin: 100px auto; + box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1); +} + +.box { + position: absolute; + top: 0px; + left: 0px; + + /* Optional styles for the example */ + width: 200px; + height: 120px; + background-color: #495057; + color: #f8f9fa; + display: flex; + justify-content: center; + align-items: center; + font-size: 18px; + border-radius: 4px; + box-shadow: 0 4px 8px rgba(0, 0, 0, 0.2); +} +``` + +Here's what the above examples look like: + +![Box at top-left of the window](https://raw.githubusercontent.com/Codecademy/docs/main/media/css-position-absolute-ex2.png) diff --git a/content/css/concepts/position/terms/fixed/fixed.md b/content/css/concepts/position/terms/fixed/fixed.md new file mode 100644 index 00000000000..2a363b0ddc7 --- /dev/null +++ b/content/css/concepts/position/terms/fixed/fixed.md @@ -0,0 +1,64 @@ +--- +Title: 'fixed' +Description: 'Positions an element relative to the viewport, removing it from the document flow and keeping it fixed during page scrolling.' +Subjects: + - 'Code Foundations' + - 'Computer Science' +Tags: + - 'Attributes' + - 'CSS' + - 'Design' + - 'Development' +CatalogContent: + - 'learn-css' + - 'paths/front-end-engineer-career-path' +--- + +In CSS, the **`fixed`** value of the `position` property positions an [HTML](https://www.codecademy.com/resources/docs/html) element of a webpage by taking that [element](https://www.codecademy.com/resources/docs/html/elements) out of the normal flow of the document and pinning it to a specified position. In this position, the element will remain fixed in place, even while scrolling the page. + +## Syntax + +```pseudo +position: fixed; +``` + +An element with a `fixed` position will be positioned relative to the viewport or the HTML element. In other words, it is fixed relative to the document itself. + +> **Note**: This differs from [absolute positioning](https://www.codecademy.com/resources/docs/css/position/absolute), where an element is positioned relative to its closest ancestor/parent element, whose position is also set to a value of [`relative`](https://www.codecademy.com/resources/docs/css/position/relative) or `absolute` (a non-static position). + +## Example + +This example demonstrates the fixed positioning. Here is the HTML code: + +```html + +``` + +Here is the CSS code: + +```css +nav.fixed { + display: inline-block; + height: 80px; + width: 100%; + position: fixed; + top: 50px; + left: 100px; + background-color: white; + border: 4px solid red; +} +``` + +In the code block above, the `nav` element with the [class](https://www.codecademy.com/resources/docs/html/classes) `fixed` has its `position` property set to `fixed`, along with its [`top`](https://www.codecademy.com/resources/docs/css/position/top) and [`left`](https://www.codecademy.com/resources/docs/css/position/left) properties set to values of `50px` and `100px`, respectively. + +This configuration means that the navigation bar will remain fixed in place relative to the viewport, appearing 50 pixels from the top and 100 pixels from the left of the browser window. As a result, when the user scrolls, the `nav` element will stay visible at that position. This will render in the browser as shown in the image: + +![Image of a fixed nav element in the browser window/viewport](https://raw.githubusercontent.com/Codecademy/docs/main/media/position-fixed-example.png) + +The `nav` element is taken out of the document flow and positioned `50px` from the top and `100px` from the left. Although the [`width`](https://www.codecademy.com/resources/docs/css/sizing/width) property is set to `100%`, its position may cause it to extend beyond the right side of the viewport, depending on the viewport width and the element's total width (including [padding](https://www.codecademy.com/resources/docs/css/padding) and [borders](https://www.codecademy.com/resources/docs/css/borders)). + +If the `nav` element had the `position` property set to [`static`](https://www.codecademy.com/resources/docs/css/position/static) (the default value), it would remain in its default position, i.e., flush against the top-left corner of the viewport: + +![Image of a static nav element in the browser window/viewport](https://raw.githubusercontent.com/Codecademy/docs/main/media/position-static-example.png) diff --git a/content/css/concepts/position/terms/left/left.md b/content/css/concepts/position/terms/left/left.md index 5dff9085d9c..0ed30e7ff6e 100644 --- a/content/css/concepts/position/terms/left/left.md +++ b/content/css/concepts/position/terms/left/left.md @@ -43,7 +43,7 @@ Set the position of `.box` element `40px` off the left edge of the nearest relat } ``` -![Example of position being absolute](<(https://raw.githubusercontent.com/Codecademy/docs/main/media/example-css-left()-absolute.png)>) +![Example of position being absolute](https://raw.githubusercontent.com/Codecademy/docs/main/media/example-css-left%28%29-absolute.png) ## Example 2 @@ -59,4 +59,4 @@ Set the position of `.box` element `40px` from the elements left edge. } ``` -![Example of position being relative](<(https://raw.githubusercontent.com/Codecademy/docs/main/media/example-css-left()-relative.png)>) +![Example of position being relative](https://raw.githubusercontent.com/Codecademy/docs/main/media/example-css-left%28%29-relative.png) diff --git a/content/css/concepts/position/terms/relative/relative.md b/content/css/concepts/position/terms/relative/relative.md new file mode 100644 index 00000000000..fad4ade56d2 --- /dev/null +++ b/content/css/concepts/position/terms/relative/relative.md @@ -0,0 +1,128 @@ +--- +Title: 'relative' +Description: 'Positions an element relative to its normal document flow placement, allowing for improved styling control.' +Subjects: + - 'Web Design' + - 'Web Development' +Tags: + - 'CSS' + - 'Elements' + - 'Positioning' + - 'Values' +CatalogContent: + - 'learn-css' + - 'paths/front-end-engineer-career-path' +--- + +In CSS, the **`relative`** value of the `position` property allows an element to be positioned relative to its normal position in the document flow, enabling adjustments without affecting the layout of surrounding elements. + +## Syntax + +```pseudo +position: relative; +``` + +When an element is set to `position: relative`, the [`top`](https://www.codecademy.com/resources/docs/css/position/top), [`right`](https://www.codecademy.com/resources/docs/css/position/right), [`bottom`](https://www.codecademy.com/resources/docs/css/position/bottom), and [`left`](https://www.codecademy.com/resources/docs/css/position/left) properties can be used to offset it from its normal position as follows: + +```pseudo +selector { + position: relative; + top: ; + right: ; + bottom: ; + left: ; +} +``` + +- ``: A value that can be specified in pixels (px), ems (em), rems (rem), percentages (%), or other [CSS units](https://www.codecademy.com/resources/docs/css/units). Positive values move the element away from the specified edge and negative values move it towards the specified edge. + +## Example 1 + +This example demonstrates basic relative positioning of a single element. Here is the HTML code: + +```html +
+
+
+``` + +Here is the CSS code: + +```css +.container { + position: relative; /* Enables child elements to be positioned absolutely within this container */ + width: 600px; + height: 360px; +} + +.box { + position: relative; /* Shifts this box relative to its normal position */ + top: 50px; /* Moves the box 50px down from its original position */ + left: 100px; /* Moves the box 100px to the right from its original position */ + width: 200px; + height: 200px; +} +``` + +Here's what the above example's output looks like: + +![CSS Relative Position Example Output](https://raw.githubusercontent.com/Codecademy/docs/main/media/css-position-relative-ex1.png) + +In this example, the blue box is moved 50 pixels down and 100 pixels to the right from its original position within the container. + +## Example 2 + +This example covers additional aspects of relative positioning, including [`z-index`](https://www.codecademy.com/resources/docs/css/position/z-index) and percentage-based positioning. Here is the HTML code: + +```html +
+
Z-index: 2
+
50% left
+
Z-index: 3
+
+``` + +Here is the CSS code: + +```css +.container { + position: relative; /* Enables absolute positioning for its child elements */ + width: 300px; + height: 300px; +} + +.box { + position: relative; /* Shifts this box relative to its normal position */ + width: 100px; + height: 100px; +} + +#box1 { + z-index: 2; /* Stacks this box above others with lower z-index */ +} + +#box2 { + top: -50px; /* Moves this box 50px up from its original position */ + left: 50%; /* Moves this box 50% to the right from its original position */ + z-index: 1; /* Stacks this box below others with higher z-index */ +} + +#box3 { + top: -100px; /* Moves this box 100px up from its original position */ + left: 25%; /* Moves this box 25% to the right from its original position */ + z-index: 3; /* Stacks this box above others with lower z-index */ +} +``` + +The above code produces the following output: + +![CSS z-index and Percentage-Based Positioning Example Output](https://raw.githubusercontent.com/Codecademy/docs/main/media/css-position-relative-ex2.png) + +This advanced example demonstrates: + +1. The `z-index` usage to control stacking order of relatively positioned elements. +2. Percentage-based positioning (50% and 25% left). +3. Negative values for top positioning to move elements upwards. +4. The way relatively positioned elements interact with each other in the same container. + +The green box (`#box3`) appears on top due to its higher `z-index`, even though it is declared last in the HTML. The orange box (`#box2`) is positioned 50% from the left edge of the container, while the green box is 25% from the left. diff --git a/content/data-science/data-science.md b/content/data-science/data-science.md index 1b23c3e51f3..1d75663fbeb 100644 --- a/content/data-science/data-science.md +++ b/content/data-science/data-science.md @@ -22,7 +22,7 @@ Since the beginning of the 21st century, data science has been used in almost ev - Data Use - Data Visualization - Data Analytics - - [Data Mining](https://wwww.codecademy.com/resources/docs/data-science/data-mining) + - [Data Mining](https://www.codecademy.com/resources/docs/data-science/data-mining) - Business Intelligence and Strategy - [Artificial Intelligence](https://www.codecademy.com/resources/docs/ai) - [Machine Learning](https://www.codecademy.com/resources/docs/ai/machine-learning) diff --git a/content/javascript/concepts/bitwise-operators/bitwise-operators.md b/content/javascript/concepts/bitwise-operators/bitwise-operators.md index cbaf3a57846..f441ed1227e 100644 --- a/content/javascript/concepts/bitwise-operators/bitwise-operators.md +++ b/content/javascript/concepts/bitwise-operators/bitwise-operators.md @@ -1,6 +1,6 @@ --- Title: 'Bitwise Operators' -Description: 'Bitwise operators in JavaScript operate on 32-bit operands. Internally, JavaScript converts 64-bit floating point numbers into 32-bit signed integers before performing the operation, it then converts back to 64-bit numbers to return the result. JavaScript uses the following bitwise operators: &, |, ^, ~, <<, >>, >>>.' +Description: 'Bitwise operators in JavaScript perform operations on binary representations of integers. They manipulate bits directly using AND, OR, XOR, NOT, shifts, etc.' Subjects: - 'Web Development' - 'Computer Science' @@ -8,10 +8,10 @@ Tags: - 'Operators' CatalogContent: - 'introduction-to-javascript' - - 'paths/create-a-back-end-app-with-javascript' + - 'paths/front-end-engineer-career-path' --- -Bitwise operators in JavaScript operate on 32-bit operands. Internally, JavaScript converts 64-bit floating point numbers into 32-bit signed integers before performing the operation, it then converts back to 64-bit numbers to return the result. +Bitwise operators in JavaScript perform operations on binary representations of integers. They manipulate bits directly using AND, OR, XOR, NOT, shifts, etc. JavaScript uses the following bitwise operators: @@ -25,11 +25,11 @@ JavaScript uses the following bitwise operators: | `>>` | Signed right shift | Pushes copies of leftmost bit in from left, rightmost bit falls off (preserves sign). | | `>>>` | Zero fill right shift | Pushes zeros in from left, rightmost bits fall off. | -## Examples +## AND -### AND +The AND (`&`) operator performs a bitwise AND on two numbers. The result is 1 only when both bits are 1: -```javascript +```js console.log(19 & 7); // Output: 3 // 10011 = 19 @@ -37,9 +37,11 @@ console.log(19 & 7); // Output: 3 // 00011 = 3 ``` -### OR +## OR -```javascript +The OR (`|`) operator performs a bitwise OR on two numbers. The result is 1 if either of the bits is 1: + +```js console.log(19 | 7); // Output: 23 // 10011 = 19 @@ -47,9 +49,11 @@ console.log(19 | 7); // Output: 23 // 10111 = 23 ``` -### XOR +## XOR + +The XOR (`^`) operator performs a bitwise XOR on two numbers. The result is 1 if the bits are different: -```javascript +```js console.log(19 ^ 7); // Output: 20 // 10011 = 19 @@ -57,33 +61,38 @@ console.log(19 ^ 7); // Output: 20 // 10100 = 20 ``` -### NOT +## NOT -Because integers are stored in two's complement -(to change the sign, invert the binary digits and add one) -a `~` operation will change the sign of the number and change the absolute value by one. +Because integers are stored in two's complement (to change the sign, the binary digits are first inverted and then `1` is added), a NOT (`~`) operation will change the sign of the number and change the absolute value by one: -```javascript +```js console.log(~19); // Output: -20 // 00000000000000000000000000010011 = 19 // 11111111111111111111111111101100 = -20 ``` -### Zero fill left shift +## Zero Fill Left Shift + +The zero fill left shift (`<<`) operator shifts the bits of a number to the left, pushing zeros in from the right. The leftmost bits fall off and are discarded: -```javascript +```js console.log(19 << 3); // Output: 152 // 00000000000000000000000000010011 = 19 // 00000000000000000000000010011000 = 152 + +console.log(5 << 2); // Output: 20 + +// 00000000000000000000000000000101 = 5 +// 00000000000000000000000000010100 = 20 ``` -### Signed right shift +## Signed Right Shift -The `>>` operator preserves the sign of the operand by pushing copies of the leftmost bit in from the left. +The signed right shift (`>>`) operator shifts the bits of a number to the right, pushing zeros in from the left. The rightmost bits fall off and are discarded: -```javascript +```js console.log(19 >> 3); // Output: 2 // 00000000000000000000000000010011 = 19 @@ -95,11 +104,11 @@ console.log(-20 >> 3); // Output: -3 // 11111111111111111111111111111101 = -3 ``` -### Zero fill right shift +## Zero Fill Right Shift -The `>>>` operator does not preserve the sign. It pushes zeros in from the left, pushing the sign bit out of its leftmost position. +The zero fill right shift (`>>>`) operator does not preserve the sign. It pushes zeros in from the left, pushing the sign bit out of its leftmost position: -```javascript +```js console.log(19 >>> 3); // Output: 2 // 00000000000000000000000000010011 = 19 diff --git a/content/javascript/concepts/callbacks/callbacks.md b/content/javascript/concepts/callbacks/callbacks.md index 3cd2c0eafca..0faa355c197 100644 --- a/content/javascript/concepts/callbacks/callbacks.md +++ b/content/javascript/concepts/callbacks/callbacks.md @@ -1,6 +1,6 @@ --- Title: 'Callbacks' -Description: 'Callback functions are functions that are passed as arguments in other functions. A callback function can then be invoked during the execution of that higher order function (that it is an argument of). In JavaScript, functions can be passed as arguments because functions are objects. Suppose there are two functions, functionA() and functionB(): js function functionA(num1, num2) { return num1 + num2; }' +Description: 'A callback is a function passed as an argument to another function.' Subjects: - 'Web Development' - 'Computer Science' @@ -11,9 +11,11 @@ CatalogContent: - 'paths/front-end-engineer-career-path' --- -Callback functions are functions that are passed as arguments in other functions. A callback function can then be invoked during the execution of that higher order function (that it is an argument of). +A callback is a function passed as an argument to another function. In JavaScript, functions can be passed as arguments because functions are objects. -In JavaScript, functions can be passed as arguments because functions are objects. +A callback function gets invoked during the execution of the higher order function (that it is an argument of). They are used in asynchronous operations like network requests or DOM events to avoid waiting for the response until the async process is completed. + +## Example Suppose a function is created which makes a calculation and doubles the results of that calculation: @@ -72,3 +74,111 @@ console.log(createNewArray(array, double)); console.log(createNewArray(array, divide)); console.log(createNewArray(array, increment)); ``` + +## Callbacks in Asynchronous JavaScript + +Callbacks are often used in asynchronous operations like fetching data from an API or listening for a DOM Event, where users don’t want to block the main thread while waiting for the response. + +### Example + +The following example demonstrates how to make an API call using callbacks: + +```js +function fetchData(url, callback) { + var xhr = new XMLHttpRequest(); // Create a new XMLHttpRequest object + xhr.open('GET', url, true); // Initialize a request + + xhr.onload = function () { + if (xhr.status === 200) { + // Check if the request was successful + callback(null, xhr.responseText); // Call the callback function with data + } else { + callback('Error: ' + xhr.status, null); // Pass error message if request failed + } + }; + + xhr.onerror = function () { + callback('Request failed', null); // Handle network errors + }; + + xhr.send(); // Send the request +} + +// Callback function to handle the response +function handleResponse(error, data) { + if (error) { + console.error(error); // Handle error case + } else { + console.log('Data received:', data); // Handle success case + } +} + +// Usage +var url = 'https://jsonplaceholder.typicode.com/posts/1'; // Sample API endpoint +fetchData(url, handleResponse); // Call the fetch function and pass the callback +``` + +In the code above, the `fetchData` function takes two arguments `url` and `handleResponse`. `url` is the API url from which we have to get the data. `handleResponse` is the callback funtion that gets executed when the network request returns either data or an error. + +The output will look like this: + +```shell +Data received: { + "userId": 1, + "id": 1, + "title": "sunt aut facere repellat provident occaecati excepturi optio reprehenderit", + "body": "quia et suscipit..." +} +``` + +### Codebyte Example + +The following codebyte example shows how to make an API call using callbacks: + +```codebyte/javascript +const https = require('https'); + +function fetchData(url, callback) { + https.get(url, res => { + let data = ''; + res.on('data', chunk => { + data += chunk; + }); + res.on('end', () => { + data = JSON.parse(data); + handleResponse(null, data); + }) + }).on('error', err => { + handleResponse(err, null); + }); +} + +// Callback function to handle the response +function handleResponse(error, data) { + if (error) { + console.error('Error', error.message); // Handle error case + } else { + console.log('Data received:', data); // Handle success case + } +} + +// Usage +var url = 'https://jsonplaceholder.typicode.com/posts/1'; // Sample API endpoint +fetchData(url, handleResponse); // Call the fetch function and pass the callback +``` + +## Callback Hell + +When multiple asynchronous operations are nested using callbacks, it can lead to complex code and might lead to errors and difficult to debug, often referred to as _callback hell_: + +```js +doSomethingFirst(function () { + doSomethingSecond(function () { + doAnotherThird(function () { + // and so on... + }); + }); +}); +``` + +To avoid this, **promises** or **async/await** can be used, which make the code more readable and maintainable. diff --git a/content/javascript/concepts/conditionals/conditionals.md b/content/javascript/concepts/conditionals/conditionals.md index 4db9edab837..a3ac215d8ff 100644 --- a/content/javascript/concepts/conditionals/conditionals.md +++ b/content/javascript/concepts/conditionals/conditionals.md @@ -1,6 +1,6 @@ --- Title: 'Conditionals' -Description: 'Conditionals take an expression, which is code that evaluates to determine a value, and checks if it is true or false. If it’s true, we can tell our program to do one thing — we can even account for false to do another. An if statement accepts an expression with a set of parentheses: - If the expression evaluates to a truthy value, then the code within its code body executes. - If the expression evaluates to a falsy value, its code body will not execute. js const isMailSent = true; if (isMailSent) {' +Description: 'Conditionals evaluate an expression (a piece of code that produces a value) to determine whether it is true or false.' Subjects: - 'Web Development' - 'Computer Science' @@ -13,7 +13,7 @@ CatalogContent: - 'paths/front-end-engineer-career-path' --- -Conditionals take an expression, which is code that evaluates to determine a value, and checks if it is `true` or `false`. If it’s `true`, we can tell our program to do one thing — we can even account for `false` to do another. +Conditionals take an expression, which is code that evaluates to determine a value, and checks if it is `true` or `false`. If it’s `true`, the program can be told to do one thing and if it's `false`, the program can be told to do another thing. ## If Statement diff --git a/content/javascript/concepts/errors/errors.md b/content/javascript/concepts/errors/errors.md index 4be70c07809..56cc4bf54de 100644 --- a/content/javascript/concepts/errors/errors.md +++ b/content/javascript/concepts/errors/errors.md @@ -1,6 +1,6 @@ --- Title: 'Errors' -Description: 'When JavaScript throws an error it throws an error object that consists of a name and a message property. The name is the general type of the error, and the message is a human-readable description of the specific error that happened. Thrown errors are caught by the next outer catch block of a try...catch...finally statement. They can also be thrown intentionally by the throw statement. The error object holds information about the exception that was thrown in its two properties: - name Sets or returns an error name. (Type of Error) - message Sets or returns an error message. (Description of specific instance.) The following types of error can be returned by the name property: - "EvalError" An error has occurred in the eval() function (Note: Depreciated in newer versions of JavaScript)' +Description: 'The JavaScript Error object represents runtime errors, providing information for throwing exceptions and handling them with try-catch blocks.' Subjects: - 'Web Development' - 'Computer Science' @@ -15,16 +15,19 @@ CatalogContent: - 'paths/create-a-back-end-app-with-javascript' --- -When JavaScript throws an error it throws an error object that consists of a `name` and a `message` property. The `name` is the general type of the error, and the `message` is a human-readable description of the specific error that happened. +**Errors** in JavaScript are issues that occur during runtime, represented by the `Error` object. This object provides information about the error type and message and can be used to throw exceptions or handle them in a `try-catch` block. + +When JavaScript throws an error, it throws an error object that consists of a `name` and a `message` property. The `name` is the general type of the error, and the `message` is a human-readable description of the specific error that happened. Thrown errors are caught by the next outer `catch` block of a `try...catch...finally` statement. They can also be thrown intentionally by the `throw` statement. ## The Error Object -The error object holds information about the exception that was thrown in its two properties: +The error object holds information about the exception that was thrown in its three properties: - `name` Sets or returns an error name. (Type of Error) - `message` Sets or returns an error message. (Description of specific instance.) +- `stack` Returns a string representing the point in the code where the error was instantiated. The following types of error can be returned by the `name` property: @@ -40,14 +43,53 @@ These are some example messages for various types of errors: - RangeError - invalid array length - invalid date + +```js +let arr = new Array(-1); // RangeError: Invalid array length +``` + - ReferenceError - "x" is not defined - assignment to undeclared variable "x" + +```js +console.log(x); // ReferenceError: x is not defined +``` + - SyntaxError - "x" is a reserved identifier - a declaration in the head of a for-of loop can't have an initializer + +```js +// SyntaxError: 'for-of' loop variable can't be initialized +try { + for (let i = 0 of [1, 2, 3]) { + console.log(i); + } +} catch (err) { + console.log(err.name); // "SyntaxError" + console.log(err.message); // "'for-of' loop variable can't have an initializer" +} +``` + - TypeError - "x" is not a function - "x" is read-only + +```js +let num = 42; +num.toUpperCase(); // TypeError: num.toUpperCase is not a function +``` + - URIError - malformed URI sequence + +```js +// This is an invalid percent encoding (notice '%E0%' is incomplete). +try { + let badURI = decodeURIComponent('%E0%'); +} catch (err) { + console.log(err.name); // "URIError" + console.log(err.message); // "malformed URI sequence" +} +``` diff --git a/content/javascript/concepts/modules/modules.md b/content/javascript/concepts/modules/modules.md index 77a52fd2b9b..8edcf5776f3 100644 --- a/content/javascript/concepts/modules/modules.md +++ b/content/javascript/concepts/modules/modules.md @@ -1,6 +1,6 @@ --- Title: 'Modules' -Description: 'As the program grows bigger, it may contain many lines of code. Instead of putting everything in a single file, modules can be used to separate codes in separate files as per their functionality. This makes the code more organized and easier to maintain. A module is a file that contains code that performs a specific task. A module may contain variables, functions, classes, etc. Suppose, a file named greetPerson.js contains the following code: js // Exporting a function export function greetPerson(name) { return Hi, ${name};' +Description: 'Modules organize code by separating related functions, classes, and variables into distinct files, making management and reuse easier in larger projects.' Subjects: - 'Web Development' - 'Computer Science' @@ -11,11 +11,9 @@ CatalogContent: - 'paths/front-end-engineer-career-path' --- -As the program grows bigger, it may contain many lines of code. Instead of putting everything in a single file, modules can be used to separate codes in separate files as per their functionality. This makes the code more organized and easier to maintain. +Modules divide large programs into separate files based on tasks, grouping related functions, variables, or classes for easier management and reuse. -A module is a file that contains code that performs a specific task. A module may contain variables, functions, classes, etc. - -Suppose, a file named **greetPerson.js** contains the following code: +Suppose a file named **greetPerson.js** contains the following code: ```js // Exporting a function @@ -87,9 +85,7 @@ Here, both the `name` variable and the `difference()` function from the **module ## Renaming Imports and Exports -If the objects (variables, functions, etc.) that you want to import are already present in your main file, the program may not behave as you want. In this case, the program takes value from the main file instead of the imported file. - -To avoid naming conflicts, you can rename these objects during the export or during the import. +To prevent naming conflicts, it is important to rename variables or functions when exporting or importing. This ensures the program uses the correct values from the intended file. ### Rename in the export file (the module) @@ -103,7 +99,7 @@ export { function1 as newName1, function2 as newName2 }; import { newName1, newName2 } from './module.js'; ``` -Here, while exporting the function from **module.js** file, new names (here, `newName1` & `newName2`) are given to the function. Hence, when importing that function, the new name is used to reference that function. +When exporting from module.js, new names (`newName1`, `newName2`) are assigned to functions, the new names must be used when importing and referencing them. ### Rename in the import file (the main file) @@ -117,7 +113,7 @@ export { function1, function2 }; import { function1 as newName1, function2 as newName2 } from './module.js'; ``` -Here, while importing the function, the new names (here, `newName1` & `newName2`) are used for the function name. Now you use the new names to reference these functions. +When importing the function, new names (`newName1`, `newName2`) are used. These new names are then used to reference the functions in the code. ## Default Export diff --git a/content/javascript/concepts/regexp/regexp.md b/content/javascript/concepts/regexp/regexp.md index c86165a9a28..540a26f2c03 100644 --- a/content/javascript/concepts/regexp/regexp.md +++ b/content/javascript/concepts/regexp/regexp.md @@ -1,6 +1,6 @@ --- Title: 'RegExp' -Description: 'The RegExp object is used for matching strings with Regular Expressions, which is a special string pattern that uses various character sequences to match a character sequence or pattern in other strings.' +Description: 'A RegExp object defines patterns for matching and manipulating strings in JavaScript.' Subjects: - 'Web Development' - 'Computer Science' @@ -12,53 +12,53 @@ CatalogContent: - 'paths/create-a-back-end-app-with-javascript' --- -The `RegExp` object is used for matching strings with Regular Expressions. A Regular Expression is a special string, called a pattern, that uses various character sequences to define the characteristics to match a character sequence within another string. +The `RegExp` object defines patterns for matching and manipulating strings in JavaScript. Regular Expressions perform pattern-based searches, replacements, or any other operations on strings. A `RegExp` object can also have flags set along with a pattern to change how matches are performed. ## Syntax -There are two methods of creating a `RegExp` object. The first method is literal notation using slashes to delimit the pattern, followed by any flags. The second method uses the `RegExp` constructor which takes the pattern as the first argument and any flags as the second. +There are two ways to create a `RegExp` object: -```pseudo -// Using literal notation +- Literal Notation: Use slashes to delimit the pattern, followed by any flags. + +```js let re1 = /foo?/i; +``` -// Using RegExp constructor -let re2 = new RegExp('foo?', 'i'); +- Constructor Function: Use the `RegExp` constructor, passing the pattern as the first argument and any flags as the second. -// Both create a RegExp object with a pattern = "foo?" and a flag = "i" +```js +let re2 = new RegExp('foo?', 'i'); ``` -There is a difference between the methods. Literal notation compiles when the expression is evaluated. It should be used when the pattern will remain constant, so it won't be recompiled unnecessarily, such as in a loop. +There is a difference between the methods. Literal notation compiles when the expression is evaluated. It should be used when the pattern will remain constant so it won't be recompiled unnecessarily, such as in a loop. -Using the object constructor means the expression will be compiled at runtime. It should be used when the pattern of the `RegExp` object would be subject to change, or the pattern is obtained during runtime, such as from user input. +Using the object constructor means the expression will be compiled at runtime. It should be used when the pattern of the `RegExp` object is subject to change or is obtained during runtime, such as from user input. -### RegExp Properties +### Properties -| Property | Description | -| ------------- | -------------------------------------------------------------------------------------------------------------------------------- | -| `.flags` | Returns a string containing the flags of the `RegExp` object. | -| `.dotAll` | Does `.` match newlines or not? | -| `.global` | Does the `RegExp` object test against all matches in a string, or only the first? | -| `.hasIndices` | Does the Regular Expression result expose the start and end indices of captured substrings? | -| `.ignoreCase` | Does the `RegExp` object ignore case when performing a match? | -| `.multiline` | Does the `RegExp` object perform matches across multiple lines? | -| `.source` | The text of the pattern used by the `RegExp` object. | -| `.sticky` | Is the search sticky? (Does the next match have to occur at `lastIndex`, or can we match the next occurrence after `lastIndex`?) | -| `.unicode` | Are Unicode features enabled? | -| `.lastIndex` | The index at which to start the next match. | +| Property | Description | +| ------------- | ------------------------------------------------------------------------------------- | +| `.flags` | Returns a string containing the flags of the `RegExp` object. | +| `.dotAll` | Indicates if `.` matches newlines. | +| `.global` | Indicates if the `RegExp` searches for all matches. | +| `.hasIndices` | Does the Regular Expression result expose captured substrings' start and end indices? | +| `.ignoreCase` | Indicates if the `RegExp` is case-insensitive. | +| `.multiline` | Indicates if the `RegExp` performs multiline matches. | +| `.source` | The text of the pattern used by the `RegExp` object. | +| `.sticky` | Indicates if the `RegExp` only matches from `lastIndex`. | +| `.unicode` | Indicates if the `RegExp` treats patterns as Unicode sequences. | +| `.lastIndex` | The index to start the next match. | -### RegExp Methods +### Methods -| Method | Description | -| ------------ | ------------------------------------------------ | -| `.exec(str)` | Execute a search on its `str` string parameter. | -| `.test(str)` | Tests for a match in its `str` string parameter. | +- `.exec(str)`: Executes a search for a match in the given string and returns an array of results. +- `.test(str)` Tests whether a pattern is found in the given string and returns `true` or `false`. -### String Methods that Can Use RegExp Objects +### String Methods Supporting RegExp -In the following `re` is a `RegExp` object. +In the following, `re` is a `RegExp` object. | Method | Description | | ---------------------- | ------------------------------------------------------------------ | @@ -70,20 +70,20 @@ In the following `re` is a `RegExp` object. \* The RegExp object must have the `g` flag set or an exception is thrown. -### `RegExp` Flags +### RegExp Flags -When specified, these flags change the default match behavior of the `RegExp` object. +`RegExp` flags modify the default matching behaviour. -| Flag | Description | -| ---- | ------------------------------------------------------------------------ | -| `g` | Performs a global match, finding all matches rather than just the first. | -| `i` | Makes matches case-insensitive. Matches both uppercase and lowercase. | -| `m` | Performs multiline matches. (Changes behavior of `^`,`$`) | -| `s` | Allows `.` to match newline characters. | -| `u` | Enables Unicode support. | -| `y` | Matches are sticky, looking only at exact position in the text. | +| Flag | Description | +| ---- | --------------------------------------------------------------------- | +| `g` | Finds all matches, not just the first one. | +| `i` | Makes matches case-insensitive. Matches both uppercase and lowercase. | +| `m` | Performs multiline matches. (Changes behavior of `^`,`$`) | +| `s` | Allows `.` to match newline characters. | +| `u` | Enables Unicode support. | +| `y` | Matches are sticky, looking only at exact position in the text. | -Usage: +#### Example 1 ```js let re1 = /foo?/gim; @@ -100,12 +100,12 @@ The following characters are used to define a Regular Expression string. The following match the boundaries between characters, not the characters themselves. -| Characters | Meaning | -| ---------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------ | -| `^` | Matches the beginning of input. In multiline search, matches immediately after a line break character. | -| `$` | Matches the end of input. In multiline search matches immediately before a line break character. | -| `\b` | Matches a word boundary. Point where a word character is not followed by a word character, or the point where a word character is not preceded by another word character | -| `\B` | Matches a non-word boundary. Point where preceding and following character are of the same type. | +| Characters | Meaning | +| ---------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | +| `^` | Matches the beginning of input. In multiline search, matches immediately after a line break character. | +| `$` | Matches the end of input. In multiline search, matches immediately before a line breaks character. | +| `\b` | Matches a word boundary. The point where a word character is not followed by a word character or the point where a word character is not preceded by another word character | +| `\B` | Matches a non-word boundary. The point where preceding and following characters are of the same type. | The following match a character or expression based on what follows or precedes it. @@ -116,7 +116,7 @@ The following match a character or expression based on what follows or precedes | `(?<=y)x` | Match `x` only if `x` is immediately preceded by `y`. `y` is not part of the match results. | | `(?\\unnnn | Matches a UTF-16 code unit with the value nnnn (four hexadecimal digits). | | `\` | Followed by a special character, means that the character should be matched literally. | -#### Examples +#### Example 3 ```js let str = '2001: A Space Odyssey'; @@ -199,7 +199,7 @@ Indicate groups and ranges of characters to match. \* If the hyphen falls at the start or end of the sequence in brackets, it is treated as a literal hyphen. -#### Examples +#### Example 4 ```js let str = 'Peter Piper picked a peck of pickled peppers.'; @@ -232,7 +232,7 @@ Quantifiers specify the number of characters or expressions to match. By default, these quantifiers are greedy, matching as much of the string as possible. By following the quantifier with `?` (`x*?`) the match will stop at its first occurrence. -#### Examples +#### Example 5 ```js let str = 'Billy bought a bushel of blue balloons.'; diff --git a/content/javascript/concepts/substring/substring.md b/content/javascript/concepts/substring/substring.md index fe1603f31b8..7feea0b3ab3 100644 --- a/content/javascript/concepts/substring/substring.md +++ b/content/javascript/concepts/substring/substring.md @@ -1,6 +1,6 @@ --- Title: 'Substring' -Description: 'The .substring() method returns part of a string. If given two arguments, they are the start and end indexes of the characters returned. If given one argument, it returns characters from that point to the end of the string. javascript // Returns characters from startIndex to end of string string.substring(startIndex); // Returns characters from startIndex to endIndex string.substring(startIndex, endIndex); ' +Description: 'Extracts a portion of a string between two given indices and returns a new string. If only one index is given, it goes to the end.' Subjects: - 'Web Development' - 'Computer Science' @@ -13,31 +13,33 @@ CatalogContent: - 'paths/create-a-back-end-app-with-javascript' --- -The `.substring()` method returns part of a string. If given two arguments, they are the start and end indexes of the characters returned. If given one argument, it returns characters from that point to the end of the string. +The **`substring()`** method in JavaScript extracts a portion of a string from one position to another (exclusive) and returns a new string. If the second position is omitted, it returns characters from the first position to the end of the string. ## Syntax -```javascript +```pseudo // Returns characters from startIndex to end of string string.substring(startIndex); +``` + +Or alternatively: +```pseudo // Returns characters from startIndex to endIndex string.substring(startIndex, endIndex); ``` ## Details -- `.substring()` returns characters at the start index up to, but not including, the character at the end index. - -- If the end index is omitted `.substring()` returns characters at the start index up through the end of the string. +- `.substring()` returns characters from the start index up to, but not including, the character at the end index. -- If the start and end indexes are equal, `.substring()` returns an empty string. +- If the end index is omitted, `.substring()` returns characters from the start index through the end of the string. -- Indexes less than zero are interpreted as zero. +- If the start and end indices are equal, `.substring()` returns an empty string. -- Indexes that are `NaN` are treated as zero. +- Indices that are less than zero or are `NaN` are interpreted as zero. -- Indexes that are greater than `string.length` are treated as `string.length`. +- Indices that are greater than `string.length` are treated as `string.length`. - If the first argument is greater than the second argument, the first argument is treated as the end index and the second argument is treated as the start index. @@ -45,7 +47,7 @@ string.substring(startIndex, endIndex); Using `.substring()` to display characters from a given string. -```javascript +```js const str = 'Codecademy'; console.log(str.substring(0, 4)); @@ -62,7 +64,7 @@ console.log(str.substring(4, 99)); Using `.substring()` to display the last `6` characters from a given string. -```javascript +```js const str = 'Codecademy'; console.log(str.substring(str.length - 6)); diff --git a/content/javascript/concepts/this/this.md b/content/javascript/concepts/this/this.md index aa7b7d3677d..23c7a9d3882 100644 --- a/content/javascript/concepts/this/this.md +++ b/content/javascript/concepts/this/this.md @@ -1,6 +1,6 @@ --- Title: 'this' -Description: 'In JavaScript, the this keyword can have several meanings depending on the execution context. Most often it is used within a method of an object to return the instance of the object whose function is being executed, but what this returns can vary depending on the context.' +Description: 'It is often used within an object method, but what it refers to will vary depending on the execution context.' Subjects: - 'Web Development' - 'Computer Science' diff --git a/content/javascript/concepts/type-coercion/type-coercion.md b/content/javascript/concepts/type-coercion/type-coercion.md index 23bc5867d4e..f1daf442ad5 100644 --- a/content/javascript/concepts/type-coercion/type-coercion.md +++ b/content/javascript/concepts/type-coercion/type-coercion.md @@ -1,6 +1,6 @@ --- Title: 'Type Coercion' -Description: 'The modification of types in an expression in order to yield a result.' +Description: 'The process of converting a value from one data type to another.' Subjects: - 'Web Development' - 'Computer Science' @@ -14,25 +14,138 @@ CatalogContent: - 'paths/front-end-engineer-career-path' --- -**Type coercion** is the modification of a type within an expression in order to yield a result. In JavaScript expressions of mixed types are evaluated by default through type coercion. When strict type comparisons are required they should be implemented with the `===` and `!==` operators. +**Type coercion** is the process of converting a value from one data type to another (such as a string to number). It works on both primitive data types and objects. However, it always results in a primitive data type. -JavaScript is a relatively permissive language, and in many situations, such as mixed type expressions or function arguments the default behavior is to return a value, rather than an error. +Type coercion can be done both implicitly and explicitly. Explicit type coercion is the intentional conversion of a value from one data type to another and is typically done using native constructors such as `String()` without the `new` keyword in front of them. There is also implicit type coercion, in which values are converted from one data type to another by JavaScript. -## Mixed Type Expressions +## String Type Coercion -Expressions of mixed types are evaluated by changing one of the elements to match the other. For example, in the code below the string `6` is changed to a `number` type and will yield `true` and the product `36`. However, the use of values that have been evaluated in such an expression may lead to unintended results when this behavior is not expected. It is a best practice to use the alternative, strict comparison operators to avoid errors from this form of evaluation. +To coerce a value into a primitive string value explicitly, the `String()` function is used. To implicitly coerce a value into a string, the value simply needs to be added to an empty string. When coercing a string, the result is as expected, with the value staying the same, but the data type becomes a string. + +Here is an example: ```js -console.log(6 == '6'); -console.log(6 * '6'); +var a = 54.1; + +console.log(String(a)); +console.log(a + ''); -console.log(6 === '6'); +console.log(String(true)); +console.log(String(null)); ``` The code above will output: ```shell +54.1 +54.1 true -36 +null +``` + +## Number Type Coercion + +To explicitly coerce a value into a number, the `Number()` function is used. A value can be coerced implicitly by using it in a mathematical operation, such as subtracting 0 from it or multiplying it by 1 to not change its value. Implicit coercion will also occur if the value is used with a comparison operator such as `<`, a bitwise operator such as `|`, the unary `+` operator, or with any of the arithmetic operators. It's important to note that using a comparison operator to coerce a value to a number depends on the type of the operands. For example, if two strings are compared with a comparison operator, they will simply be compared lexicographically, and no type coercion will occur. + +Using `Number()` on booleans gives the expected results of `true` becoming `1` and `false` becoming `0`. When using `Number()` on a string, if the string's value is a valid number, it will successfully be converted into a number. If the string contains any non-numeric characters, the result will be `NaN`. An empty string returns `0`. + +Here is an example: + +```js +var a = '-76.2'; + +console.log(Number(a)); +console.log(a * 1); + +console.log(Number(true)); +console.log(Number(null)); +console.log(Number(undefined)); +console.log(Number('7km')); +``` + +The code above will output: + +```shell +-76.2 +-76.2 +1 +0 +NaN +NaN +``` + +## Boolean Type Coercion + +To explicitly coerce a value into a boolean, the `Boolean()` function is used. A value undergoes implicit coercion when used in a test expression for an `if` statement, `for` loop, `while` loop, or a ternary expression. A value can also undergo implict coercion when used as the left-hand operand to the logical operators (`||`, `&&`, and `!`). + +Nearly all possible values will convert into `true`, but only a handlful will convert into `false`. The values that will become false are: + +- `undefined` +- `null` +- `false` +- `0` +- `NaN` +- `""` + +All other values, including objects, when coerced to a boolean, will be converted into `true`. + +Here is an example: + +```js +var a = 'lamp'; + +console.log(Boolean(a)); +console.log(!!a); + +console.log(Boolean('')); +console.log(Boolean(null)); +``` + +The code above will output: + +```shell +true +true +false false ``` + +## Loose vs Strict Equals + +When using loose equals `==`, only the values of the operands are compared. If the values are of different types, one or both of the values will be implicitly coerced. On the other hand, strict equals `===` will not allow coercion and compares both the value and type of the operands. + +Here is an example: + +```js +var a = '12'; +var b = 12; + +console.log(a == b); +console.log(a === b); +``` + +The code above will output: + +```shell +true +false +``` + +## Codebyte Example + +The example below shows how type coercion works between a string and number with both loose and strict equals: + +```codebyte/javascript +var num = 5; +var str = "10"; + +var result1 = num + str; +var result2 = num * str; +var result3 = num == "5"; +var result4 = num === "5" + +console.log(result1); +console.log(result2); +console.log(result3); +console.log(result4); +``` diff --git a/content/kotlin/concepts/arrays/terms/arrayOfNulls/arrayOfNulls.md b/content/kotlin/concepts/arrays/terms/arrayOfNulls/arrayOfNulls.md new file mode 100644 index 00000000000..01b6fe4f34b --- /dev/null +++ b/content/kotlin/concepts/arrays/terms/arrayOfNulls/arrayOfNulls.md @@ -0,0 +1,52 @@ +--- +Title: 'arrayOfNulls()' +Description: 'Creates an array of a specified size with all elements initialized as null.' +Subjects: + - 'Code Foundations' + - 'Mobile Development' +Tags: + - 'Android' + - 'Arrays' + - 'Map' + - 'Kotlin' +CatalogContent: + - 'learn-kotlin' + - 'paths/computer-science' +--- + +In Kotlin, the **`arrayOfNulls()`** function creates an array of a specified size with all elements initialized to `null`. This function is useful for creating an array with a defined size when initial values are not yet available, allowing for values to be assigned later. + +## Syntax + +```pseudo +fun arrayOfNulls(size: Int): Array +``` + +- `T`: The type of elements in the array. +- `size`: An integer specifying the size of the array to create. + +It returns an `Array` of the specified size, initialized with `null`. + +## Example + +The following example uses the `arrayOfNulls()` function: + +```kotlin +fun main() { + // Create an array of size 5 with all elements initialized as null + val nullArray = arrayOfNulls(5) + + // Assign values to some elements in the array + nullArray[0] = 2 + nullArray[1] = 4 + + // Print the array after assigning values + println(nullArray.contentToString()) +} +``` + +This example results in the following output: + +```shell +[2, 4, null, null, null] +``` diff --git a/content/kotlin/concepts/arrays/terms/forEach/forEach.md b/content/kotlin/concepts/arrays/terms/forEach/forEach.md new file mode 100644 index 00000000000..d95f17ee97f --- /dev/null +++ b/content/kotlin/concepts/arrays/terms/forEach/forEach.md @@ -0,0 +1,56 @@ +--- +Title: '.forEach()' +Description: 'Iterates over elements in a collection and performs a specified action on each element, without producing a new collection.' +Subjects: + - 'Code Foundations' + - 'Mobile Development' +Tags: + - 'Android' + - 'Arrays' + - 'ForEach' + - 'Kotlin' +CatalogContent: + - 'learn-kotlin' + - 'paths/computer-science' +--- + +In Kotlin, the **`.forEach()`** method iterates over elements in a collection ([array](https://www.codecademy.com/resources/docs/kotlin/arrays), list, or [set](https://www.codecademy.com/resources/docs/kotlin/sets)) and performs the provided action on each element. It does not modify the original collection or return a new one, making it useful for operations with side effects like printing or logging. + +## Syntax + +```pseudo +fun Iterable.forEach(action: (T) -> Unit) +``` + +Or alternatively: + +```pseudo +fun Array.forEach(action: (T) -> Unit) +``` + +- `T`: The type of the elements in the collection (or array). +- `action`: A [function](https://www.codecademy.com/resources/docs/kotlin/functions) that takes an element of type `T` and performs an action on it. + +## Example + +The following example demonstrates the usage of the `.forEach()` method: + +```kotlin +fun main() { + // Initialize an array of numbers + val numbers = arrayOf(4, 12, 14, 17, 8) + + // Use .forEach() to print each element multiplied by 2 + numbers.forEach { println(it * 2) } +} +``` + +The above code generates the following output: + +```shell +8 +24 +28 +34 +16 +``` diff --git a/content/kotlin/concepts/arrays/terms/map/map.md b/content/kotlin/concepts/arrays/terms/map/map.md new file mode 100644 index 00000000000..5f3c95be2b7 --- /dev/null +++ b/content/kotlin/concepts/arrays/terms/map/map.md @@ -0,0 +1,58 @@ +--- +Title: '.map()' +Description: 'Transforms elements in a collection by applying a specified transformation function, resulting in a new collection with the transformed values.' +Subjects: + - 'Code Foundations' + - 'Mobile Development' +Tags: + - 'Android' + - 'Arrays' + - 'Map' + - 'Kotlin' +CatalogContent: + - 'learn-kotlin' + - 'paths/computer-science' +--- + +In Kotlin, the **`.map()`** method transforms elements in a collection (Array, List, or Set) using the provided logic. It does not modify the original collection, ensuring data permanence, which can be useful in scenarios where the original data must remain unchanged. + +## Syntax + +```pseudo +fun Iterable.map(transform: (T) -> R): List +``` + +Or alternatively: + +```pseudo +fun Array.map(transform: (T) -> R): List +``` + +- `T`: The type of the elements in the original collection (or array). +- `R`: The type of the elements in the resulting list after transformation. +- `transform`: A function that takes an element of type `T` and returns a transformed value of type `R`. + +It returns a `List` containing the transformed elements. + +## Example + +The following example uses the `.map()` function: + +```kotlin +fun main() { + // Initialize an Array of numbers. + val numbers = arrayOf(4, 12, 14, 17, 8) + + // Use .map() to multiply each element by 2 + val doubledNumbers = numbers.map { it * 2 } // Transforms each element by multiplying it by 2 + + // Print the transformed array + println(doubledNumbers) +} +``` + +The code above generates the following output: + +```shell +[8, 24, 28, 34, 16] +``` diff --git a/content/lua/concepts/tables/terms/remove/remove.md b/content/lua/concepts/tables/terms/remove/remove.md index a28f743c670..c7b2653ef43 100644 --- a/content/lua/concepts/tables/terms/remove/remove.md +++ b/content/lua/concepts/tables/terms/remove/remove.md @@ -1,6 +1,6 @@ --- -Title: 'remove()' -Description: 'Removes a value from a table.' +Title: '.remove()' +Description: 'Removes and returns the element at a specified position from a table (array).' Subjects: - 'Computer Science' - 'Game Development' @@ -12,20 +12,19 @@ CatalogContent: - 'paths/computer-science' --- -The **`remove()`** function in Lua removes the value of the specified index and clears the index from the table (reducing the length of the table by 1). +The **`.remove()`** function in Lua removes the value of the specified index and clears the index from the table (reducing the length of the table by 1). ## Syntax ```pseudo -table.remove(tableName,pos) - +table.remove(tableName, pos) ``` -`remove()` returns the value that was removed from the `tableName`. The `pos` parameter has a default value of `n`, which is the length of the table. This causes the last element of the table to be removed if the `pos` parameter is not provided. +The `.remove()` method removes and returns the element at the specified position `pos` from the given table `tableName`. If `pos` is not provided, it defaults to the length of the table, meaning the last element will be removed by default. ## Example -In the following example `remove()` is used to remove the element at the `pos` position from the table. This causes other elements to shift down. +In the following example `.remove()` is used to remove the element at the `pos` position from the table. This causes other elements to shift down: ```lua local fruit = { @@ -50,3 +49,5 @@ This example results in the following output: 🍎, 🍇, 🍓, 🍉 ``` + +> **Note:** In Lua, indices start from 1. Therefore the banana was removed from the table as it was at index 2. diff --git a/content/mysql/concepts/built-in-functions/terms/unhex/unhex.md b/content/mysql/concepts/built-in-functions/terms/unhex/unhex.md new file mode 100644 index 00000000000..3d9cda18139 --- /dev/null +++ b/content/mysql/concepts/built-in-functions/terms/unhex/unhex.md @@ -0,0 +1,48 @@ +--- +Title: 'UNHEX()' +Description: 'Converts a hexadecimal string to its corresponding binary string.' +Subjects: + - 'Computer Science' + - 'Code Foundations' +Tags: + - 'Functions' + - 'Database' + - 'MySQL' + - 'Strings' +CatalogContent: + - 'learn-sql' + - 'paths/analyze-data-with-sql' +--- + +The **`UNHEX()`** [function](https://www.codecademy.com/resources/docs/mysql/built-in-functions) is a build-in function in MySQL that converts a hexadecimal string to its corresponding binary string. Useful when we have data stored in hexadecimal format we can use `UNHEX()` function to convert it to the original binary form making it usable and understandable. + +## Syntax + +```pseudo +UNHEX(val); +``` + +- `val`: A hexadecimal string to be converted to its corresponding binary form. + +## Example + +The below example shows how `UNHEX()` function works. + +```sql +CREATE TABLE documents ( + id INT PRIMARY KEY, + content BLOB +); + +INSERT INTO documents (id, content) VALUES (1, UNHEX('636F6465636164656D79')); + +SELECT HEX(content) AS 'hex-content', CAST(content AS CHAR) AS readable_content +FROM documents +WHERE id = 1; +``` + +The output of the above code will be: + +| hex-content | readable-content | +| -------------------- | ---------------- | +| 636F6465636164656D79 | codecademy | diff --git a/content/numpy/concepts/built-in-functions/terms/append/append.md b/content/numpy/concepts/built-in-functions/terms/append/append.md index 20069ca8e0a..ae1bc35378d 100644 --- a/content/numpy/concepts/built-in-functions/terms/append/append.md +++ b/content/numpy/concepts/built-in-functions/terms/append/append.md @@ -52,3 +52,26 @@ This produces the following output: [4 5 6] [7 8 9]] ``` + +## Codebyte Example + +The following example creates two arrays and demonstrates appending them using `.append()`, both without specifying an axis (resulting in a 1D array) and along specified axes (rows and columns): + +```codebyte/python +import numpy as np + +nd1 = np.array([[0,0,0,0], [1,1,1,1]]) +print("First array: \n", nd1) + +nd2 = np.arange(8).reshape(2, 4) +print("Second array: \n", nd2) + +nd3 = np.append(nd1, nd2) +print("Appended array with no axis specified:\n", nd3); + +nd4 = np.append(nd1, nd2, axis = 0) +print("Appended array on axis 0:\n", nd4); + +nd5 = np.append(nd1, nd2, axis = 1) +print("Appended array on axis 1:\n", nd5); +``` diff --git a/content/numpy/concepts/built-in-functions/terms/linspace/linspace.md b/content/numpy/concepts/built-in-functions/terms/linspace/linspace.md index f35abefeb96..23547d2134d 100644 --- a/content/numpy/concepts/built-in-functions/terms/linspace/linspace.md +++ b/content/numpy/concepts/built-in-functions/terms/linspace/linspace.md @@ -66,3 +66,22 @@ This results in the following output: [3.4 4.4 5.4] [4. 5. 6. ]] ``` + +## Codebyte Example + +Run the following codebyte example to understand the usage of the `linspace()` function with different inputs and parameters: + +```codebyte/python +import numpy as np + +result, step_size = np.linspace(0, 20, num=5, retstep=True) +print("Resulting array: ", result) +print("Step size: ", step_size) + +result2, step_size2 = np.linspace(0, 20, num=5, endpoint=False, retstep=True) +print("Resulting array (without endpoint): ", result2) +print("Step size: ", step_size2) + +result3 = np.linspace([0, 10], [20, 100], num=8, axis=1) +print(result3) +``` diff --git a/content/numpy/concepts/built-in-functions/terms/log/log.md b/content/numpy/concepts/built-in-functions/terms/log/log.md index db91946a5a9..186587c3858 100644 --- a/content/numpy/concepts/built-in-functions/terms/log/log.md +++ b/content/numpy/concepts/built-in-functions/terms/log/log.md @@ -15,7 +15,7 @@ CatalogContent: - 'paths/data-science' --- -The `.log()` function returns an element-wise natural logarithm of an array. +The **`.log()`** function returns an element-wise natural logarithm of an array. ## Syntax @@ -47,3 +47,32 @@ This produces the following output: [[0. 0.99999933] [0.99999933 0. ]] ``` + +## Codebyte Example + +The following codebyte creates different arrays and demonstrates applying `np.log()` to each array, calculating the natural logarithm of all elements: + +```codebyte/python +import numpy as np + +# Create an array containing a single element +single_element_array = np.array([10]) +print("Single element array:") +print(single_element_array) +print("Log of single element array:") +print(np.log(single_element_array)) + +# Create an array containing multiple elements +multiple_elements_array = np.array([1, 10, 100]) +print("\nMultiple elements array:") +print(multiple_elements_array) +print("Log of multiple elements array:") +print(np.log(multiple_elements_array)) + +# Create an array having more than 1 dimension +higher_dimensional_array = np.array([[1, 2], [3, 4]]) +print("\nHigher-dimensional array:") +print(higher_dimensional_array) +print("Log of higher-dimensional array:") +print(np.log(higher_dimensional_array)) +``` diff --git a/content/numpy/concepts/built-in-functions/terms/reshape/reshape.md b/content/numpy/concepts/built-in-functions/terms/reshape/reshape.md index 61104d272df..94518ec2295 100644 --- a/content/numpy/concepts/built-in-functions/terms/reshape/reshape.md +++ b/content/numpy/concepts/built-in-functions/terms/reshape/reshape.md @@ -1,6 +1,6 @@ --- Title: '.reshape()' -Description: 'Rearranges the data of an ndarray into a new shape.' +Description: 'Rearranges the data of a ndarray into a new shape.' Subjects: - 'Computer Science' - 'Data Science' @@ -20,16 +20,23 @@ The `.reshape()` function rearranges the data in an [`ndarray`](https://www.code ## Syntax ```pseudo -numpy.reshape(array, newshape) +numpy.reshape(array, newshape, order = 'C') ``` -Where `array` is the array to be reshaped, and `newshape` can be an integer or a [`tuple`](https://www.codecademy.com/resources/docs/python/tuples) representing the size of the new array. If a dimension is `-1`, that dimension will be inferred from the size of the original array. +- `array`: The input array to be reshaped. +- `newshape`: An integer or a [`tuple`](https://www.codecademy.com/resources/docs/python/tuples) representing the desired shape of the new array. If one dimension is set to -1, that dimension will be inferred based on the size of the original array. +- `order`: Specifies how elements should be read from the original array and placed into the reshaped array. It can be set to `'C'`, `'F'`, or `'A'`: + - `C`: Read/write elements in row-major order (C-like), where the last axis (columns) changes fastest, and the first axis (rows) changes slowest. The elements are placed row by row. + - `F`: Read/write elements in column-major order (Fortran-like), where the first axis (rows) changes fastest, and the last axis (columns) changes slowest. The elements are placed column by column. + - `A`: Use Fortran-like index order if the array is Fortran contiguous in memory (i.e., stored sequentially without gaps), or C-like order otherwise. -If possible, the `ndarray` returned will be a view of the original `ndarray`'s data. +Using `'C'` or `'F'` in `.reshape()` affects the indexing order but does not alter the physical layout of the data in memory. + +If possible, the `ndarray` returned will be a view of the data from the original `ndarray`. ## Example -The following example creates an `ndarray` then uses `.reshape()` to change its dimensions. +The following example creates an `ndarray` then uses `.reshape()` to change its dimensions: ```py import numpy as np @@ -58,3 +65,17 @@ This produces the following output: [5] [6]] ``` + +## Codebyte Example + +The following example creates a `ndarray` and then uses `order` as an optional parameter for `.reshape()` to change its dimensions: + +```codebyte/python +import numpy as np + +nd1 = np.array([[10, 20, 30], [40, 50, 60]]) + +print(nd1) +print(np.reshape(nd1, (3, 2), order='C')) +print(np.reshape(nd1, (3, 2), order='F')) +``` diff --git a/content/numpy/concepts/built-in-functions/terms/transpose/transpose.md b/content/numpy/concepts/built-in-functions/terms/transpose/transpose.md index 5438d324ebf..698658f0516 100644 --- a/content/numpy/concepts/built-in-functions/terms/transpose/transpose.md +++ b/content/numpy/concepts/built-in-functions/terms/transpose/transpose.md @@ -29,7 +29,7 @@ If possible, the `ndarray` returned will be a view of the original `ndarray`'s d ## Example -The below example creates an `ndarray` and then uses `.transpose()` on it. +The below example creates an `ndarray` and then uses `.transpose()` on it: ```py import numpy as np @@ -50,3 +50,16 @@ This produces the following output: [2 5] [3 6]] ``` + +## Codebyte Example + +The `axes` argument allows control over the specific reordering of dimensions in a tensor. Run the below codebyte example to see how `.transpose()` can be used to rearrange the three dimensions of a 3D array: + +```codebyte/python +import numpy as np + +array_3d = np.array([[[1, 2], [3, 4]], [[5, 6], [7, 8]]]) + +print(array_3d) +print(np.transpose(array_3d)) +``` diff --git a/content/numpy/concepts/built-in-functions/terms/variance/variance.md b/content/numpy/concepts/built-in-functions/terms/variance/variance.md index b3180104153..a7bcf26bb1b 100644 --- a/content/numpy/concepts/built-in-functions/terms/variance/variance.md +++ b/content/numpy/concepts/built-in-functions/terms/variance/variance.md @@ -58,3 +58,26 @@ This produces the following output: [6. 6. 6.] [0.66666667 0.66666667 0.66666667] ``` + +## Codebyte Example + +The following codebyte example demonstrates how to calculate the variance of a 2D array: + +```codebyte/python +import numpy as np + +# Creating a 2D array +arr = [[2, 2, 2, 2, 2], +[15, 6, 27, 8, 2], +[23, 2, 54, 1, 2, ], +[11, 44, 34, 7, 2]] + +# Calculating the variance of the flattened array +print("\nvar of arr, axis = None : ", np.var(arr)) + +# Calculating the variance along axis = 0 +print("\nvar of arr, axis = 0 : ", np.var(arr, axis = 0)) + +# Calculating the variance along axis = 1 +print("\nvar of arr, axis = 1 : ", np.var(arr, axis = 1)) +``` diff --git a/content/numpy/concepts/math-methods/terms/floor/floor.md b/content/numpy/concepts/math-methods/terms/floor/floor.md new file mode 100644 index 00000000000..3c3a57afc57 --- /dev/null +++ b/content/numpy/concepts/math-methods/terms/floor/floor.md @@ -0,0 +1,75 @@ +--- +Title: '.floor()' +Description: 'Rounds down a number or an array of numbers to the nearest smallest integer.' +Subjects: + - 'Computer Science' + - 'Data Science' +Tags: + - 'Arrays' + - 'Math' + - 'NumPy' +CatalogContent: + - 'learn-python-3' + - 'paths/computer-science' +--- + +In the NumPy library, the **`.floor()`** method rounds down a number or an array of numbers to the nearest smallest integer. It returns an array without commas separating the elements. To view the output with commas, use the [`.repr()`](https://www.codecademy.com/resources/docs/python/built-in-functions/repr) function. + +## Syntax + +```psuedo +numpy.floor(array, out=None) +``` + +- `array`: Represents a single number or an array of numbers. Each element, whether a float or integer, will be rounded down. +- `out` (Optional): An output array where the rounded results will be stored. A new array will be created to store the rounded-down values if not provided. + +## Example + +The below example shows different use cases of the `.floor()` method: + +```py +import numpy as np + +# Case 1: np.floor() returns a single number rounded down. +number = 5.64 +rounded_number = np.floor(number) +print("# Case 1") +print(rounded_number) + +# Case 2: np.floor() accepts arrays as a parameter and will return the elements of the array rounded down. +array_unrounded = [4.734, 3.141, 9.567] +array_rounded = np.floor(array_unrounded) +print("# Case 2") +print(array_rounded) + +# Case 3: np.floor() accept arrays as a second parameter and will store the round down values in it. +array_unrounded = [2.5, 1.5, 3.55] +array_rounded = np.zeros_like(array_unrounded) +np.floor(array_unrounded, out=array_rounded) +print("# Case 3") +print(array_rounded) +``` + +The above use cases produce the following output: + +```shell +# Case 1 +5.0 +# Case 2 +[4. 3. 9.] +# Case 3 +[2. 1. 3.] +``` + +## Codebyte Example + +Run the following codebyte example to understand how the `.floor()` method works: + +```codebyte/python +import numpy as np + +unrounded_list = [23.89, 54.843, 17.478] +rounded_list = np.floor(unrounded_list) +print(rounded_list) +``` diff --git a/content/numpy/concepts/math-methods/terms/nanprod/nanprod.md b/content/numpy/concepts/math-methods/terms/nanprod/nanprod.md new file mode 100644 index 00000000000..95e24254eac --- /dev/null +++ b/content/numpy/concepts/math-methods/terms/nanprod/nanprod.md @@ -0,0 +1,90 @@ +--- +Title: '.nanprod()' +Description: 'Calculates the product of array elements.' +Subjects: + - 'Computer Science' + - 'Data Science' +Tags: + - 'Arrays' + - 'Functions' + - 'Math' + - 'NumPy' +CatalogContent: + - 'learn-python-3' + - 'paths/computer-science' +--- + +In NumPy, the **`.nanprod()`** function calculates the product of array elements over a specified axis, treating `NaN` (Not a Number) values as 1. This is useful when working with arrays that contain missing or undefined values represented as `NaN`. + +## Syntax + +```pseudo +numpy.nanprod(a, axis=None, dtype=None, out=None, keepdims=) +``` + +- `a`: An array for which the product is calculated. +- `axis`: An optional parameter used to specify the axis along which the product is computed. If not specified, the product of all elements in the array is calculated. +- `dtype` : An optional parameter used to specify the data type of the result. If not specified, it defaults to the data type of the input array, or the default platform integer if the input contains integers. +- `out`: An optional parameter specifying the array to store the result. If not provided, a new array is created. +- `keepdims`: An optional parameter. If set to `True`, the reduced axes are retained in the result as dimensions with size one, allowing the result to broadcast correctly. + +## Example 1 + +This example demonstrates using `.nanprod()` function to calculate the product of an array containing `NaN` values: + +```py +import numpy as np + +# Creating a numpy array with NaN values +arr = np.array([1, 2, np.nan, 4, 5]) + +# Computing the product of the array, treating NaN as 1 +result = np.nanprod(arr) + +print(result) +``` + +The above example code results in the following output: + +```shell +40.0 +``` + +## Example 2 + +This example shows how to use `.nanprod()` function along a specific axis: + +```py +import numpy as np + +# Creating a 2D numpy array with NaN values +arr = np.array([[1, 2, np.nan], [4, 5, 6]]) + +# Computing the product along axis 0 (columns) +result = np.nanprod(arr, axis=0) + +print(result) +``` + +The above example code results in the following output: + +```shell +[4. 10. 6.] +``` + +## Codebyte Example + +In this codebyte example, the `.nanprod()` method computes the product of the elements in the array along both axes, demonstrating the use of the `keepdims` parameter: + +```codebyte/python +import numpy as np + +arr = np.array([[1, 2, np.nan], [4, np.nan, 6], [7, 8, 9]]) + +result = np.nanprod(arr, axis=(0, 1), keepdims=True) + +print("Original array:") +print(arr) +print("\nResult:") +print(result) +``` diff --git a/content/numpy/concepts/math-methods/terms/unwrap/unwrap.md b/content/numpy/concepts/math-methods/terms/unwrap/unwrap.md new file mode 100644 index 00000000000..baee6b179ce --- /dev/null +++ b/content/numpy/concepts/math-methods/terms/unwrap/unwrap.md @@ -0,0 +1,90 @@ +--- +Title: '.unwrap()' +Description: 'Unwraps a phase angle array by changing deltas greater than a threshold to their 2*pi complement.' +Subjects: + - 'Computer Science' + - 'Data Science' +Tags: + - 'Arrays' + - 'Functions' + - 'Math' + - 'NumPy' +CatalogContent: + - 'learn-python-3' + - 'paths/computer-science' +--- + +In NumPy, the **`.unwrap()`** function is used to unwrap a phase angle array. This function adjusts the phase angles by changing any absolute difference between consecutive angles greater than the specified threshold (default: `pi`) by their `2*pi` complement. It is commonly used in signal processing to correct phase angle discontinuities in wrapped data. + +## Syntax + +```pseudo +numpy.unwrap(p, discont=pi, axis=-1, period=6.283185307179586) +``` + +- `p`: The input array of phase angles to be unwrapped. +- `discont` (optional): The discontinuity threshold, which defaults to `pi`. Differences greater than this value will be adjusted by adding or subtracting multiples of `2*pi`. +- `axis` (optional): The axis along which the unwrap operation is applied. Default is the last axis `-1`. +- `period` (optional): The period of the phase angles. Default is `2*pi`, but it can be set to other values to adjust for different periodicities. + +## Example 1 + +This example demonstrates how to use the `.unwrap()` function to correct phase discontinuities in an array of wrapped phase angles. + +```py +# Importing the 'numpy' library as 'np' +import numpy as np + +# Creating an array of phase angles with discontinuities +angles = np.array([0, np.pi/2, np.pi, -np.pi/2, -np.pi]) + +# Applying the unwrap function to correct discontinuities +unwrapped = np.unwrap(angles) + +print(unwrapped) +``` + +The above example code results in the following output: + +```shell +[0. 1.57079633 3.14159265 4.71238898 3.14159265] +``` + +> **Note:** NumPy outputs phase angles with high precision. For clarity, these examples use rounded values. + +## Example 2 + +This example shows how to adjust the discontinuity threshold by setting a custom discont value in `.unwrap()`: + +```py +# Importing the 'numpy' library as 'np' +import numpy as np + +# Creating an array of phase angles with large discontinuities +angles = np.array([0, np.pi/2, np.pi, 3*np.pi, -np.pi/2]) + +# Unwrapping with a custom discontinuity threshold of 2*pi +unwrapped = np.unwrap(angles, discont=2*np.pi) + +print(unwrapped) +``` + +The above example code results in the following output: + +```shell +[0. 1.57079633 3.14159265 3.14159265 4.71238898] +``` + +## Codebyte Example + +In this Codebyte example, the `.unwrap()` method corrects discontinuities in an array of phase angles: + +```codebyte/python +import numpy as np + +angles = np.array([0, np.pi, 2*np.pi, -np.pi]) + +unwrapped = np.unwrap(angles) + +print(unwrapped) +``` diff --git a/content/numpy/concepts/ndarray/terms/reshape/reshape.md b/content/numpy/concepts/ndarray/terms/reshape/reshape.md index ab3f2a0594e..e8ebea4bc35 100644 --- a/content/numpy/concepts/ndarray/terms/reshape/reshape.md +++ b/content/numpy/concepts/ndarray/terms/reshape/reshape.md @@ -60,3 +60,16 @@ This produces the following output: [5] [6]] ``` + +## Codebyte Example + +Run the following codebyte example to understand the usage of the `.reshape()` method: + +```codebyte/python +import numpy as np + +arr = np.array([1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12]) +new_arr = arr.reshape(4, 3) + +print(new_arr) +``` diff --git a/content/plotly/concepts/express/terms/funnel/funnel.md b/content/plotly/concepts/express/terms/funnel/funnel.md new file mode 100644 index 00000000000..e73be5759ce --- /dev/null +++ b/content/plotly/concepts/express/terms/funnel/funnel.md @@ -0,0 +1,90 @@ +--- +Title: '.funnel()' +Description: 'Generates a funnel chart that visualizes the reduction of data in progressive stages.' +Subjects: + - 'Computer Science' + - 'Data Science' +Tags: + - 'Data' + - 'Graphs' + - 'Libraries' + - 'Methods' + - 'Plotly' +CatalogContent: + - 'learn-python-3' + - 'paths/computer-science' +--- + +The **`.funnel()`** method in Plotly Express creates a funnel chart, which visualizes the progressive reduction of data as it moves through sequential stages. The chart is composed of stacked horizontal bars, with each bar's length representing a value at a specific stage. This helps highlight changes, bottlenecks, or drop-offs in the process. + +## Syntax + +```pseudo +plotly.express.funnel(data_frame=None, x=None, y=None, color=None, facet_row=None, facet_col=None, ...) +``` + +- `data_frame`: The dataset (typically a [Pandas DataFrame](https://www.codecademy.com/resources/docs/pandas/dataframe)) to be plotted. If this is not provided, Plotly Express will construct a DataFrame using the other arguments. +- `x`: The column in the DataFrame that specifies the values to determine the length of the bars, plotted along the x-axis. +- `y`: The column in the DataFrame that represents the stages of the funnel, plotted along the y-axis. +- `color`: The column in the DataFrame that assigns colors to the bars of the funnel. +- `facet_row`: Splits the funnel chart into vertically-stacked subplots based on a specified column from the DataFrame. +- `facet_col`: Splits the funnel chart into horizontally-arranged subplots based on a specified column from the DataFrame. + +> **Note:** The ellipsis (...) indicates there can be additional optional parameters beyond those listed here. + +## Example 1 + +The example below generates a funnel chart representing the job search process for an applicant: + +```py +import plotly.express as px +import pandas as pd + +# Create sample dictionary +data = { + 'Stage': ['Applications Sent', 'Phone Interview', 'Technical Interview', 'Onsite Interview', 'Offers Received', 'Offers Accepted'], + 'Job Applications': [500, 348, 92, 56, 10, 1] +} + +# Convert the dictionary into a DataFrame +df = pd.DataFrame(data) + +# Create the funnel chart with title "Job Search" +fig = px.funnel(df, x='Job Applications', y='Stage', title='Job Search') + +# Show the chart +fig.show() +``` + +The above example produces the following output: + +![Funnel Chart Illustrating Job Search](https://raw.githubusercontent.com/Codecademy/docs/main/media/plotly-express-funnel-example1.png) + +## Example 2 + +As a variation of the previous example, this example adds subplots using the `facet_col` parameter to compare two different job applicants side by side: + +```py +import plotly.express as px +import pandas as pd + +# Create sample dictionary +data = { + 'Stage': ['Applications Sent', 'Phone Interview', 'Technical Interview', 'Onsite Interview', 'Offers Received', 'Offers Accepted'] * 2, + 'Job Applications': [500, 348, 92, 56, 10, 1, 500, 329, 290, 225, 167, 1], + 'Applicants': ['Candidate 1'] * 6 + ['Candidate 2'] * 6 +} + +# Convert the dictionary into a DataFrame +df = pd.DataFrame(data) + +# Create the funnel chart with title "Job Search Comparison" +fig = px.funnel(df, x='Job Applications', y='Stage', facet_col='Applicants', title='Job Search Comparison') + +# Show the chart +fig.show() +``` + +The above code will result in the following output: + +![Funnel Chart Comparing Two Applicants](https://raw.githubusercontent.com/Codecademy/docs/main/media/plotly-express-funnel-example2.png) diff --git a/content/plotly/concepts/express/terms/scatter-3d/scatter-3d.md b/content/plotly/concepts/express/terms/scatter-3d/scatter-3d.md new file mode 100644 index 00000000000..22bdcd8e491 --- /dev/null +++ b/content/plotly/concepts/express/terms/scatter-3d/scatter-3d.md @@ -0,0 +1,85 @@ +--- +Title: '.scatter_3d()' +Description: 'Creates a 3D scatter plot to visualize data points across three dimensions (x, y, z) with options for color, size, and hover data.' +Subjects: + - 'Data Science' + - 'Data Visualization' +Tags: + - 'Graphs' + - 'Libraries' + - 'Plotly' + - 'Data' +CatalogContent: + - 'learn-python-3' + - 'paths/computer-science' +--- + +The **`.scatter_3d()`** method in the `plotly.express` module creates a 3D scatter plot to visualize the relationships between three variables using markers in a three-dimensional space. The data points are plotted based on their values on the `x`, `y`, and `z` axes. It also allows customizing marker colors, sizes, and symbols. + +## Syntax + +The `x`, `y`, and `z` parameters are required and accept values as a string, integer, `Series`, or array-like object, representing the data for each axis. Optional parameters, such as `color`, `symbol`, and `size`, customize the markers' appearance. If `data_frame` is not provided, a `DataFrame` will be constructed from other arguments. + +```pseudo +plotly.express.scatter_3d(data_frame=None, x=None, y=None, z=None, color=None, symbol=None, size=None, ...) +``` + +- `data_frame`: The Pandas [`DataFrame`](https://www.codecademy.com/resources/docs/pandas/dataframe) containing the data to visualize. +- `x`: The column name in `data_frame`, `Series`, or array-like object for x-axis data. +- `y`: The column name in `data_frame`, `Series`, or array-like object for y-axis data. +- `z`: The column name in `data_frame`, `Series`, or array-like object for z-axis data. +- `color`: The column name in `data_frame`, `Series`, or array-like object to specify marker colors. +- `symbol`: The column name in `data_frame`, `Series`, or array-like object for assigning marker symbols. +- `size`: The column name in `data_frame`, `Series`, or array-like object to assign marker sizes. + +> **Note:** The ellipsis in the syntax (...) indicates additional optional parameters that can be used to customize the plot further. + +## Examples + +The examples below demonstrate how the [`.scatter()`](https://www.codecademy.com/resources/docs/plotly/express/scatter) method creates a 2D scatter plot, while the `.scatter_3d()` method provides a more complex visualization in three dimensions, utilizing additional parameters for color and symbol customization. + +### Example 1 + +The following example demonstrates the use of the `.scatter()` method: + +```py +# Defining 'x' and 'y' as array-like objects +import plotly.express as px +x = [1, 3, 5, 7, 9] +y = [4, 6, 5, 8, 2] + +# Creating a scatter plot +fig = px.scatter(x = x, y = y) + +# Displaying the plot +fig.show() +``` + +The output for the above code is as follows: + +![The output for the above example](https://raw.githubusercontent.com/Codecademy/docs/main/media/plotlyScatter3dOutput1.png) + +### Example 2 + +This example illustrates the use of the `.scatter_3d()` method, showcasing its capability to utilize more parameters for enhanced visualization: + +```py +import plotly.express as px + +# Sample Data +x = [1, 3, 5, 7, 9] +y = [4, 6, 5, 8, 2] +z = [7, 2, 9, 4, 8] +color = ['red', 'green', 'blue', 'purple', 'orange'] +symbol = ['circle', 'square', 'diamond', 'star', 'triangle-up'] + +# Creating a 3D scatter plot +fig = px.scatter_3d(x=x, y=y, z=z, color=color, symbol=symbol, title="3D Scatter Plot with Colors and Symbols") + +# Displaying the plot +fig.show() +``` + +The above code produces the following output: + +![The output for the above example](https://raw.githubusercontent.com/Codecademy/docs/main/media/plotlyScatter3dOutput2.png) diff --git a/content/plotly/concepts/graph-objects/terms/surface/surface.md b/content/plotly/concepts/graph-objects/terms/surface/surface.md new file mode 100644 index 00000000000..f32f464a03e --- /dev/null +++ b/content/plotly/concepts/graph-objects/terms/surface/surface.md @@ -0,0 +1,70 @@ +--- +Title: '.Surface()' +Description: 'Creates a 3d plot using the `Surface` class of the `graph_objects` module in Plotly' +Subjects: + - 'Data Science' + - 'Data Visualization' +Tags: + - 'Plotly' + - 'Graphs' + - 'Data' + - 'Values' +CatalogContent: + - 'learn-python-3' + - 'paths/computer-science' +--- + +The **`Surface`** class creates a 3D surface plot using Plotly's `graph_objects` module. It allows for the visualization of data in three dimensions. This class enables the rendering of surfaces defined by `x`, `y`, and `z` coordinates, and can be customized with various parameters like colors, scales, and more to represent complex datasets. + +## Syntax + +```pseudo +plotly.graph_objects.Surface( + z=None, # 2D array-like, required. + x=None, # 1D array-like, optional. + y=None, # 1D array-like, optional. + colorscale=None, # list of tuples or named color scale, optional. + cmin=None, # float, optional. + cmax=None, # float, optional. + opacity=None, # float between 0 and 1, optional. + surfacecolor=None, # 2D array-like, optional. + **kwargs +) +``` + +- `z`: It defines the surface's `Z` coordinates (height/depth). +- `x`: It represents the `X` coordinates. If not provided, it defaults to the range of the number of columns in `z`. +- `y`: It represents the `Y` coordinates. If not provided, it defaults to the range of the number of rows in `z`. +- `colorscale`: Can be a named colour scale (e.g., `'Viridis'`) or a list of tuples that define custom colour mapping (optional). +- `cmin`: Minimum value of the colorscale range (optional). +- `cmax`: Maximum value of the colorscale range (optional). +- `opacity`: A float between 0 (completely transparent) and 1 (fully opaque), defining surface opacity (optional). +- `surfacecolor`: A 2D array of values used to colour the surface independent of the Z axis (optional). + +## Example + +This code creates a 3D surface plot using Plotly's `Surface` class from the `graph_objects` module. It defines a mathematical function $f(x, y) = x^2 + y^2$, where `x` and `y` form a mesh grid, and `z` represents the height of the surface: + +```py +import plotly.graph_objects as go +import numpy as np + +x = np.linspace(-5, 5, 50) +y = np.linspace(-5, 5, 50) +x, y = np.meshgrid(x, y) +z = x**2 + y**2 + +fig = go.Figure(data=[go.Surface(z=z, x=x, y=y)]) + +fig.update_layout(title='3D Surface Plot of f(x, y) = x^2 + y^2', + scene=dict( + xaxis_title='X', + yaxis_title='Y', + zaxis_title='f(x, y)' + )) +fig.show() +``` + +The above code generates the following output: + +![Output from above code](https://raw.githubusercontent.com/Codecademy/docs/main/media/3d-surface-example-plotly.png) diff --git a/content/postgresql/concepts/transactions/transactions.md b/content/postgresql/concepts/transactions/transactions.md new file mode 100644 index 00000000000..ae3e067d241 --- /dev/null +++ b/content/postgresql/concepts/transactions/transactions.md @@ -0,0 +1,127 @@ +--- +Title: 'Transactions' +Description: 'Transactions bundle one or more steps into a single unit of work; an all-or-nothing operation where all statements succeed or all statements fail.' +Subjects: + - 'Computer Science' + - 'Data Science' +Tags: + - 'PostgreSQL' + - 'Database' + - 'Finance' + - 'Data' +CatalogContent: + - 'paths/data-science' + - 'paths/data-science-foundations' +--- + +**Transactions** are a fundamental concept in PostgreSQL that bundles one or more steps into a single unit of work. It is an all-or-nothing operation where all statements succeed or all statements fail. The intermediate states between the steps are not visible to other concurrent transactions and if a failure occurs that prevents the transaction from completing, it does not affect the database. + +Examples for when to use transactions would be in finance, such as a bank database that contains balances for various customer accounts and total deposit balances for branches. Transactions are fundamental for maintaining the accuracy and reliability of the records in a database. + +## Syntax + +There are three main commands in a transaction. These are `BEGIN`, `COMMIT`, and `ROLLBACK`. + +`BEGIN` starts a transaction block: + +```pseudo +BEGIN; +``` + +Even if a `BEGIN` command is _not_ issued, each individual statement has an implicit `BEGIN`. If successful, it will have a `COMMIT` wrapped around it. + +`COMMIT` permanently saves the changes made within the transaction block to the database: + +```pseudo +COMMIT; +``` + +`ROLLBACK` is used to undo a transaction. It cancels all changes made in the current transaction block. This can also be used if partway through the transaction, there is no need to commit these changes: + +```pseudo +ROLLBACK; +``` + +Putting it all together, here is the general syntax for the three commands: + +```pseudo +BEGIN; +-- Set of statements +COMMIT; +``` + +Or, + +```pseudo +BEGIN; +-- Set of statements +ROLLBACK; +``` + +## Example 1 + +A customer named Alice has an initial balance of $500.00 in her bank account. Here is an example that demonstrates the usage of a transaction block using the `BEGIN` and `COMMIT` commands: + +```sql +BEGIN; +UPDATE accounts SET balance = balance - 100.00 + WHERE name = 'Alice'; +-- Set of statements +COMMIT; +``` + +After the transaction, $100 has been deducted from Alice's balance. To verify Alice's updated balance, a query is run on the `accounts` table: + +```sql +SELECT balance FROM accounts WHERE name = 'Alice'; +``` + +Here is the output: + +```shell +400.00 +``` + +## Example 2 + +Customers Alice, Bob, and Carol each start with $500.00 in their bank accounts. + +To have more control over statements in a transaction, the `SAVEPOINT` command can be used, which allows a savepoint to be defined. After defining a savepoint, if needed, the transaction can be rolled back to the savepoint with the `ROLLBACK TO` command. + +Here is an example that demonstrates the usage of a transaction block, implementing the `SAVEPOINT` and `ROLLBACK TO` commands, giving more control over the statements within the transaction block: + +```sql +BEGIN; +UPDATE accounts SET balance = balance - 100.00 + WHERE name = 'Alice'; +-- Output: Alice's account was deducted by 100.00 and now has 400.00 +-- Add a savepoint for Alice's account +SAVEPOINT my_savepoint; +UPDATE accounts SET balance = balance + 100.00 + WHERE name = 'Bob'; +-- Output: Bob's account was increased by 100.00 and now Bob has 600.00 +-- Oops... this wasn't for Bob, use Carol's account +ROLLBACK TO my_savepoint; +-- No Output: Bob's account reverts back to 500.00 +UPDATE accounts SET balance = balance + 100.00 + WHERE name = 'Carol'; + -- Output: Carol's account was increased by 100.00 and now Carol has 600.00 +COMMIT; +``` + +To verify the balances after the transaction, the `accounts` table is queried: + +```sql +SELECT balance FROM accounts WHERE name = 'Alice'; +-- Output: 400.00 + +SELECT balance FROM accounts WHERE name = 'Bob'; +-- Output: 500.00 + +SELECT balance FROM accounts WHERE name = 'Carol'; +-- Output: 600.00 +``` + +Using the `SAVEPOINT` selectively discards parts of the transaction, while committing the rest. + +`ROLLBACK TO` prevents the need for rolling back the transaction completely and starting over. This means the database changes between `SAVEPOINT` and `ROLLBACK TO` are discarded, but earlier changes in the savepoint are kept. diff --git a/content/python/concepts/built-in-functions/built-in-functions.md b/content/python/concepts/built-in-functions/built-in-functions.md index 13c672c4301..cc24b35082d 100644 --- a/content/python/concepts/built-in-functions/built-in-functions.md +++ b/content/python/concepts/built-in-functions/built-in-functions.md @@ -1,6 +1,6 @@ --- Title: 'Built-in Functions' -Description: 'The Python interpreter has a set of functions and types built into it (pre-defined). They are always ready at your disposal; you can use them without needing to import a library. There are 68 built-in functions and they are listed here in alphabetical order.' +Description: 'Python includes over 60 pre-defined built-in functions and types, which can be used without importing libraries.' Subjects: - 'Computer Science' - 'Data Science' @@ -13,6 +13,27 @@ CatalogContent: - 'paths/computer-science' --- -The Python interpreter has a set of functions and types built into it (pre-defined). They are always ready at your disposal; you can use them without needing to import a library. +**Built-in functions** in Python are a collection of pre-defined functions readily available for use without requiring the import of any external libraries. These functions provide essential functionality for performing common tasks, such as manipulating data types, handling input/output, and more. Python includes over 60 built-in functions, which are categorized and listed alphabetically for easy reference. -There are 68 built-in functions and they are listed here in alphabetical order. +## Example + +The example below uses a built-in function `len()` that returns the length of an object: + +```py +# Creating a list of states +states = ["Idaho", "Kansas", "Louisiana"] + +# A string +text = "Hello, World!" + +# Calculating the length using len() +print(len(states)) +print(len(text)) +``` + +The output of the above code is as follows: + +```shell +3 +13 +``` diff --git a/content/python/concepts/built-in-functions/terms/hash/hash.md b/content/python/concepts/built-in-functions/terms/hash/hash.md index 83b616ee996..e57df598390 100644 --- a/content/python/concepts/built-in-functions/terms/hash/hash.md +++ b/content/python/concepts/built-in-functions/terms/hash/hash.md @@ -14,7 +14,7 @@ CatalogContent: - 'paths/computer-science' --- -The built-in **`hash()`** function returns the hash value of an object as a fixed sized integer. The object can be of various types, including numbers, strings, tuples, or custom objects that have implemented the `__hash__()` method. The hash value is computed using a specific hashing algorithm based on the object's type. It's worth noting that the `hash()` function is a built-in function in Python and doesn't require any import statements. Hash values are useful for efficient comparison of dictionary keys during lookups. +The built-in **`hash()`** function returns a fixed-size integer hash value for an object, such as numbers, strings, tuples, or custom objects implementing the `__hash__()` method. Using type-specific algorithms, it facilitates efficient dictionary key comparisons during lookups. It can be used directly without requiring any imports. ## Syntax @@ -28,11 +28,11 @@ The `object` can be of any hashable type, such as numbers, strings, tuples, or c ## Example -The example below begins by defining a class called `MyClass` with an attribute called value. The `__hash__()` method is implemented to customize the hashing behavior based on the value attribute using the `hash()` function. +The example below defines a class called `MyClass`, with an attribute called `value`. The `__hash__()` method is implemented to customize the hashing behavior based on the `value` attribute. -Two instances of `MyClass` `obj1` and `obj2`, are created with different values. The `hash()` function is used to calculate the hash values of these objects. And these values are then printed to the console. +Two instances of `MyClass`, `obj1` and `obj2`, are created with different values. The `hash()` function is used to calculate the hash values of these objects. These values are then printed to the console. -This example demonstrates how to customize the hash function for a class using the `__hash__()` method. The `hash()` function allows us to obtain the hash value of an object, which is an integer used for quick comparison and dictionary key lookups. +This example demonstrates how to customize the hash function for a custom class using the `__hash__()` method. ```py # Define a class @@ -54,7 +54,7 @@ print(hash(obj2)) ## Codebyte Example -In the example below, we define `my_tuple` as "1, 2, 3". Subsequently, we use the `hash()` function to obtain the hash value of the input `my_tuple`. Followed by a call to print the output of the `hash()` function. +In the example below, we define `my_tuple` as `(1, 2, 3)`. Subsequently, we use the `hash()` function to obtain the hash value of the input `my_tuple`. Then, we print the output of the `hash()` function. ```codebyte/python my_tuple = (1, 2, 3) diff --git a/content/python/concepts/comments/comments.md b/content/python/concepts/comments/comments.md index be6df4676a7..4cb243ddf7d 100644 --- a/content/python/concepts/comments/comments.md +++ b/content/python/concepts/comments/comments.md @@ -1,6 +1,6 @@ --- Title: 'Comments' -Description: 'A comment is a piece of text within a program that is not executed. It can be used to provide additional information to aid in understanding the code. In Python, the # character is used to start a comment. The comment continues after the # until the end of the line. py name = "Pied Piper" # Comment after code Python does not have a specific syntax for multi-line comments, unlike some other languages. Instead, multiple # characters can be used:' +Description: 'A comment is a piece of text in a program used to explain code.' Subjects: - 'Computer Science' - 'Data Science' @@ -12,7 +12,7 @@ CatalogContent: - 'paths/computer-science' --- -A comment is a piece of text within a program that is not executed. It can be used to provide additional information to aid in understanding the code. +A comment is a piece of text within a program that is not executed. It is used to provide additional information or context to help understand the code. Python uses the `#` character to start a comment, which extends to the end of the line. ## Single-line Comments @@ -21,14 +21,12 @@ In Python, the `#` character is used to start a comment. The comment continues a ```py # Comment on a single line -name = "Pied Piper" # Comment after code +name = "Pied Piper" # Comment after code ``` ## Multi-line Comments -Python does not have a specific syntax for multi-line comments, unlike some other languages. - -Instead, multiple `#` characters can be used: +Python does not have a specific syntax for multi-line comments, unlike some other languages. Instead, multiple `#` characters can be used: ```py # This is a comment written over @@ -37,7 +35,7 @@ Instead, multiple `#` characters can be used: print("Hello, World!") ``` -Another, less official way of writing comments in Python is to use a multi-line string. Python will ignore string literals that are not assigned to a variable, so multi-line strings (created by surrounding text with triple quotes `"""`) can be used as de facto comments: +Alternatively, multi-line strings (with triple quotes `"""`) can also be used as de facto comments. These are ignored by Python if not assigned to a variable: ```py """ @@ -50,9 +48,9 @@ print("Hello, World!") ## Codebyte Example -Here are some examples of comments in a Python program: +Run the following codebyte to understand how comments work in Python: -```codebyte/py +```codebyte/python """ Tip Calculator Written by Sonny diff --git a/content/python/concepts/pip/pip.md b/content/python/concepts/pip/pip.md index 55ed036ecc6..15523989466 100644 --- a/content/python/concepts/pip/pip.md +++ b/content/python/concepts/pip/pip.md @@ -73,3 +73,61 @@ Finally, it is now possible to start installing packages from PyPI. In the follo ```shell py -m pip install ACoolPackage ``` + +## Virtual Environments with `pip` + +Managing dependencies effectively is crucial when working on multiple Python projects. Without isolation, different projects might require different versions of the same package, which can lead to conflicts. This is where virtual environments come in. They allow users to create isolated environments for each project, ensuring that dependencies do not interfere with one another. + +### Setting Up a Virtual Environment + +The step-by-step process of setting up a virtual environment is described below. + +Step 1: Create a virtual environment + +```shell +python -m venv venv_name +``` + +This creates a new directory (`venv_name`) that contains a standalone Python installation and a local copy of `pip`. + +Step 2: Activate the virtual environment + +```shell +# Windows +venv_name\Scripts\activate + +# Linux/macOS +source venv_name/bin/activate +``` + +After activation, any `pip` commands will install packages only within the virtual environment, ensuring isolation. + +Step 3: Install dependencies + +Once the environment is activated, the project's dependencies can be installed: + +```shell +pip install -r requirements.txt +``` + +Step 4: Deactivate the virtual environment + +When the usage is complete, the virtual environment can be deactivated by simply running: + +```shell +deactivate +``` + +### Generating a `requirements.txt` File + +To help others reproduce the environment, a `requirements.txt` file can be generated. This file lists all the installed packages and their versions: + +```shell +pip freeze > requirements.txt +``` + +This file can then be used to create the same environment by running: + +```shell +pip install -r requirements.txt +``` diff --git a/content/python/concepts/random-module/terms/getrandbits/getrandbits.md b/content/python/concepts/random-module/terms/getrandbits/getrandbits.md new file mode 100644 index 00000000000..4e56eacf6de --- /dev/null +++ b/content/python/concepts/random-module/terms/getrandbits/getrandbits.md @@ -0,0 +1,55 @@ +--- +Title: '.getrandbits()' +Description: 'Generates an integer with a specified number of random bits.' +Subjects: + - 'Computer Science' + - 'Data Science' +Tags: + - 'Functions' + - 'Methods' + - 'Random' +CatalogContent: + - 'learn-python-3' + - 'paths/computer-science' +--- + +The Python random module generates an integer with a specified number of random bits using the **`.getrandbits()`** method. This method produces an integer value that is uniformly distributed across the range of possible values that can be represented with the specified number of bits. + +## Syntax + +```pseudo +random.getrandbits(k) +``` + +- `k`: The number of bits in the generated integer, which must be a non-negative integer. The result will range from 0 to 2k - 1. + +## Example + +In the example below, `.getrandbits()` returns an integer with 256 bits: + +```py +import random + +random_bits = random.getrandbits(256) + +print(random_bits) +``` + +The above code generates the following output: + +```shell +10657559295629545859200648092091505165182082957984693304497110910582120092295 +``` + +> **Note:** The output will change every time the code is run because `.getrandbits()` generates a new random integer each time it's called. + +## Codebyte Example + +Run the following codebyte to understand how the `.getrandbits()` method works: + +```codebyte/python +import random + +get_random = random.getrandbits(8) +print(get_random) +``` diff --git a/content/python/concepts/regex/terms/sub/sub.md b/content/python/concepts/regex/terms/sub/sub.md index 6d08e21c41d..5feec3c1641 100644 --- a/content/python/concepts/regex/terms/sub/sub.md +++ b/content/python/concepts/regex/terms/sub/sub.md @@ -21,17 +21,13 @@ The **`re.sub()`** function replaces matching substrings with a new string for a re.sub(, , string, , ) ``` -A `` is a [regular expression](https://www.codecademy.com/resources/docs/general/regular-expressions) that can include any of the following: - -- A string: `Jane Smith` -- A character class code: `/w`, `/s`, `/d` -- A regex symbol: `$`, `|`, `^` - -The other arguments include: - -- The replacement string (``): `foo` -- An integer value for the number of replacements (``): `10` -- ``: `IGNORECASE`, `VERBOSE`, `DOTALL` +- ``: A [regular expression](https://www.codecademy.com/resources/docs/general/regular-expressions) pattern used to match substrings. + - A string: `Jane Smith` + - Character class codes: `/w`, `/s`, `/d` + - Regex symbols: `$`, `|`, `^` +- ``: The replacement argument. This can either be a string or a function. +- ``: An integer specifying the number of occurrences to replace. The default is to replace all matches. +- ``: Specifies additional options such as `IGNORECASE`, `VERBOSE`, `DOTALL`, etc. ## Example @@ -40,11 +36,14 @@ The following example replaces all occurrences of "BI" with "business intelligen ```py import re -blurb = '''The analytics firm uses a range of BI tools to visualize data. Their internal data science team suggests +def replace_business_intelligence(match): + return 'business intelligence' + +blurb = '''The analytics firm uses a range of BI tools to visualize data. Their internal data science team suggests bi tools may be their most valuable resource.''' -match = re.sub(r'bi','business intelligence',blurb,flags=re.IGNORECASE) -# The IGNORECASE flag allows for matches regardless of the case +# Use the function `replace_bussines_intelligence` as the replacement argument in re.sub() +match = re.sub(r'bi', replace_business_intelligence, blurb, flags=re.IGNORECASE) print(match) ``` @@ -63,10 +62,12 @@ Replace all numerical values with "REDACTED": ```codebyte/python import re -confidential_str = '''The suspect's bank account (#333344444) and pin (#9999) were found in his cell''' +def redact_numbers(match): + return 'REDACTED' + +confidential_str = '''The suspect's bank account (#333344444) and pin (#9999) were found in his cell.''' -redacted = re.sub(r'\d+', 'REDACTED', confidential_str) -# \d matches any numerical character +redacted = re.sub(r'\d+', redact_numbers, confidential_str) print(redacted) ``` diff --git a/content/python/concepts/threading/terms/thread/thread.md b/content/python/concepts/threading/terms/thread/thread.md index 3f8b9562e2f..a6f6342d308 100644 --- a/content/python/concepts/threading/terms/thread/thread.md +++ b/content/python/concepts/threading/terms/thread/thread.md @@ -12,12 +12,12 @@ CatalogContent: - 'paths/computer-science' --- -The `.Thread()` method is a class constructor which returns a thread object that can run a function with zero or more arguments. +The **`.Thread()`** method is a class constructor that returns a thread object that can run a function with zero or more arguments. ## Syntax ```pseudo -threading.Thread(target=object, args=()) +threading.Thread(target=callable, args=()) ``` [Functions](https://www.codecademy.com/resources/docs/python/functions) are commonly passed as the `target` argument, but without parentheses. If any items are listed in the `args` tuple, they are passed as positional arguments to the `target`. @@ -43,7 +43,7 @@ Every thread object has a `name` attribute that, unless otherwise specified, def ``` -## Codebyte Example +## Codebyte Example 1 In the example below, a thread, `hello_thread`, targets the `say_hello()` function with supplied arguments. After the thread is created, the targeted `say_hello()` function is executed when the [`.start()`](https://www.codecademy.com/resources/docs/python/threading/start) method is run. @@ -58,3 +58,64 @@ hello_thread = threading.Thread(target=say_hello, args=("World",)) hello_thread.start() ``` + +## Codebyte Example 2 + +In the example below, two threads, `thread_1` and `thread_2`, target the `download_file()` function with supplied arguments. Each thread simulates downloading a file concurrently by running the `download_file()` function in the background. After the threads are created, the targeted `download_file()` functions are executed when the `.start()` method is run. + +```codebyte/python +import threading +import time + +def download_file(filename, duration): + print(f"Starting download: {filename}") + time.sleep(duration) + print(f"Finished downloading: {filename}") + +# Creating two threads to simulate downloading two files simultaneously +thread_1 = threading.Thread(target=download_file, args=("file1.txt", 2)) +thread_2 = threading.Thread(target=download_file, args=("file2.txt", 4)) + +# Starting the threads, both downloads begin concurrently +thread_1.start() +thread_2.start() + +# Ensuring the main program waits for both threads to finish +thread_1.join() +thread_2.join() + +print("Both downloads completed!") +``` + +## Codebyte Example 3 + +In the example below, two threads, `coffee_thread` and `toast_thread`, target the `make_coffee()` and `toast_bread()` functions, respectively. Each thread simulates the preparation of coffee and toast concurrently. After the threads are created, the targeted functions are executed when the `.start()` method is run. + +```codebyte/python +import threading +import time + +def make_coffee(): + print("Making coffee...") + time.sleep(3) # Simulating the time taken to make coffee + print("Coffee is ready!") + +def toast_bread(): + print("Toasting bread...") + time.sleep(2) # Simulating the time taken to toast bread + print("Bread is toasted!") + +# Creating threads for making coffee and toasting bread +coffee_thread = threading.Thread(target=make_coffee) +toast_thread = threading.Thread(target=toast_bread) + +# Starting both threads to make coffee and toast bread concurrently +coffee_thread.start() +toast_thread.start() + +# Ensuring the main program waits for both threads to finish +coffee_thread.join() +toast_thread.join() + +print("Breakfast is ready!") +``` diff --git a/content/pytorch/concepts/optimizers/optimizers.md b/content/pytorch/concepts/optimizers/optimizers.md new file mode 100644 index 00000000000..5d30bd9ff3d --- /dev/null +++ b/content/pytorch/concepts/optimizers/optimizers.md @@ -0,0 +1,78 @@ +--- +Title: 'Optimizers' +Description: 'Help adjust the model parameters during training to minimize the error between the predicted output and the actual output.' +Subjects: + - 'Data Science' + - 'Machine Learning' +Tags: + - 'Deep Learning' + - 'Libraries' + - 'Python' + - 'TensorFlow' +CatalogContent: + - 'intro-to-py-torch-and-neural-networks' + - 'paths/data-science' +--- + +In PyTorch, **optimizers** help adjust the model parameters during training to minimize the error between the predicted output and the actual output. They use the gradients calculated through backpropagation to update the model in a direction that reduces this error, improving the model's performance over time. + +## Syntax + +```pseudo +torch.optim.optimizer_type(model_parameters, learning_rate) +``` + +- `optimizer_type`: The type of optimizer that will be used. +- `model_parameter`: The parameter of the model that will adjust during training. +- `learning_rate`: The parameter that controls how the optimizer adjusts the model weight. + +## Example + +The following example demonstrates the usage of optimizers in PyTorch: + +```py +import torch +import torch.nn as nn +import torch.optim as optim + +# Input and target data (simple linear relationship y = 2x) +x = torch.tensor([[1.0], [2.0], [3.0], [4.0]]) +y = torch.tensor([[2.0], [4.0], [6.0], [8.0]]) + +# Simple model: 1 linear layer +model = nn.Linear(1, 1) + +# Adam Optimizer and Mean Squared Error (MSE) Loss +optimizer = optim.Adam(model.parameters(), lr=0.01) +criterion = nn.MSELoss() + +# Training loop +for epoch in range(50): + predictions = model(x) + loss = criterion(predictions, y) + optimizer.zero_grad() + loss.backward() + optimizer.step() + + if (epoch+1) % 10 == 0: # Print loss every 10 epochs + print(f'Epoch {epoch+1}, Loss: {loss.item():.4f}') + +# Test the model by making a prediction for x = 5 +with torch.no_grad(): + test_input = torch.tensor([[5.0]]) + test_output = model(test_input) + print(f'The predicted value for input 5: {test_output.item():.4f}') +``` + +> **Note:** Optimizers also support specifying per-parameter options like learning rate allowing. + +The output of the above code is: + +```shell +Epoch 10, Loss: 9.0166 +Epoch 20, Loss: 7.0211 +Epoch 30, Loss: 5.3501 +Epoch 40, Loss: 3.9961 +Epoch 50, Loss: 2.9324 +The predicted value for input 5: 6.4472 +``` diff --git a/content/pytorch/concepts/tensor-operations/terms/conj/conj.md b/content/pytorch/concepts/tensor-operations/terms/conj/conj.md new file mode 100644 index 00000000000..3662aabc6ab --- /dev/null +++ b/content/pytorch/concepts/tensor-operations/terms/conj/conj.md @@ -0,0 +1,55 @@ +--- +Title: '.conj()' +Description: 'Computes the complex conjugate of each element in a given tensor.' +Subjects: + - 'Computer Science' + - 'Machine Learning' +Tags: + - 'Python' + - 'Machine Learning' + - 'Functions' + - 'Values' +CatalogContent: + - 'intro-to-py-torch-and-neural-networks' + - 'paths/computer-science' +--- + +In PyTorch, the **`.conj()`** function is used to compute the complex conjugate of each element in a given tensor, returning a new tensor with the computed conjugate values. + +## Syntax + +```pseudo +torch.conj(tensor) +``` + +- `tensor`: The input tensor for which the complex conjugate will be computed. + +## Example + +The following example illustrates the usage of `.conj()`: + +```py +import torch + +complex_tensor = torch.tensor([1 + 2j, 3 - 4j, 5 + 0j]) +print("Original Complex Tensor:") +print(complex_tensor) + +# Applying .conj() on a complex tensor +complex_conj = torch.conj(complex_tensor) +print(f"\nReturn type of .conj() - {type(complex_conj)}") +print("\nComplex Conjugate:") +print(complex_conj) +``` + +The above program gives the following output: + +```shell +Original Complex Tensor: +tensor([1.+2.j, 3.-4.j, 5.+0.j]) + +Return type of .conj() - + +Complex Conjugate: +tensor([1.-2.j, 3.+4.j, 5.-0.j]) +``` diff --git a/content/pytorch/concepts/tensor-operations/terms/gather/gather.md b/content/pytorch/concepts/tensor-operations/terms/gather/gather.md new file mode 100644 index 00000000000..2278d2db1e1 --- /dev/null +++ b/content/pytorch/concepts/tensor-operations/terms/gather/gather.md @@ -0,0 +1,57 @@ +--- +Title: '.gather()' +Description: 'Retrieves specific elements from a tensor along a defined axis based on indices.' +Subjects: + - 'AI' + - 'Data Science' +Tags: + - 'AI' + - 'Data Types' + - 'Deep Learning' + - 'Functions' +CatalogContent: + - 'intro-to-py-torch-and-neural-networks' + - 'paths/data-science' +--- + +The **`.gather()`** function in PyTorch is a tensor operation that retrieves specific elements from a tensor along a specified axis. It is beneficial for selecting values based on a set of indices, making it ideal for applications in machine learning and data processing, where efficient data selection is critical. + +## Syntax + +```pseudo +torch.gather(input, dim, index) +``` + +- `input`: The source tensor from which values are gathered. +- `dim`: The dimension along which to gather values. This is the axis in the `input` tensor where the selection occurs. +- `index`: A tensor of indices specifying which values to gather from the `input` tensor along the specified `dim`. + +The function returns a tensor with the same shape as the `index`, where each value is gathered from the `input` tensor based on the specified indices. + +## Example + +Here's an example of how `.gather()` can be used to select elements from a tensor based on specified indices: + +```py +import torch + +# Define a source tensor +input_tensor = torch.tensor([[1, 2], [3, 4]]) + +# Define the indices to gather +index_tensor = torch.tensor([[0, 1], [1, 0]]) + +# Gather elements from the source tensor along dimension 1 +output_tensor = torch.gather(input_tensor, 1, index_tensor) + +print(output_tensor) +``` + +This example results in the following output: + +```shell +tensor([[1, 2], + [4, 3]]) +``` + +In this example, `.gather()` retrieves elements from `input_tensor` based on `index_tensor` along dimension `1`. The result is a new tensor where values are selected from the original tensor according to the provided indices. diff --git a/content/pytorch/concepts/tensor-operations/terms/hsplit/hsplit.md b/content/pytorch/concepts/tensor-operations/terms/hsplit/hsplit.md new file mode 100644 index 00000000000..36dccb45c91 --- /dev/null +++ b/content/pytorch/concepts/tensor-operations/terms/hsplit/hsplit.md @@ -0,0 +1,58 @@ +--- +Title: '.hsplit()' +Description: 'Splits a tensor horizontally into multiple sub-tensors.' +Subjects: + - 'AI' + - 'Data Science' +Tags: + - 'AI' + - 'Arrays' + - 'Data Structures' + - 'Deep Learning' +CatalogContent: + - 'intro-to-py-torch-and-neural-networks' + - 'paths/computer-science' +--- + +In PyTorch, the **`.hsplit()`** method splits a [tensor](https://www.codecademy.com/resources/docs/pytorch/tensors) into multiple sub-tensors horizontally (column-wise) along the specified dimension (axis). + +## Syntax + +```pseudo +torch.hsplit(tensor, indices_or_sections) +``` + +- `tensor`: The tensor to be split. +- `indices_or_sections`: This can be an integer or a list of integers. + - If it's an integer, it specifies the number of equal-sized sub-tensors to split the tensor into. + - If it's a list of integers, it specifies the sizes of each sub-tensor along the specified dimension. + +## Example + +The following example demonstrates the usage of the `.hsplit()` method: + +```py +import torch + +# Define a tensor +tensor = torch.tensor([[1, 2, 3, 4], + [5, 6, 7, 8], + [9, 10, 11, 12]]) + +# Split the tensor into 2 equal parts +sub_tensors = torch.hsplit(tensor, 2) + +print(sub_tensors) +``` + +The above code produces the following output: + +```shell +(tensor([[ 1, 2], + [ 5, 6], + [ 9, 10]]), tensor([[ 3, 4], + [ 7, 8], + [11, 12]])) +``` + +The tensor is split into two sub-tensors along the columns. The first sub-tensor contains the first two columns of the original tensor, while the second sub-tensor contains the last two columns. diff --git a/content/pytorch/concepts/tensor-operations/terms/hstack/hstack.md b/content/pytorch/concepts/tensor-operations/terms/hstack/hstack.md new file mode 100644 index 00000000000..cda4ca55c37 --- /dev/null +++ b/content/pytorch/concepts/tensor-operations/terms/hstack/hstack.md @@ -0,0 +1,53 @@ +--- +Title: '.hstack()' +Description: 'Concatenates two or more tensors along the horizontal axis (column-wise).' +Subjects: + - 'AI' + - 'Data Science' +Tags: + - 'AI' + - 'Data Types' + - 'Deep Learning' + - 'Functions' +CatalogContent: + - 'intro-to-py-torch-and-neural-networks' + - 'paths/data-science' +--- + +In PyTorch, **`.hstack()`** (short for horizontal stack) is a function used to concatenate two or more [tensors](https://www.codecademy.com/resources/docs/pytorch/tensors) along the horizontal axis (`axis=1`). This operation is helpful in combining data with the same number of rows but differing in the number of columns. It acts similarly to **`np.hstack()`** in [NumPy](https://www.codecademy.com/resources/docs/numpy) and is particularly handy for data that needs to be concatenated side by side before being fed into a model for training or inference. + +## Syntax + +```pseudo +torch.hstack(tensors) -> Tensor +``` + +- `tensors`: A sequence of tensors with the same number of rows. All tensors must have the same number of dimensions and the same size in all dimensions except for the dimension corresponding to the horizontal stacking. + +The function returns a new tensor containing the horizontal concatenation of the input tensors. + +## Example + +Here's an example demonstrating how `.hstack()` can be used to concatenate tensors: + +```py +import torch + +# Create two tensors +a = torch.tensor([[1, 2],[3, 4]]) +b = torch.tensor([[5, 6],[7, 8]]) + +# Stack the tensors horizontally +c = torch.hstack((a, b)) + +print(c) +``` + +The above code produces the following output: + +```shell +tensor([[1, 2, 5, 6], + [3, 4, 7, 8]]) +``` + +This example demonstrates concatenating two 2x2 tensors horizontally resulting in 2x4 tensor. diff --git a/content/pytorch/concepts/tensor-operations/terms/mm/mm.md b/content/pytorch/concepts/tensor-operations/terms/mm/mm.md new file mode 100644 index 00000000000..d29aff253c8 --- /dev/null +++ b/content/pytorch/concepts/tensor-operations/terms/mm/mm.md @@ -0,0 +1,81 @@ +--- +Title: '.mm()' +Description: 'Calculates the matrix product of two given tensors.' +Subjects: + - 'AI' + - 'Data Science' +Tags: + - 'AI' + - 'Arrays' + - 'Data Structures' + - 'Deep Learning' +CatalogContent: + - 'intro-to-py-torch-and-neural-networks' + - 'paths/computer-science' +--- + +In PyTorch, the **`.mm()`** method calculates the matrix product of two given tensors. + +## Syntax + +```pseudo +torch.mm(ten1, ten2, *, out=None) +``` + +- `ten1`: The first tensor to be multiplied. +- `ten2`: The second tensor to be multiplied. +- `out` (Optional): The output tensor to be used. The default value is `None`. + +> **Note:** If `ten1` is a `(m x n)` tensor and `ten2` is a `(n x p)` tensor, then `out` will be a `(m x p)` tensor. + +## Example + +The following example demonstrates the usage of the `.mm()` method: + +```py +import torch + +# Define two tensors +ten1 = torch.tensor([[1, 2, 3], + [4, 3, 8], + [1, 7, 2]]) + +ten2 = torch.tensor([[2, 4, 1], + [1, 3, 6], + [2, 6, 5]]) + +# Multiply the tensors +out = torch.mm(ten1, ten2) + +print(out) +``` + +The above code produces the following output: + +```shell +tensor([[10, 28, 28], + [27, 73, 62], + [13, 37, 53]]) +``` + +## Codebyte Example + +The following codebyte example shows the use of the `.mm()` method: + +```codebyte/python +import torch + +# Define two tensors +ten1 = torch.tensor([[6, 8, 1], + [5, 2, 4], + [9, 3, 7]]) + +ten2 = torch.tensor([[9, 2, 3], + [7, 8, 4], + [6, 1, 5]]) + +# Multiply the tensors +out = torch.mm(ten1, ten2) + +print(out) +``` diff --git a/content/pytorch/concepts/tensor-operations/terms/narrow/narrow.md b/content/pytorch/concepts/tensor-operations/terms/narrow/narrow.md new file mode 100644 index 00000000000..0fb4ee3fd28 --- /dev/null +++ b/content/pytorch/concepts/tensor-operations/terms/narrow/narrow.md @@ -0,0 +1,109 @@ +--- +Title: '.narrow()' +Description: 'Returns a narrow subsection of a tensor along a specified dimension.' +Subjects: + - 'Computer Science' + - 'Machine Learning' +Tags: + - 'Python' + - 'Machine Learning' + - 'Methods' + - 'Functions' +CatalogContent: + - 'intro-to-py-torch-and-neural-networks' + - 'paths/computer-science' +--- + +In PyTorch, the **`.narrow()`** method selects a subsection of a [tensor](https://www.codecademy.com/resources/docs/pytorch/tensors) along a specified dimension. It returns a narrowed view without copying the underlying data, making it efficient for extracting specific sections of large tensors without incurring additional memory allocations. + +## Syntax + +```pseudo +torch.narrow(input, dim, start, length) +``` + +- `input`: The tensor to be narrowed. +- `dim`: The dimension along which the input tensor is to be narrowed. +- `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 illustrates the usage of the `.narrow()` method in various scenarios: + +```py +import torch + +# Create a 2D tensor +tensor_2d = torch.arange(1, 13).reshape(3, 4) +print(f"Original 2D Tensor:\n{tensor_2d}") + +# Case 1: Narrowing along rows (dim=0) +row_narrow = torch.narrow(tensor_2d, 0, 1, 2) +print("\nCase 1: Narrow Along Rows (dim=0, start=1, length=2)") +print(row_narrow) + +# Case 2: Narrowing along columns (dim=1) +col_narrow = torch.narrow(tensor_2d, 1, 1, 2) +print("\nCase 2: Narrow Along Columns (dim=1, start=1, length=2)") +print(col_narrow) + +# Case 3: Extracting a single column (dim=1, length=1) +single_col = torch.narrow(tensor_2d, 1, 2, 1) +print("\nCase 3: Extract Single Column (dim=1, start=2, length=1)") +print(single_col) + +# Case 4: Narrow with length extending beyond tensor's dimension +# In this case, .narrow() raises an error because the sub-tensor's length exceeds the tensor's dimension +try: + error_narrow = torch.narrow(tensor_2d, 0, 1, 5) + print("\nCase 4: Narrow With Length Exceeding Dimension Size") + print(error_narrow) +except RuntimeError as e: + print("\nCase 4: RuntimeError -", e) + +# Case 5: Using a negative start index (dim=1, start=-3, length=2) +negative_start_narrow = torch.narrow(tensor_2d, 1, -3, 2) +print("\nCase 5: Negative Start Index (dim=1, start=-3, length=2)") +print(negative_start_narrow) + +# Case 6: Using a 0-dimensional start index +tensor_0_dim = torch.tensor(1) # 0-dimensional integer tensor +tensor_start_narrow = torch.narrow(tensor_2d, 0, tensor_0_dim, 2) +print("\nCase 6: Start Index as a 0-Dim Tensor (dim=0, start=tensor(1), length=2)") +print(tensor_start_narrow) +``` + +The above program gives the following output: + +```shell +Original 2D Tensor: +tensor([[ 1, 2, 3, 4], + [ 5, 6, 7, 8], + [ 9, 10, 11, 12]]) + +Case 1: Narrow Along Rows (dim=0, start=1, length=2) +tensor([[ 5, 6, 7, 8], + [ 9, 10, 11, 12]]) + +Case 2: Narrow Along Columns (dim=1, start=1, length=2) +tensor([[ 2, 3], + [ 6, 7], + [10, 11]]) + +Case 3: Extract Single Column (dim=1, start=2, length=1) +tensor([[ 3], + [ 7], + [11]]) + +Case 4: RuntimeError - start (1) + length (5) exceeds dimension size (3). + +Case 5: Negative Start Index (dim=1, start=-3, length=2) +tensor([[ 2, 3], + [ 6, 7], + [10, 11]]) + +Case 6: Start Index as a 0-Dim Tensor (dim=0, start=tensor(1), length=2) +tensor([[ 5, 6, 7, 8], + [ 9, 10, 11, 12]]) +``` diff --git a/content/pytorch/concepts/tensor-operations/terms/split/split.md b/content/pytorch/concepts/tensor-operations/terms/split/split.md new file mode 100644 index 00000000000..a168064da07 --- /dev/null +++ b/content/pytorch/concepts/tensor-operations/terms/split/split.md @@ -0,0 +1,136 @@ +--- +Title: '.split()' +Description: 'Splits a tensor into chunks of specified sizes along a given dimension.' +Subjects: + - 'Computer Science' + - 'Machine Learning' + - 'Data Science' +Tags: + - 'Python' + - 'Machine Learning' +CatalogContent: + - 'intro-to-py-torch-and-neural-networks' + - 'paths/computer-science' +--- + +In PyTorch, the **`.split()`** function is used to split a tensor into chunks of specified sizes along a specified dimension and returns a tuple of tensors. It is useful for processing smaller segments of data independently. + +## Syntax + +```pseudo +torch.split(tensor, split_size_or_sections, dim=0) +``` + +- `tensor`: The tensor to be split. This is a required parameter. +- `split_size_or_sections`: Specifies the size of each chunk. If an integer, it defines the number of elements in each chunk. If a list of integers, it specifies the exact size of each chunk in order. +- `dim`(Optional): The dimension along which to split the tensor. The default value is 0. + +## Example + +The following example illustrates the usage of `.split()` in various scenarios: + +```py +import torch + +# a 1D tensor and a 2D tensor +tensor_1d = torch.arange(1, 13) +tensor_2d = tensor_1d.reshape(2, 6) + +print(f"Input 1D Tensor - {tensor_1d}") + +# Case 1: Splitting into equal chunks of size 3 +equal_chunks = torch.split(tensor_1d, 3) +print("\nCase 1: Equal Chunks (Size = 3)") +for chunk in equal_chunks: + print(chunk) + +# Case 2: Splitting into unequal chunks of sizes [4, 3, 5] +unequal_chunks = torch.split(tensor_1d, [4, 3, 5]) +print("\nCase 2: Unequal Chunks (Sizes = [4, 3, 5])") +for chunk in unequal_chunks: + print(chunk) + +# Case 3: Attempting to split with non-divisible chunk size +non_divisible_split = torch.split(tensor_1d, 5) +print("\nCase 3: Non-Divisible Chunk Size (Size = 5)") +for chunk in non_divisible_split: + print(chunk) + +print(f"\nInput 2D Tensor - {tensor_2d}") + +# Case 4: Splitting a 2D tensor along rows (dim=0) +row_split = torch.split(tensor_2d, 1, dim=0) +print("\nCase 4: Split Along Rows (dim=0, size=1)") +for chunk in row_split: + print(chunk) + +# Case 5: Splitting a 2D tensor along columns (dim=1) +col_split = torch.split(tensor_2d, 3, dim=1) +print("\nCase 5: Split Along Columns (dim=1, size=3)") +for chunk in col_split: + print(chunk) + +# Case 6: Splitting a 2D tensor into unequal sizes along columns (dim=1) +uneven_split_2d = torch.split(tensor_2d, [1, 3, 2], dim=1) +print("\nCase 6: Unequal Split Sizes on 2D Tensor ([1, 3, 2], dim=1)") +for chunk in uneven_split_2d: + print(chunk) + +# Case 7: Unequal split with sizes that do not sum up to the tensor size +# In this case, .split() raises an error when the sizes don't add up correctly. +print("\nCase 7: Unequal Split Sizes That Do Not Sum Upto the 2D Tensor Size ([1, 3, 3], dim=1)") +try: + error_split = torch.split(tensor_2d, [1, 3, 3], dim=1) + + for chunk in error_split: + print(chunk) + +except RuntimeError as e: + print(f"RuntimeError - {e}") +``` + +The above program gives the following output: + +```shell +Input 1D Tensor - tensor([ 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12]) + +Case 1: Equal Chunks (Size = 3) +tensor([1, 2, 3]) +tensor([4, 5, 6]) +tensor([7, 8, 9]) +tensor([10, 11, 12]) + +Case 2: Unequal Chunks (Sizes = [4, 3, 5]) +tensor([1, 2, 3, 4]) +tensor([5, 6, 7]) +tensor([ 8, 9, 10, 11, 12]) + +Case 3: Non-Divisible Chunk Size (Size = 5) +tensor([1, 2, 3, 4, 5]) +tensor([ 6, 7, 8, 9, 10]) +tensor([11, 12]) + +Input 2D Tensor - tensor([[ 1, 2, 3, 4, 5, 6], + [ 7, 8, 9, 10, 11, 12]]) + +Case 4: Split Along Rows (dim=0, size=1) +tensor([[1, 2, 3, 4, 5, 6]]) +tensor([[ 7, 8, 9, 10, 11, 12]]) + +Case 5: Split Along Columns (dim=1, size=3) +tensor([[1, 2, 3], + [7, 8, 9]]) +tensor([[ 4, 5, 6], + [10, 11, 12]]) + +Case 6: Unequal Split Sizes on 2D Tensor ([1, 3, 2], dim=1) +tensor([[1], + [7]]) +tensor([[ 2, 3, 4], + [ 8, 9, 10]]) +tensor([[ 5, 6], + [11, 12]]) + +Case 7: Unequal Split Sizes That Do Not Sum Upto the 2D Tensor Size ([1, 3, 3], dim=1) +RuntimeError - split_with_sizes expects split_sizes to sum exactly to 6 (input tensor's size at dimension 1), but got split_sizes=[1, 3, 3] +``` diff --git a/content/pytorch/concepts/tensor-operations/terms/take/take.md b/content/pytorch/concepts/tensor-operations/terms/take/take.md new file mode 100644 index 00000000000..3bf135c5f79 --- /dev/null +++ b/content/pytorch/concepts/tensor-operations/terms/take/take.md @@ -0,0 +1,50 @@ +--- +Title: '.take()' +Description: 'Returns a 1D tensor containing elements from input at the specified indices.' +Subjects: + - 'AI' + - 'Data Science' +Tags: + - 'AI' + - 'Arrays' + - 'Data Structures' + - 'Deep Learning' +CatalogContent: + - 'intro-to-py-torch-and-neural-networks' + - 'paths/computer-science' +--- + +The **`.take()`** function returns a 1D tensor containing elements from the given tensor at the specified indices. The resulting tensor will always be a 1D tensor irrespective of the size of the given tensor. + +## Syntax + +```pseudo +torch.take(input,index) +``` + +- `input`: The input tensor from which the elements will be selected. +- `index`: A 1D tensor containing the indices of the elements to extract from `input`. + +## Example + +The following example demonstrates the usage of `.take()` function: + +```py +import torch + +# Define a tensor +data = torch.tensor([[4, 2, -1], [7, 8, 0]]) + +# Define indices as a tensor +indices = torch.tensor([0, 2, 5]) + +# Use torch.take with data and indices +result = torch.take(data, indices) +print(result) +``` + +The code produces the following output: + +```shell +[4,-1,0] +``` diff --git a/content/pytorch/concepts/tensors/terms/chunk/chunk.md b/content/pytorch/concepts/tensors/terms/chunk/chunk.md new file mode 100644 index 00000000000..e2af6e3f643 --- /dev/null +++ b/content/pytorch/concepts/tensors/terms/chunk/chunk.md @@ -0,0 +1,58 @@ +--- +Title: '.chunk()' +Description: 'Splits a tensor with a specified dimension into chunks.' +Subjects: + - 'Data Science' + - 'Machine Learning' +Tags: + - 'AI' + - 'Data Types' + - 'Deep Learning' + - 'Functions' +CatalogContent: + - 'intro-to-py-torch-and-neural-networks' + - 'paths/data-science' +--- + +In PyTorch, the **`.chunk()`** function splits a tensor into a specific number of chunks. The function may return fewer than the specified number of chunks. To get the exact number of chunks, the **`.tensor_split()`** function can be used. + +## Syntax + +```pseudo +torch.chunk(input, chunks, dim) +``` + +- `input`: A required parameter that specifies the tensor that will be split into chunks. +- `chunks`: A required parameter that specifies the number of chunks that will be returned. +- `dim`: An optional parameter that specifies the dimension along which the split is performed. + +> **Note:** If the tensor size is divisible by the number of chunks, then all the chunks returned are of same size. Otherwise, one chunk will be of a different size. If neither is an option, the function may return fewer chunks than the number of chunks specified. + +## Example + +Here is an example of a one-dimensional tensor with 6 elements, which is split into 3 chunks: + +```py +import torch + +# Create a 1D tensor +x = torch.tensor([1, 2, 3, 4, 5, 6]) + +print("Original tensor:", x) + +# Split the tensor into 3 chunks +chunks = torch.chunk(x, chunks=3) + +# Print each chunk +for i, chunk in enumerate(chunks): + print(f"Chunk {i}:", chunk) +``` + +The output of this is shown below: + +```shell +Original tensor: tensor([1, 2, 3, 4, 5, 6]) +Chunk 0: tensor([1, 2]) +Chunk 1: tensor([3, 4]) +Chunk 2: tensor([5, 6]) +``` diff --git a/content/pytorch/concepts/tensors/terms/full/full.md b/content/pytorch/concepts/tensors/terms/full/full.md new file mode 100644 index 00000000000..bd602ff4e24 --- /dev/null +++ b/content/pytorch/concepts/tensors/terms/full/full.md @@ -0,0 +1,51 @@ +--- +Title: '.full()' +Description: 'Creates a tensor filled with a specified value, with the shape defined by the given dimensions.' +Subjects: + - 'Data Science' + - 'Machine Learning' +Tags: + - 'AI' + - 'Alias' + - 'Algorithms' + - 'Data' + - 'Data Structures' +CatalogContent: + - 'learn-python-3' + - 'intro-to-py-torch-and-neural-networks' +--- + +The **`.full()`** function creates a tensor of a specified shape, filled with a constant value. This function is particularly useful in machine learning and data science for efficiently managing tensors, as it allows the creation of tensors with predefined values. Additionally, it accepts several parameters that allow users to specify the shape, fill value, and other optional attributes like data type and device allocation. + +## Syntax + +```pseudo +torch.full(size, fill_value, *, out=None, dtype=None, layout=torch.strided, device=None, requires_grad=False) +``` + +- `size`: A list or tuple that specifies the desired shape of the output tensor. +- `fill_value`: A scalar value that fills the tensor. +- `out` (optional): An existing tensor where the result will be stored, it must have the same shape as the output. +- `dtype` (optional): The desired data type of the output tensor. +- `layout` (optional): Desired layout of the returned tensor. Default value is `torch.strided`. +- `device` (optional): The device on which the tensor is to be allocated. +- `requires_grad (optional)`: A boolean value that indicates whether to track the operations on the tensor for gradient computation. By default this is `False`. + +## Example + +The below example code creates a _2x3_ tensor where all elements are set to _5_: + +```py +import torch + +# Create a 2x3 tensor filled with the value 5 +tensor = torch.full((2, 3), 5) +print(tensor) +``` + +The code above produces the following output: + +```shell +tensor([[5, 5, 5], + [5, 5, 5]]) +``` diff --git a/content/pytorch/concepts/tensors/terms/linspace/linspace.md b/content/pytorch/concepts/tensors/terms/linspace/linspace.md new file mode 100644 index 00000000000..8d6bd3e69b1 --- /dev/null +++ b/content/pytorch/concepts/tensors/terms/linspace/linspace.md @@ -0,0 +1,48 @@ +--- +Title: '.linspace()' +Description: 'Returns a one-dimensional tensor with a specified number of evenly spaced values between the given start and end points.' +Subjects: + - 'Data Science' + - 'Machine Learning' +Tags: + - 'AI' + - 'Data Types' + - 'Deep Learning' + - 'Functions' +CatalogContent: + - 'intro-to-py-torch-and-neural-networks' + - 'py-torch-for-classification' +--- + +The **`.linspace()`** function in PyTorch is used to return a one-dimensional tensor with a specified number of evenly spaced values between the given start and end points. + +## Syntax + +```pseudo +torch.linspace(start, end, steps) +``` + +- `start`: The starting value to be used. +- `end`: The ending value to be used. +- `steps`: The number of steps to be taken between the starting and ending values. + +This function is particularly useful when there is a need to create a tensor of equally spaced points for plotting graphs or for performing other numerical computations. + +## Example + +The following example shows how to use the `.linspace()` function in PyTorch: + +```py +import torch + +# Create a tensor of 5 equally spaced points between 0 and 1 +x = torch.linspace(0, 1, 5) + +print(x) +``` + +The code above generates the following output: + +```shell +tensor([0.0000, 0.2500, 0.5000, 0.7500, 1.0000]) +``` diff --git a/content/pytorch/concepts/tensors/terms/logspace/logspace.md b/content/pytorch/concepts/tensors/terms/logspace/logspace.md new file mode 100644 index 00000000000..56ddefbbe6f --- /dev/null +++ b/content/pytorch/concepts/tensors/terms/logspace/logspace.md @@ -0,0 +1,69 @@ +--- +Title: '.logspace()' +Description: 'Returns a one-dimensional tensor with values logarithmically spaced.' +Subjects: + - 'Data Science' + - 'Machine Learning' +Tags: + - 'AI' + - 'Data Types' + - 'Deep Learning' + - 'Functions' +CatalogContent: + - 'intro-to-py-torch-and-neural-networks' + - 'py-torch-for-classification' +--- + +The **`.logspace()`** function returns a one-dimensional tensor with values logarithmically spaced. + +The function is useful for generating logarithmically spaced values for various applications, such as plotting data on a logarithmic scale or creating logarithmic scales for neural network hyperparameters. + +## Syntax + +```pseudo +torch.logspace(start, end, steps, base, dtype=None) +``` + +- `start`: The first number in the range expressed as a logarithm. +- `end`: The last number in the range expressed as a logarithm. +- `steps`: Number of elements to be returned in the tensor. +- `base`: The base of the logarithm used for calculating the values default value is 10. +- `dtype`: Specifies the data type of the returned tensor. + +## Example 1 + +In this example, the code generates a tensor containing 5 logarithmically spaced values between 1 and 1000: + +```py +import torch + +# Generate a tensor with 5 logarithmically spaced values between 1 and 1000 +tensor = torch.logspace(0, 3, steps=5) +print(tensor) +``` + +The code above generates the following output: + +```shell +tensor([ 1.0000, 5.6234, 31.6228, 177.8279, 1000.0000]) +``` + +## Example 2 + +In this example, the code generates a tensor containing 3 logarithmically spaced values between 1 and 10 using the `.logspace()` function: + +```py +import torch + +# Generate a tensor with 3 logarithmically spaced values between 0 and 10 +tensor = torch.logspace(0, 1, steps=3, dtype=torch.float64) +print(tensor) +``` + +Output: + +```shell +tensor([1.0000, 3.1623, 10.0000], dtype=torch.float64) +``` + +In this example, we created a tensor `tensor` containing 3 logarithmically spaced values between 0 and 1 using the `.logspace()` function with a data type of `torch.float64`. The tensor `tensor` contains the values `[1.0000, 3.1623, 10.0000]`. diff --git a/content/pytorch/concepts/tensors/terms/size/size.md b/content/pytorch/concepts/tensors/terms/size/size.md new file mode 100644 index 00000000000..0f18794a6fd --- /dev/null +++ b/content/pytorch/concepts/tensors/terms/size/size.md @@ -0,0 +1,48 @@ +--- +Title: '.size()' +Description: 'Returns the size of the self tensor as a tuple of integers.' +Subjects: + - 'Data Science' + - 'Machine Learning' +Tags: + - 'AI' + - 'Data Structures' + - 'Deep Learning' + - 'Methods' +CatalogContent: + - 'learn-python-3' + - 'paths/computer-science' +--- + +The **`size()`** method in PyTorch returns a `torch.Size` object containing the size (shape) information of a tensor. It serves as a fundamental function for dynamically obtaining the tensor's shape during operations. Specific dimensions can be accessed by indexing into the `torch.Size` object, which functions like a tuple. + +## Syntax + +```pseudo +tensor.size(dim=None) +``` + +- `tensor`: The PyTorch tensor on which the `.size()` method is called. +- `dim` (Optional): Specifies the dimension for which to retrieve the size. The default value is `None`. + - If `dim` is not provided, the returned value is a `torch.Size` object representing the size of all dimensions. + - If `dim` is specified, the returned value is an `int` representing the size of the given dimension. + +## Example + +The following example shows how to use the `.size()` method: + +```py +import torch + +t = torch.empty(3, 4, 5) + +print(t.size()) +print(t.size(dim=1)) +``` + +The code above generates the following output: + +```shell +torch.Size([3, 4, 5]) +4 +``` diff --git a/content/pytorch/concepts/tensors/terms/view/view.md b/content/pytorch/concepts/tensors/terms/view/view.md new file mode 100644 index 00000000000..b92d19c5447 --- /dev/null +++ b/content/pytorch/concepts/tensors/terms/view/view.md @@ -0,0 +1,53 @@ +--- +Title: '.view()' +Description: 'Reshapes a tensor to a specified shape without changing its data, as long as the total number of elements remains the same.' +Subjects: + - 'AI' + - 'Data Science' +Tags: + - 'AI' + - 'Data Types' + - 'Deep Learning' + - 'Functions' +CatalogContent: + - 'intro-to-py-torch-and-neural-networks' + - 'paths/data-science' +--- + +The **`.view()`** method in PyTorch reshapes a tensor without altering its underlying data, provided the total number of elements remains the same. This method is useful when preparing tensors for operations requiring specific dimensions, such as neural network inputs. + +## Syntax + +```pseudo +tensor.view(shape) +``` + +- `shape`: A tuple or list defining the desired dimensions. The total number of elements must match the original tensor. + +The function returns a tensor with the specified shape, sharing the same data as the original tensor. + +## Example + +This example reshapes a tensor from a shape of _(2, 3)_ to _(3, 2)_ using `.view()`: + +```py +import torch + +# Create a tensor of shape (2, 3) +original_tensor = torch.tensor([[1, 2, 3], [4, 5, 6]]) + +# Reshape the tensor to (3, 2) +reshaped_tensor = original_tensor.view(3, 2) + +print(reshaped_tensor) +``` + +This example results in the following output: + +```shell +tensor([[1, 2], + [3, 4], + [5, 6]]) +``` + +In this example, `.view()` modifies the shape of `original_tensor` while preserving its data. diff --git a/content/sklearn/concepts/label-propagation/label-propagation.md b/content/sklearn/concepts/label-propagation/label-propagation.md new file mode 100644 index 00000000000..83779bec16c --- /dev/null +++ b/content/sklearn/concepts/label-propagation/label-propagation.md @@ -0,0 +1,76 @@ +--- +Title: 'Label Propagation' +Description: 'A semi-supervised learning algorithm that spreads labels from a small set of labeled data points to the unlabeled data using a graph-based approach.' +Subjects: + - 'Data Science' + - 'Machine Learning' +Tags: + - 'Classification' + - 'Scikit-learn' +CatalogContent: + - 'learn-python-3' + - 'paths/data-science' +--- + +**Label Propagation** is a semi-supervised learning algorithm used in classification problems where a small portion of the data is labeled, and the remaining data is unlabeled. The algorithm spreads the label information from the labeled instances to the unlabeled ones by propagating labels across the graph built from the input data. In Scikit-learn, this is implemented as part of the `sklearn.semi_supervised` module. + +Scikit-learn provides two closely related semi-supervised algorithms: + +- **Label Propagation**: Propagates labels through the graph using a probabilistic transition matrix. +- **Label Spreading**: A variant of Label Propagation that uses a normalized graph Laplacian to reduce noise sensitivity. + +## Syntax + +```pseudo +from sklearn.semi_supervised import LabelPropagation + +# Create a LabelPropagation object with desired parameters +model = LabelPropagation(kernel='rbf', gamma=1, max_iter=1000) + +# Fit the model to your data +model.fit(X, y) + +# Predict labels for unlabeled data +y_pred = model.predict(X_unlabeled) +``` + +- `kernel`: The kernel function used for label propagation. Common options are `rbf` (radial basis function), `knn` (k-nearest neighbors), and `poly` (polynomial). +- `gamma`: The kernel coefficient for the `rbf` kernel. +- `max_iter`: The maximum number of iterations for the label propagation algorithm. +- `X`: The input data, where each row is a sample and each column is a feature. +- `y`: The corresponding labels for the labeled samples. +- `X_unlabeled`: The input data for the unlabeled samples. + +## Example + +In the following example, a small set of labeled points (`y = 0, 1`) and unlabeled points (`y = -1`) is given. The Label Propagation algorithm spreads the known labels to the unlabeled data points based on their proximity. + +```python +import numpy as np +from sklearn.semi_supervised import LabelPropagation +import matplotlib.pyplot as plt + +# Create synthetic data +X = np.array([[1, 1], [2, 1], [3, 2], [5, 5], [6, 5], [7, 6]]) +y = np.array([0, 0, 1, -1, -1, -1]) # -1 represents unlabeled data + +# Initialize Label Propagation model +model = LabelPropagation() +model.fit(X, y) + +# Predict labels for unlabeled data +predicted_labels = model.transduction_ +print("Predicted labels:", predicted_labels) + +# Plotting the data +plt.scatter(X[:, 0], X[:, 1], c=predicted_labels, cmap='viridis', s=100) +plt.show() +``` + +The output of the above code will be: + +```shell +Predicted labels: [0 0 1 1 1 1] +``` + +![Label Propagation Example](https://raw.githubusercontent.com/Codecademy/docs/main/media/sklearn-label-propagation.png) diff --git a/content/sklearn/concepts/multitask-classification/multitask-classification.md b/content/sklearn/concepts/multitask-classification/multitask-classification.md index e317c4673cd..2d84c48bc80 100644 --- a/content/sklearn/concepts/multitask-classification/multitask-classification.md +++ b/content/sklearn/concepts/multitask-classification/multitask-classification.md @@ -65,3 +65,28 @@ Predicted labels (Quality, Demand): [[0 1]] ``` In the above output, `0` indicates _low quality_ and `1` indicates _high demand_. + +## Codebyte Example + +The following codebyte example trains a Random Forest classifier for multilabel classification on synthetic data and +predicts the quality and demand for a new product. + +```codebyte/python +from sklearn.ensemble import RandomForestClassifier +from sklearn.datasets import make_multilabel_classification + +# Generate example data for multitask classification +X, y = make_multilabel_classification(n_samples=100, n_features=10, n_classes=2, n_labels=1, random_state=42) + +# Create and train the model +model = RandomForestClassifier(random_state=42) +model.fit(X, y) + +# New product data to predict +new_product = [[0.6, 1.5, -0.2, 0.9, 2.0, -1.1, 1.3, 0.6, 1.2, -0.8]] + +# Predict the quality and demand for the new product +predictions = model.predict(new_product) + +print("Predicted labels (Quality, Demand):", predictions) +``` diff --git a/content/sklearn/concepts/naive-bayes/naive-bayes.md b/content/sklearn/concepts/naive-bayes/naive-bayes.md index 451da49d28b..30ffdc8f22c 100644 --- a/content/sklearn/concepts/naive-bayes/naive-bayes.md +++ b/content/sklearn/concepts/naive-bayes/naive-bayes.md @@ -23,3 +23,71 @@ Typically, a preprocessed dataset is divided into training and testing sets. The - **Categorical Naive Bayes**: Designed for features that can be separated into distinct categories (e.g., predicting a person’s favorite sport based on gender and preferred weather). - **Gaussian Naive Bayes**: Designed for continuous features. It assumes that features follow a Gaussian distribution curve and determines the most likely class for an instance by calculating the probability of each class. - **Complement Naive Bayes**: Designed to address the limitations of the standard Multinomial Naive Bayes classifier when dealing with imbalanced datasets. Imbalanced datasets are those where some classes have significantly more examples than others. + +## Example + +```py +import numpy as np +from sklearn.naive_bayes import GaussianNB +from sklearn.model_selection import train_test_split +from sklearn.metrics import accuracy_score + +# Create random dataset for classification +n = 100 # 100 data points +X = 6 * np.random.rand(n, 2) - 3 # 2 features +y = (X[:, 0] + X[:, 1] > 1).astype(int) # Class labels based on sum of features + +# 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) + +# Instantiate the Naive Bayes model +model = GaussianNB() + +# Fit the model to the training data +model.fit(X_train, y_train) + +# Predict the labels for the test data +y_prediction = model.predict(X_test) + +# Print predicted values +print("Predicted Labels: ", y_prediction) +``` + +Here is the output for the above example: + +```shell +Predicted Labels: [1 0 0 0 1 0 1 0 0 0 1 0 1 0 1 1 0 0 1 1 0 0 0 1 1 0 1 0 1 0] +``` + +## Codebyte Example + +The following codebyte example demonstrates the use of a random dataset for classification using the Naive-Bayes model: + +```codebyte/python +import numpy as np +from sklearn.naive_bayes import GaussianNB +from sklearn.model_selection import train_test_split +from sklearn.metrics import accuracy_score + +# Create random dataset for classification +n = 100 # 100 data points +X = 6 * np.random.rand(n, 2) - 3 # 2 features +y = (X[:, 0] + X[:, 1] > 1).astype(int) # Class labels based on sum of features + +# 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) + +# Instantiate the Naive Bayes model +model = GaussianNB() + +# Fit the model to the training data +model.fit(X_train, y_train) + +# Predict the labels for the test data +y_prediction = model.predict(X_test) + +# Print predicted values and accuracy +print("Predicted Labels: ", y_prediction) +``` + +> Note: The output predictions will vary due to the random generation of training data and noise in the model. diff --git a/content/sklearn/concepts/support-vector-machines/support-vector-machines.md b/content/sklearn/concepts/support-vector-machines/support-vector-machines.md index 7d0f9a1a490..0bbcd69cf40 100644 --- a/content/sklearn/concepts/support-vector-machines/support-vector-machines.md +++ b/content/sklearn/concepts/support-vector-machines/support-vector-machines.md @@ -82,3 +82,28 @@ The output of the above code will be: ```shell Predicted class: 1 ``` + +## Codebyte Example + +This codebyte example demonstrates the use of a Support Vector Classifier (SVC) with a +linear kernel on a synthetic two-class dataset and predicts the class of a new data point: + +```codebyte/python +from sklearn.svm import SVC +from sklearn.datasets import make_blobs + +# Generate sample data with two classes +X, y = make_blobs(n_samples=500, centers=2, random_state=0, cluster_std=0.6) + +# Define and train the SVC model +model = SVC(kernel='linear', C=1.0) +model.fit(X, y) + +# New data point to predict +new_data = [[5, 1.5]] + +# Predict the class of the new data +prediction = model.predict(new_data) + +print("Predicted class:", prediction[0]) +``` diff --git a/content/sql/concepts/commands/terms/pivot/pivot.md b/content/sql/concepts/commands/terms/pivot/pivot.md new file mode 100644 index 00000000000..50bc1ebb674 --- /dev/null +++ b/content/sql/concepts/commands/terms/pivot/pivot.md @@ -0,0 +1,46 @@ +--- +Title: 'PIVOT' +Description: 'Transforms rows of a table into columns.' +Subjects: + - 'Data Science' + - 'Computer Science' +Tags: + - 'Database' + - 'Queries' + - 'Aggregate Functions' + - 'SQL Server' +CatalogContent: + - 'learn-sql' + - 'paths/analyze-data-with-sql' +--- + +In SQL, the **`PIVOT`** command transforms rows of a table into columns. + +## Syntax + +```pseudo +SELECT column1, column2, ... +FROM table +PIVOT + ( + aggregate_function(column_to_be_aggregated) + FOR pivot_column IN (pivot_column_values) + ) AS alias_name; +``` + +- `alias_name`: The temporary name for the newly created pivot table. + +## Example + +The below example shows a table `transactions` containing three columns `customer_name`, `book_genre`, and `price`. Each row represents a transaction at a bookstore. The query below creates a temporary pivot table named `pivot_table` with columns `customer_name`, `scifi`, and `romance`. In this table, each row represents the aggregate price that the customers paid for books in each of these genres: + +```sql +SELECT + customer_name, + scifi, + romance +FROM + transactions PIVOT ( + SUM(price) FOR book_genre IN (scifi, romance) + ) AS pivot_table; +``` diff --git a/content/sql/concepts/commands/terms/rollback/rollback.md b/content/sql/concepts/commands/terms/rollback/rollback.md new file mode 100644 index 00000000000..70034e81ca8 --- /dev/null +++ b/content/sql/concepts/commands/terms/rollback/rollback.md @@ -0,0 +1,133 @@ +--- +Title: 'ROLLBACK' +Description: 'Undoes any work performed in the current transaction. It can also be used to undo work performed by in-doubt transactions.' +Subjects: + - 'Data Science' +Tags: + - 'Database' + - 'Documentation' + - 'Functions' + - 'Queries' +CatalogContent: + - 'learn-sql' + - 'paths/analyze-data-with-sql' +--- + +In SQL, the **`ROLLBACK`** command undoes work performed in the current transaction to a savepoint or to the last commit to the database. A SQL transaction is a series of one or more SQL statements in the current session. + +Therefore, the rollback procedure allows a user to undo the work to a previous point without applying these statements to the database. + +> Note: To learn more about how to start and commit a transaction, check out the [MySQL documentation](https://dev.mysql.com/doc/refman/8.4/en/commit.html). + +## Syntax + +```pseudo +ROLLBACK [WORK] [TO SAVEPOINT savepoint_name]; +``` + +- `TO SAVEPOINT savepoint_name`: Resets the database to an established savepoint `savepoint_name` within the current transaction. These savepoint names can be created using the command `SAVEPOINT savepoint_name`. + +### Rollback Current Transaction + +The following syntax can be used to undo any changes in the current transaction: + +```pseudo +ROLLBACK; +-- Or, for compatibility with some SQL standards: +ROLLBACK WORK; +``` + +### Rollback Current Transaction to Savepoint + +To rollback to a specific savepoint, the following syntax can be used: + +```pseudo +ROLLBACK [WORK] TO SAVEPOINT savepoint_name; +``` + +> Note: Certain statements cannot be rolled back once performed, such as creating, dropping, or altering tables and databases. For more info, check out the [MySQL documentation](https://dev.mysql.com/doc/refman/8.4/en/cannot-roll-back.html). + +## Example + +Here is a table `table_1` containing the following data: + +| id | dob | name | +| --- | ---------- | ---------------- | +| 1 | 11/16/2001 | Jolly Old Chap | +| 2 | 1/12/2000 | Jolly Young Chap | + +Next, the following code is used to fix Young Chap's birthday and make him younger than Old Chap: + +```sql +UPDATE table_1 +SET dob = "1/21/2024"; +SELECT * FROM table_1; +``` + +This gives the following as the output: + +| id | dob | name | +| --- | --------- | ---------------- | +| 1 | 1/21/2024 | Jolly Old Chap | +| 2 | 1/21/2024 | Jolly Young Chap | + +However, the above output suggests that everyone's birthday has been accidentally set to `1/21/2024`. + +To fix that, the following code is used to rollback the transaction and update the birthday correctly: + +```sql +ROLLBACK; +UPDATE table_1 +SET dob = "1/21/2024" +WHERE id = 2; +SELECT * FROM table_1; +``` + +This gives the following as the output: + +| id | dob | name | +| --- | ---------- | ---------------- | +| 1 | 11/16/2001 | Jolly Old Chap | +| 2 | 1/21/2024 | Jolly Young Chap | + +Finally, the following code adds another chap to the database and then rolls back the addition: + +```sql +-- Create a savepoint, in case another error is made +SAVEPOINT first; + +-- Add a new chap +INSERT INTO table_1 (name,dob) + VALUES ("Jolly Medium Chap","3/22/2012"); +SELECT name FROM table_1 WHERE id=3; + +-- Gives "Jolly Medium Chap" + +-- Create a new savepoint +SAVEPOINT second; + +-- Change the name +UPDATE table_1 + SET name = "Jolly Rancher" + WHERE id=3; +SELECT name FROM table_1 WHERE id=3; + +-- Gives "Jolly Rancher" + +-- The original name feels better. So, let's go ahead and rollback. +ROLLBACK TO SAVEPOINT second; +SELECT name FROM table_1 WHERE id=3; + +-- Gives "Jolly Medium Chap" + +-- There is no need of the new chap anymore. Let's just go back to the save with just two chaps. +ROLLBACK TO SAVEPOINT first; +SELECT * FROM table_1; +``` + +This would output the following table: + +| id | dob | name | +| --- | ---------- | ---------------- | +| 1 | 11/16/2001 | Jolly Old Chap | +| 2 | 1/21/2024 | Jolly Young Chap | diff --git a/content/sql/concepts/dates/terms/between/between.md b/content/sql/concepts/dates/terms/between/between.md new file mode 100644 index 00000000000..c17ceaf6bc0 --- /dev/null +++ b/content/sql/concepts/dates/terms/between/between.md @@ -0,0 +1,54 @@ +--- +Title: 'BETWEEN' +Description: 'Returns records where a specified value is within a given range, including the boundary values.' +Subjects: + - 'Computer Science' + - 'Data Science' +Tags: + - 'Database' + - 'Date' + - 'Queries' + - 'SQL Server' +CatalogContent: + - 'learn-sql' + - 'paths/analyze-data-with-sql' +--- + +The **`BETWEEN`** [operator](https://www.codecademy.com/resources/docs/sql/operators) finds values within a given range. The values can be texts, dates, or numbers. Also, this operator is inclusive, i.e., both beginning and ending values are included. + +## Syntax + +```pseudo +SELECT column_name(s) +from table_name +where column_name between value1 and value2; +``` + +> Note: The basic syntax for `BETWEEN` is generally the same across most databases, but some differences may arise depending on how each database handles specific [data types](https://www.codecademy.com/resources/docs/sql/data-types) or expressions. To use this operator on a particular database, data handling, null handling, case sensitivity, and collations must be checked first to avoid errors. + +## Example + +Suppose there’s a `order_details` table with the following data: + +| order_id | item | price | quantity | order_date | +| -------- | ------------ | ----- | -------- | ------------------- | +| 1 | Donut | 2.49 | 2 | 2022-08-16 08:04:23 | +| 2 | Cookie | 0.99 | 3 | 2022-08-21 09:43:00 | +| 3 | Donut | 2.49 | 1 | 2022-08-18 11:25:12 | +| 4 | Egg Sandwich | 7.99 | 1 | 2022-08-20 11:45:41 | +| 5 | Ice Coffee | 3.99 | 2 | 2022-08-17 12:18:50 | + +Here is a query using the `BETWEEN` operator: + +```sql +SELECT * FROM order_details WHERE order_date BETWEEN '2022-08-15' AND '2022-08-19'; +``` + +This would return all records from the `order_details` table, where the `order_date` is between August 15, 2022 +and August 19, 2022 (inclusive): + +| order_id | item | price | quantity | order_date | +| -------- | ---------- | ----- | -------- | ------------------- | +| 1 | Donut | 2.49 | 2 | 2022-08-16 08:04:23 | +| 3 | Donut | 2.49 | 1 | 2022-08-18 11:25:12 | +| 5 | Ice Coffee | 3.99 | 2 | 2022-08-17 12:18:50 | diff --git a/content/sql/concepts/operators/terms/iff/iff.md b/content/sql/concepts/operators/terms/iff/iff.md new file mode 100644 index 00000000000..15b967ae942 --- /dev/null +++ b/content/sql/concepts/operators/terms/iff/iff.md @@ -0,0 +1,70 @@ +--- +Title: 'IIF' +Description: ' Performs inline conditional checks within SELECT statements to return different values based on a condition.' +Subjects: + - 'Code Foundations' + - 'Computer Science' +Tags: + - 'Operators' + - 'Database' + - 'Data' + - 'Conditionals' +CatalogContent: + - 'learn-sql' + - 'paths/analyze-data-with-sql' +--- + +The **`IFF`** function in SQL is used to perform a conditional evaluation and return one of two values based on the result of a specified condition. It is similar to the ternary operator (condition ? true_value : false_value) found in many programming languages. + +## Syntax + +```pseudo +IIF(condition, value_if_true, value_if_false) +``` + +- `condition`: The condition to be evaluated. +- `value_if_true`: The value to be returned if the condition is true. +- `value_if_false`: The value to be returned if the condition is false. + +## Usage + +The **`IFF`** function is particularly useful for inline conditional logic within SQL queries. It allows you to embed simple conditional checks directly within SELECT, WHERE, ORDER BY, and other clauses. + +## Example + +The following example demonstrates the use of the `IF` function to label stock prices as `High` or `Low`: + +```sql +# Create a table named 'employees' and categorize their salaries as high or moderate using the 'IIF' function + +CREATE TABLE employees ( + employee_id INT PRIMARY KEY, + name VARCHAR(100), + salary DECIMAL(10, 2) +); + +INSERT INTO employees (employee_id, name, salary) VALUES +(1, 'Alice', 45000), +(2, 'Bob', 55000), +(3, 'Charlie', 70000), +(4, 'Diana', 30000), +(5, 'Edward', 85000); + +SELECT + name, + salary, + IIF(salary > 60000, 'High Salary', 'Moderate Salary') AS salary_category +FROM + employees; +``` + +The output of the `SELECT` statement will be: +| name | salary | salary_category | +| --------- | ------- | -------------- | +| Alice | 45000 | Moderate Salary | +| Bob | 55000 | Moderate Salary | +| Charlie | 70000 | High Salary | +| Diana | 30000 | Moderate Salary | +| Edward | 85000 | High Salary | + +The `IIF` function checks if the salary is greater than `60000`. If true, it assigns `High Salary` to the `salary_category`. Otherwise, it assigns `Moderate Salary`. diff --git a/content/sql/concepts/operators/terms/similar-to/similar-to.md b/content/sql/concepts/operators/terms/similar-to/similar-to.md new file mode 100644 index 00000000000..cb7d52e8f2a --- /dev/null +++ b/content/sql/concepts/operators/terms/similar-to/similar-to.md @@ -0,0 +1,95 @@ +--- +Title: 'SIMILAR TO' +Description: 'Used to compare a string to a regular expression' +Subjects: + - 'Data Science' + - 'Computer Science' +Tags: + - 'Operators' + - 'Database' + - 'Queries' + - 'PostgreSQL' +CatalogContent: + - 'learn-sql' + - 'paths/analyze-data-with-sql' +--- + +The **`SIMILAR TO`** operator is primarily found in `PostgreSQL`. It returns `TRUE` if its pattern matches the given string; otherwise, it returns `FALSE`. This operator is similar to the `LIKE` operator used in other databases, such as SQL Server, MySQL, and Oracle SQL, and supports pattern matching via the use of [wildcards](https://www.codecademy.com/resources/docs/sql/wildcards). + +## Syntax + +`SIMILAR TO` is typically used conditionally with a `WHERE` clause to select rows based on a column matching a given string pattern. + +```pseudo +SELECT * +FROM table_name +WHERE column_name SIMILAR TO pattern; +``` + +The `pattern` here constitutes a string that includes the following wildcards: + +- `%`: Matches zero or more arbitrary characters. +- `_`: Matches exactly one arbitrary character. + +## Example 1 + +The following example selects every country from the `countries` table where the name starts with "M": + +```sql +SELECT * +FROM countries +WHERE country_name SIMILAR TO 'M%'; +``` + +Explanation: + +- `M`: The name must start with the letter "M". +- `%`: Matches zero or more characters after "M". + +Example Matches: + +- Mexico +- Malaysia + +## Example 2 + +The following example selects every `employee` from the `employees` table whose name starts with either `John` or `Jane`: + +```sql +SELECT * +FROM employees +WHERE name SIMILAR TO '(John|Jane)%'; +``` + +Explanation: + +- `(John|Jane)`: The name must start with either "John" or "Jane". +- `%`: Matches zero or more characters after "John" or "Jane". + +Example Matches: + +- Johnathan +- John Smith + +## Example 3 + +The following example selects `employees` whose name is either `John` or `Jane`, followed by a middle initial and a period: + +```sql +SELECT * +FROM employees +WHERE name SIMILAR TO '(John|Jane)_[A-Z].%'; +``` + +Explanation: + +- `(John|Jane)`: The name must start with either "John" or "Jane". +- `_`: Matches exactly one arbitrary character (in this case, a space or any other single character). +- `[A-Z]`: Matches a single uppercase letter, representing a middle initial. +- `.`: Matches a literal period (used after the middle initial). +- `%`: Matches zero or more characters after the period, such as a last name or other additional characters. + +Example Matches: + +- John A. Smith +- Jane B. Doe diff --git a/content/typescript/concepts/utility-types/utility-types.md b/content/typescript/concepts/utility-types/utility-types.md new file mode 100644 index 00000000000..71cf9db7435 --- /dev/null +++ b/content/typescript/concepts/utility-types/utility-types.md @@ -0,0 +1,224 @@ +--- +Title: 'Utility Types' +Description: 'Helps in working with data types more efficiently.' +Subjects: + - 'Web Development' + - 'Code Foundations' + - 'Computer Science' +Tags: + - 'Utility Types' + - 'Data Types' + - 'TypeScript' +CatalogContent: + - 'learn-typescript' + - 'paths/full-stack-engineer-career-path' +--- + +TypeScript consists of several predefined generic types known as **Utility Types**. These utility types are useful for manipulating or creating new types more efficiently. + +## Partial + +Partial is a utility type that is used to create a type where all properties are marked as optional. + +### Syntax + +A partial is written as: + +```pseudo +Partial; +``` + +Where `T` is the typo you want to make all the properties optional. + +### Partial Example + +In this example, all the properties of the `User` interface are optional: + +```ts +interface User { + name: string; + age: number; + email: string; +} + +const partialUser: Partial = { + name: 'John', +}; +``` + +## Required + +`Required` is a utility type that is used to create a type with all properties of `T` marked as `Required`. It is the opposite of `Partial`. + +### Syntax + +`Required` in Typescript is written as: + +```pseudo +Required; +``` + +Where `T` is the typo you want to make all the properties mandatory. + +### Required Example + +In this example, all the properties of the `User` interface (including the optional properties) are made mandatory: + +```ts +interface User { + name: string; + age?: number; +} + +const requiredUser: Required<{ name: string; age: number }> = { + name: 'John', + age: 25, +}; +``` + +## Readonly + +`Readonly` is a utility type that marks all the properties in `T` as `readonly`, preventing any reassignment. + +### Syntax + +`Readonly` is written as: + +```pseudo +Readonly; +``` + +Where properties of `T` is marked as `Readonly`. + +### Readonly Example + +In this example, attempting to reassign the value of `readonlyUser.age` generates an error: + +```ts +interface User { + name: string; + age: number; +} + +const readonlyUser: Readonly = { + name: 'John', + age: 30, +}; + +readonlyUser.age = 31; // Error: Cannot assign to 'age' because it is a read-only property. +``` + +## Pick + +Pick allows you to create a new type by selecting a set of properties `K` from an existing type `T`. + +### Syntax + +Pick is written as: + +```pseudo +Pick; +``` + +where `K` are the properties you want to include from `T`. + +### Pick Example + +In this example, `Pick` is used to create a type from `User` that includes only the `name` and `email` fields, omitting `age`, without needing to declare a new interface: + +```ts +interface User { + name: string; + age: number; + email: string; +} + +const pickedUser: Pick = { + name: 'John', + email: 'john@example.com', +}; +``` + +## Omit + +Omit allows you to create a new type by excluding a set of properties `K` from an existing type `T`. + +### Syntax + +Omit is written as: + +```pseudo +Omit; +``` + +where `K` properties are omitted from `T`. + +### Omit Example + +In this example, we removed the `age` property from the `User` interface: + +```ts +interface User { + name: string; + age: number; + email: string; +} + +const omittedUser: Omit = { + name: 'John', + email: 'john@example.com', +}; +``` + +## Record + +Record helps you give cleaner type to `objects`. + +### Syntax + +Record is written as: + +```pseudo +Record; +``` + +where `K` represents the keys and `T` represents the values. + +### Record Example + +In this example, it ensures that the keys are `strings` and the values are `numbers`. + +```ts +type Users = Record; + +const userRoles: Users = { + admin: 1, + user: 2, + guest: 3, +}; +``` + +## Exclude + +Excludes from `T` those types that are assignable to `U`. + +### Syntax + +Exclude is written as: + +```pseudo +Exclude; +``` + +where `U` represents the types you want to exclude from the union type`T`. + +### Exclude Example + +In this example, we exclude `apple` and `banana` from the union type, resulting in just `orange`: + +```ts +type fruits = 'apple' | 'banana' | 'orange'; +type ExcludedFruits = Exclude; // "orange" +``` + +These utility types make managing and transforming types easier, helping you write cleaner and safer code. diff --git a/documentation/content-standards.md b/documentation/content-standards.md index b79ee50af9c..d71335317b9 100644 --- a/documentation/content-standards.md +++ b/documentation/content-standards.md @@ -115,4 +115,4 @@ Review the [Docs Style Guide](https://github.com/Codecademy/docs/blob/main/docum Check out the [concept entry template](https://github.com/Codecademy/docs/blob/main/documentation/concept-entry-template.md) and [term entry template](https://github.com/Codecademy/docs/blob/main/documentation/term-entry-template.md) in this folder. And take a look at [GitHub Issues](https://github.com/Codecademy/docs/issues) to see where help is needed! -For a refresher on how to make a Pull Request, head back to the [Contribution Guide](https://github.com/Codecademy/docs/blob/main/.github/CONTRIBUTING.md). 🎒 +For a refresher on how to make a Pull Request, head back to the [Contribution Guide](https://github.com/Codecademy/docs/blob/main/CONTRIBUTING.md). 🎒 diff --git a/documentation/tags.md b/documentation/tags.md index 0f10830b744..91dc120814d 100644 --- a/documentation/tags.md +++ b/documentation/tags.md @@ -356,6 +356,7 @@ Units Unix Unsupervised Learning URL +Utility Types UX Validation Values diff --git a/media/3d-surface-example-plotly.png b/media/3d-surface-example-plotly.png new file mode 100644 index 00000000000..9acd5f18314 Binary files /dev/null and b/media/3d-surface-example-plotly.png differ diff --git a/media/css-position-absolute-ex1.png b/media/css-position-absolute-ex1.png new file mode 100644 index 00000000000..78092f507f8 Binary files /dev/null and b/media/css-position-absolute-ex1.png differ diff --git a/media/css-position-absolute-ex2.png b/media/css-position-absolute-ex2.png new file mode 100644 index 00000000000..051eb3c0dd8 Binary files /dev/null and b/media/css-position-absolute-ex2.png differ diff --git a/media/css-position-relative-ex1.png b/media/css-position-relative-ex1.png new file mode 100644 index 00000000000..80c5f4d434a Binary files /dev/null and b/media/css-position-relative-ex1.png differ diff --git a/media/css-position-relative-ex2.png b/media/css-position-relative-ex2.png new file mode 100644 index 00000000000..5b83471a261 Binary files /dev/null and b/media/css-position-relative-ex2.png differ diff --git a/media/plotly-express-funnel-example1.png b/media/plotly-express-funnel-example1.png new file mode 100644 index 00000000000..b347877f3bf Binary files /dev/null and b/media/plotly-express-funnel-example1.png differ diff --git a/media/plotly-express-funnel-example2.png b/media/plotly-express-funnel-example2.png new file mode 100644 index 00000000000..24073624441 Binary files /dev/null and b/media/plotly-express-funnel-example2.png differ diff --git a/media/plotlyScatter3dOutput1.png b/media/plotlyScatter3dOutput1.png new file mode 100644 index 00000000000..e7627b8b061 Binary files /dev/null and b/media/plotlyScatter3dOutput1.png differ diff --git a/media/plotlyScatter3dOutput2.png b/media/plotlyScatter3dOutput2.png new file mode 100644 index 00000000000..56e1a040a99 Binary files /dev/null and b/media/plotlyScatter3dOutput2.png differ diff --git a/media/position-fixed-example.png b/media/position-fixed-example.png new file mode 100644 index 00000000000..4e0c734ec1b Binary files /dev/null and b/media/position-fixed-example.png differ diff --git a/media/position-static-example.png b/media/position-static-example.png new file mode 100644 index 00000000000..9d5c27633ca Binary files /dev/null and b/media/position-static-example.png differ diff --git a/media/sklearn-label-propagation.png b/media/sklearn-label-propagation.png new file mode 100644 index 00000000000..5c23d5fdb19 Binary files /dev/null and b/media/sklearn-label-propagation.png differ