717. 1-bit and 2-bit Characters

We have two special characters: The first character can be represented by one bit 0. The second character can be represented by two bits (10 or 11). Given a binary array bits that ends with 0, return true if the last character must be a one-bit character.
/**
 * @param {number[]} bits
 * @return {boolean}
 */
var isOneBitCharacter = function(bits) {
    // Start from the first bit
    let i = 0;

    // Traverse until the second-to-last bit
    // (because the last bit is always 0, we want to see if it's consumed or not)
    while (i < bits.length - 1) {
        if (bits[i] === 1) {
            // If we see a '1', it must form a two-bit character (10 or 11)
            // So we skip TWO positions
            i += 2;
        } else {
            /

Project folder file structure

import os
from pathlib import Path

# -------------------------
# Define project name (main package)
# -------------------------
project_name = "src"  # More descriptive than "src"

# -------------------------
# Define additional folders
# -------------------------
cicd_folder       = "Github"
configs_folder    = "configs"
data_folder       = "data"
notebooks_folder  = "notebooks"
static_css_folder = "static/css"
templates_folder  = "templates"
tests_folder      = "tests"
scrip

Chatbot

print("Hello")
import os
from dotenv import load_dotenv
from langchain_openai import ChatOpenAI
from langchain_classic.chains import ConversationChain
from langchain_classic.memory import ConversationBufferMemory
from langchain_classic.prompts import ChatPromptTemplate, MessagesPlaceholder
from langchain_classic.schema import SystemMessage,HumanMessage
# Load environment variables
load_dotenv()
openai_api_key = os.getenv("OPENAI_API_KEY"
if not openai_api_key:
    raise ValueError("O

LangChain Core Package


## Messages

from langchain.core.messages import (
    AIMessage,
    AIMessageChunk,
    BaseMessage,
    BaseMessageChunk,
    HumanMessage,
    HumanMessageChunk,
    SystemMessage,
    SystemMessageChunk,
    ToolMessage,
    ToolMessageChunk,
    FunctionMessage,
    FunctionMessageChunk,
)

  ## Prompts
  
  from langchain.core.prompts import (
    PromptTemplate,
    ChatPromptTemplate,
    SystemMessagePromptTemplate,
    HumanMessagePromptTemplate,
    AIMessag

Chatbot Prompt

🚀 Project Prompt: Build a Smart End-to-End Chatbot
🧩 Objective
Design and implement a robust, modular, and intelligent chatbot system using modern AI and web technologies. The chatbot should be capable of handling dynamic conversations, storing history, and providing a clean user interface.
🛠️ Tech Stack

🧠 Brain: LangChain + OpenAI (for LLM orchestration and prompt management)
⚙️ Backend: FastAPI (for serving the chatbot API)
💬 Frontend: Streamlit (for interactive chat UI)
🔒 Security: .

Correlation Matrix

import pandas as pd
import seaborn as sns
import matplotlib.pyplot as plt

# Load your dataset
df = pd.read_csv("your_data.csv")  # Replace with your actual file

# Compute correlation matrix
corr_matrix = df.corr(numeric_only=True)

# Plot heatmap
plt.figure(figsize=(10, 8))
sns.heatmap(corr_matrix, annot=True, fmt=".2f", cmap="coolwarm", linewidths=0.5)
plt.title("Correlation Heatmap")
plt.tight_layout()
plt.show()

Pandas

final_df = pd.concat([
    temperature_humidity[['time', 'day_temperature_C', 'day_humidity_percent',
                          'dayofweek_sin', 'dayofweek_cos',
                          'dayofmonth_sin', 'dayofmonth_cos',
                          'dayofyear_sin', 'dayofyear_cos']],
    daily_counts[['COUNT']].rename(columns={'COUNT': 'complaint_count'})
], axis=1)

remove_outliers_iqr

import pandas as pd

# Sample data
data = {'temperature': [22, 23, 21, 24, 100, 22, 23, 25, 20, 21]}
df = pd.DataFrame(data)

# Function to remove outliers using IQR
def remove_outliers_iqr(df, column):
    Q1 = df[column].quantile(0.25)
    Q3 = df[column].quantile(0.75)
    IQR = Q3 - Q1
    lower_bound = Q1 - 1.5 * IQR
    upper_bound = Q3 + 1.5 * IQR
    return df[(df[column] >= lower_bound) & (df[column] <= upper_bound)]

# Call the function
df_clean = remove_outliers_iqr(df

Model Visualization

import matplotlib.pyplot as plt
import seaborn as sns

# List of columns to plot
columns_to_plot = [
    'day_temperature_C', 'day_humidity_percent', 'complaint_count',
    'dayofweek_sin', 'dayofweek_cos',
    'dayofmonth_sin', 'dayofmonth_cos',
    'dayofyear_sin', 'dayofyear_cos'
]

# Loop through each column and plot KDE
for col in columns_to_plot:
    plt.figure(figsize=(10, 6))
    sns.kdeplot(df[col], shade=True, color='purple')
    plt.title(f'Density Plot of {col}')
    

MinMaxScaler

import pandas as pd
from sklearn.preprocessing import MinMaxScaler

# Example dataset (replace this with your own DataFrame)
df = pd.DataFrame({
    'temp_max_C': [25, 30, 35, 40],
    'precip_mm': [0.0, 5.0, 10.0, 50.0],
    'wind_speed_max_m_s': [2.5, 5.0, 7.5, 10.0],
    'day_of_week_sin': [0.5, 0.7, -0.3, -0.9]  # example of other feature
})

# Columns to scale
scale_cols = ['temp_max_C', 'precip_mm', 'wind_speed_max_m_s']

# Initialize scaler
scaler = MinMaxScaler()

# Fit 

boxplot

import matplotlib.pyplot as plt

# Create box plot
plt.figure(figsize=(14, 6))  # Optional: enlarge canvas
plt.boxplot(new_df['Power_Load_kW'], patch_artist=True, boxprops=dict(facecolor='lightblue', color='blue'),
            medianprops=dict(color='red'), whiskerprops=dict(color='black'),
            capprops=dict(color='black'), flierprops=dict(marker='o', color='orange', alpha=0.5))

# Add title and labels
plt.title('Box Plot Example', fontsize=16)
plt.ylabel('Value', fontsize=14)

train_test_split

# Separate features (X) and target (y)
X = df.drop(columns=['complaint_count'])
y = df['complaint_count']
# Split data into train and test sets (80-20 split)
train_size = int(len(df) * 0.8)
y_train, y_test = y[:train_size], y[train_size:]
X_train, X_test = X[:train_size], X[train_size:]
# Print shapes
print("X_train shape:", X_train.shape)
print("X_test shape:", X_test.shape)
print("y_train shape:", y_train.shape)
print("y_test shape:", y_test.shape)
print(f"Training set size: {len(y

LSTM

import numpy as np
from sklearn.model_selection import train_test_split

# ============================================
# TRAIN–TEST SPLIT
# ============================================

# Define features (X) and target (y)
X = new_df.drop(columns=['Power_Load_kW'])   # Feature columns
y = new_df['Power_Load_kW']                  # Target column


# ----- STEP 1: Create sequences for LSTM -----
# Create sequences for LSTM
def create_sequences(X, y, seq_length=7):
    X_seq, y_seq 

seaborn.kdeplot

plt.figure(figsize=(10, 6))
sns.kdeplot(filtered_data['Complaint_Count'], shade=True, color='purple')
plt.title('Density Plot of Complaint_Count')
plt.xlabel('Complaint_Count')
plt.ylabel('Density')
plt.grid(True)
plt.show()

----------------------------------------------------------------------------------------------------

import matplotlib.pyplot as plt
import seaborn as sns

# List of columns to plot
columns_to_plot = ['hour_sin', 'hour_cos', 'dayofweek_sin',
       'dayofwee

scatter plot

# Create scatter plot
plt.figure(figsize=(14, 6))  # Optional: enlarge canvas
plt.scatter(new_df['Power_Load_kW'], new_df['Temperature_C'], color='blue', marker='o', s=100, edgecolors='black')

# Add labels and title
plt.xlabel('X-axis Label')
plt.ylabel('Y-axis Label')
plt.title('Simple Scatter Plot')

# Show plot
plt.grid(True)
plt.show()

data checking

import pandas as pd
import numpy as np

def process_data(path, key_columns=None, impute_strategy='median'):
    df = pd.read_csv(path)

    # Core Data Check / Validation
    print("🔍 Core Data Validation")
    print("Shape:", df.shape)
    print("Data Types:\n", df.dtypes)
    print("Missing Values:\n", df.isnull().sum())
    print("Duplicate Rows:", df.duplicated().sum())

    if key_columns:
        for col in key_columns:
            if col in df.columns:
                prin