Snippets Collections
>>> import jmespath
>>> path = jmespath.search('foo.bar', {'foo': {'bar': 'baz'}})
'baz'
 #include <stdio.h>

int main() {
    int N;
    scanf("%d", &N);
    for (int i = 1; i <= N; i++) {
        int n;
        scanf("%d", &n);
        while (n > 0) {
            int digit = n % 10;
            printf("%d ", digit);
            n = n / 10;
        }
        printf("\n");
    }
    return 0;
}
[HKEY_CURRENT_USER\Software\Policies\Microsoft\Windows\WindowsCopilot]
"TurnOffWindowsCopilot"=dword:00000001

[HKEY_LOCAL_MACHINE\SOFTWARE\Policies\Microsoft\Windows\WindowsCopilot]
"TurnOffWindowsCopilot"=dword:00000001

#Add or Remove Copilot Button on Taskbar in Windows 11

[HKEY_CURRENT_USER\Software\Microsoft\Windows\CurrentVersion\Explorer\Advanced]
"ShowCopilotButton"=dword:00000000
function redirect_non_admin_users_to_frontend() {
$current_user = wp_get_current_user();
$allowed_roles = array('administrator', 'editor', 'author', 'contributor', 'shop_manager');

if (!array_intersect($allowed_roles, $current_user->roles)) {
wp_redirect(site_url('/'));
exit;
}
}

add_action('admin_init', 'redirect_non_admin_users_to_frontend');
#include <iostream>
using namespace std;

int main()
{
    int n;
    int m;

    std::cout << "Enter desired max of the array: " << endl;
    cin >> n;
    cin >> m;

    int* arr = new int [n * m]; // создание размерности матрицы из данных с клавиатуры
    
    for (int i = 0; i < n * m; ++i) {
        cin >> arr[i];
    }

    for (int i = 0; i < n * m; i++) {
        for (int j = 0; j < n * m - 1; j++) {
            if (arr[j] > arr[j + 1]) {

                arr[j] += arr[j + 1];
                arr[j + 1] = arr[j] - arr[j + 1];
                arr[j] = arr[j] - arr[j + 1];

            }
        }
    }

    int matrix[20][20];
    bool b_matrix[20][20];
    for (int i = 0; i < 20; ++i)
        for (int j = 0; j < 20; ++j)
            b_matrix[i][j] = false;

    int speed_x = 1;
    int speed_y = 0;
    int x = 0, y = 0;
    int turn_counter = 0;
}
for (int i = 0; i < n * m; ++i) {
        matrix[x][y] = arr[i];
        b_matrix[x][y] = true;

        if (b_matrix[x + speed_x][y + speed_y] or (0 > speed_x + x or speed_x + x > n - 1) or (0 > speed_y + y or speed_y + y > m - 1)) {
            turn_counter += 1;
            switch (turn_counter % 4)
            {
            case 1:
            {
                speed_x = 0;
                speed_y = 1;
                break;
            }
            case 2:
            {
                speed_x = -1;
                speed_y = 0;
                break;
            }
            case 3:
            {
                speed_x = 0;
                speed_y = -1;
                break;
            }
            case 0:
            {
                speed_x = 1;
                speed_y = 0;
                break;
            }
            default:
                break;
            }
        }
        x += speed_x;
        y += speed_y;

    }

    for (int i = 0; i < n; ++i) {
        for (int j = 0; j < m; ++j) {
            cout << matrix[j][i] << " ";
        }
        cout << endl;
    }

    return 0;
#Try from admin cmd
#Code:
rd /s /q \\?\C:\.cache

#Will not work if files are currently in use
#include <bits/stdc++.h>
using namespace std;

void dfs(int node, int start, int& timeCounter, vector<vector<int>>& Dsachke, vector<int>& Found, vector<int>& Lowest, vector<pair<int, int>>& BRIDGES) {
    Found[node] = Lowest[node] = timeCounter++;

    cout << "Đang thăm node: " << node << ", timeCounter: " << timeCounter << ", Found[" << node << "]: " << Found[node] << ", Lowest[" << node << "]: " << Lowest[node] << endl;

    for (int neighbor : Dsachke[node]) {
        if (neighbor == start) {
            continue;  // Bỏ qua đỉnh cha
        }
        
        if (Found[neighbor] != -1) {  // Đỉnh đã được thăm
            Lowest[node] = min(Lowest[node], Found[neighbor]);
            cout << "Thăm lại neighbor: " << neighbor << ", Found[" << neighbor << "]: " << Found[neighbor] << ", cập nhật Lowest[" << node << "]: " << Lowest[node] << endl;
        } 
        else {  // Đỉnh chưa được thăm
            dfs(neighbor, node, timeCounter, Dsachke, Found, Lowest, BRIDGES);
            Lowest[node] = min(Lowest[node], Lowest[neighbor]);

            cout << "Quay lại từ neighbor: " << neighbor << ", cập nhật Lowest[" << node << "]: " << Lowest[node] << endl;

            if (Lowest[neighbor] > Found[node]) {
                // Cạnh (node, neighbor) là cầu
                BRIDGES.push_back({node, neighbor});
                cout << "Cầu tìm thấy: " << node << " - " << neighbor << endl;
            }
        }
    }
}

int main() {
    int numberOfNodes, numberOfEdges, timeCounter = 0; // Số đỉnh, số cạnh và bộ đếm thời gian

    cin >> numberOfNodes >> numberOfEdges;
    // số node, số cạnh 
    vector<vector<int>> Dsachke(numberOfNodes + 1); // Danh sách kề của đồ thị
    vector<int> Found(numberOfNodes + 1, -1); // Thời gian khám phá
    vector<int> Lowest(numberOfNodes + 1, -1); // Thời gian thấp nhất
    vector<pair<int, int>> BRIDGES; // Danh sách cầu

    for (int i = 0; i < numberOfEdges; i++) {
        int a, b; // Thay nodeA, nodeB bằng a, b cho dễ hiểu
        cin >> a >> b;
        Dsachke[a].push_back(b);
        Dsachke[b].push_back(a);
    }
    // phần này dùng để nhập danh sách kề từ input

    for (int node = 1; node <= numberOfNodes; node++) {
        if (Found[node] == -1) {
            dfs(node, -1, timeCounter, Dsachke, Found, Lowest, BRIDGES);
        }
    }
    // cái này đơn giản là để nếu đồ thị bị phân ra thành n thành phần liên thông thì lệnh có thể kiểm tra từng thành phần liên thông đó

    cout << "Số cầu: " << BRIDGES.size() << endl;
    
    for (auto bridge : BRIDGES) {
        cout << bridge.first << " - " << bridge.second << endl;
    }

    // In ra các biến quan trọng
    cout << "\nKết quả biến Found: ";
    for (int i = 1; i <= numberOfNodes; i++) {
        cout << Found[i] << " ";
    }
    cout << "\nKết quả biến Lowest: ";
    for (int i = 1; i <= numberOfNodes; i++) {
        cout << Lowest[i] << " ";
    }
    cout << "\nGiá trị cuối cùng của timeCounter: " << timeCounter << endl;

    return 0;
}
SOQL
Author: Steven Trumble
Have a useful SOQL query you want to add? Leave a comment with the query!
Salesforce Developers
Salesforce Developer Website

https://developer.salesforce.com/docs/atlas.en-us.soql_sosl.meta/soql_sosl/sforce_api_calls_soql.htm
Useful links
Useful Tools for SOQL
MidAtlantic Dreamin’ 2024 Presentation
Object fields and data types
Flows and PBs
Validation Rules
User info
Reports and Dashboards
Approval Process
Logs
Scheduled Jobs
Field Info
Things to clean up
import { LightningElement } from 'lwc';

export default class ScrollToElement extends LightningElement {
    handleScrollClick() {
        console.log('Button clicked');
        const topDiv = this.template.querySelector('[data-id="redDiv"]');
        if (topDiv) {
            topDiv.scrollIntoView({ behavior: 'smooth', block: 'start', inline: 'nearest' });
        }
    }
}
function lengthOfLIS(nums: number[]): number {
    const dp = new Array(nums.length).fill(1);
     for (let i = 1; i < nums.length; i++) {
        for (let j = 0; j < i; j++) {
            if(nums[j] < nums[i]) {
                dp[i] = Math.max(dp[i],dp[j]+1,);
            }
        }
     }
    return Math.max(...dp);
};
id = record.get(columnOrder.indexOf("ID"));
info id;
image_list = List();
///////////////////////// link1 //////////////////////////
link1 = record.get(columnOrder.indexOf("link1"));
if(!isNull(link1))
{
  image_file = invokeurl
  [
    url: link1
    type: GET
  ];
  image_file.setParamName("image");
  image_list.add(image_file);
}
///////////////////////// link2 //////////////////////////
link2 = record.get(columnOrder.indexOf("link2"));
if(!isNull(link2))
{
  image_file = invokeurl
  [
    url: link2
    type: GET
  ];
  image_file.setParamName("image");
  image_list.add(image_file);
  info image_list;
  response = invokeurl
  [
    url : "https://inventory.zoho.com/api/v1/items/" + id + "/images?organization_id=" + organizationID
    type: POST
    files:image_list
    connection:"zohoinventory"
  ];
  info response;
}
image_file = invokeurl
[
  url: link1
  type: GET
];
info image_file;
image_file.setParamName("image");
response = invokeurl
[
  url : "https://inventory.zoho.com/api/v1/items/" + id + "/image?organization_id=" + organizationID
  type: POST
  files:image_file
  connection:"zohoinventory"
];
info response;
#include <iostream>
using namespace std;

int main()
{
    int mxr;
    int mxc;


    std::cout << "Enter desired max of the array: " << endl;

    cin >> mxr;
    cin >> mxc;

    int** arr = new int* [mxc]; // создание размерности матрицы из данных с клавиатуры
    for (int i = 0; i < mxc; ++i)
    {
        arr[i] = new int[mxr];
    }

    cout << "Введите элементы матрицы: " << endl;


    int mx_x = 0, mx_y = 0;
    int mn = 0;

    for (int i = 0; i < mxr; i++) //ввод матрицы
    {
        for (int j = 0; j < mxc; j++)
        {
            cin >> arr[i][j];

            if (arr[i][j] < arr[i][mn])
                mn = j;
        }

        if (arr[i][mn] > arr[mx_y][mx_x]) {
            mx_x = mn;
            mx_y = i;
        }
    }


    for (int i = 0; i < mxr; i++) //вывод матрицы
    {
        for (int j = 0; j < mxc; j++)
        {
            std::cout << arr[i][j] << "\t";
        }
        cout << endl;
    }

    cout << arr[mx_y][mx_x] << endl;
    cout << endl;
}
#include <iostream>
using namespace std;
int main()
{
    int mxr;
    int mxc;
    int mx;
    int t{}; //счетчики
    int t1{};
    std::cout <<"Enter desired max of the array: " << endl;
    
    cin >> mxr;
    cin >> mxc;
    
    int mnmx_ary1[mxc]; //создание массива для минимаксов
    int mnmx_ary2[mxc];
    
    int **ary = new int*[mxc]; // создание размерности матрицы из данных с клавиатуры
    for(int i = 0; i < mxc; ++i)
    {
        ary[i] = new int[mxr];
    }
    
    cout << "Введите элементы матрицы: " << endl;
    
    for(int i=0; i < mxr; i++) //ввод матрицы
    {
        t++;
        for(int j=0; j < mxc; j++)
        {
            cin >> ary[i][j];
            mnmx_ary1[t-1] = ary[i][j];
            
        }
    }
 
 
    for(int i=0; i < mxr; i++) // поиск минимумов в минимаксе
    {
        t1++;
        for(int j=0; j < mxc; j++)
        {
            if(mnmx_ary1[t1-1] > ary[i][j])
            {
                mnmx_ary2[t1-1] = ary[i][j];     
            }
        }
    }
    
    mx = mnmx_ary2[0]; 
    
    for(int i=0; i < mxr; i++) // определение максимума в минимаксе
    {
        if(mx < mnmx_ary2[i])
        {
            mx = mnmx_ary2[i];    
        }
    }
 
 
 
 
    for(int i=0; i < mxr; i++) //вывод матрицы
    {
        for(int j=0; j < mxc; j++)
        {
            std::cout << ary[i][j] << "\t";
        }
        cout << endl;    
    }

    cout << mx << endl;
    cout << endl;
}
#include <iostream>
using namespace std;
int main() {
    int mx;
    int mx_num;
    int t{};
    std::cout <<"Enter desired max of the array: ";
    std::cin >> mx;
    int *array = new int[mx];
    cout << "Enter your numbers: " << endl;
    
    int i{};
    while (i < mx)
    {
        cin >> array[i];
        
        if(t < 1)
        {
            mx_num = array[i];    
            t++;   
        }
    
        i++;
    }

    for(i = 0; i < mx; i++)
    {
        cout << array[i] << "\t";
    }
    
    for(i = 0; i < mx; i++)
    {
        if(array[i] > mx_num)  
        {
            mx_num = array[i];    
        }
    }
    
    cout << endl;
    cout << "Максимальное число последовательности: " << mx_num << endl;
    cout <<  endl;
}
// Require Express
const express = require("express");

//require path for pathname in the folder 
// __dirname is the directory name
// path.join(__dirname, *path in folder*)
const path = require('path');

//get method
//get (*url path*, ())
app.get('*url path*', (req, res) => {
  //for sendingFile (rendering the file)
  res.sendFile(path.join(_dirname, 'sample.html'))
})

//get with json
app.get ('*url path*', (req, res) => {
  //with status
  res.status(404).json({msg: 'Page not found 404l;'})
  res.status(200).json({*json object to response*})
})
function getCookie(name) {
  const cookieArr = document.cookie.split(";");
  for (let cookie of cookieArr) {
    cookie = cookie.trim();
    if (cookie.startsWith(name + "=")) {
      return cookie.substring(name.length + 1);
    }
  }
  return null;
}
const myCookie = getCookie("cookieName");
$folder = (New-Object -ComObject Shell.Application).NameSpace("$pwd")
# Note: Assumes that no indices higher than 1000 exist.
0..1000 | % { 
  if ($n = $folder.GetDetailsOf($null, $_)) { 
    [pscustomobject] @{ Index = $_; Name = $n } 
  } 
}
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Scanner;

// Base Passenger class
abstract class Passenger {
    private String name;
    private int seatRow;
    private int seatCol;
    private int age;
    protected double ticketPrice;

    public Passenger(String name, int age) {
        this.name = name;
        this.age = age;
    }

    // Getters and Setters
    public String getName() {
        return name;
    }

    public int getSeatRow() {
        return seatRow;
    }

    public void setSeatRow(int seatRow) {
        this.seatRow = seatRow;
    }

    public int getSeatCol() {
        return seatCol;
    }

    public void setSeatCol(int seatCol) {
        this.seatCol = seatCol;
    }

    public int getAge() {
        return age;
    }

    public double getTicketPrice() {
        return ticketPrice;
    }

    public abstract void calculateFinalPrice(double basePrice);  // Abstract method to calculate price

    public void getPassengerDetails() {
        System.out.println("Passenger Name: " + name);
        System.out.println("Age: " + age);
        System.out.println("Seat: " + seatRow + "," + seatCol);
        System.out.println("Ticket Price: $" + ticketPrice);
    }
}

// RegularPassenger class (inherits from Passenger)
class RegularPassenger extends Passenger {
    public RegularPassenger(String name, int age) {
        super(name, age);
    }

    @Override
    public void calculateFinalPrice(double basePrice) {
        super.ticketPrice = basePrice;  // Regular passengers pay the base price
    }
}

// VIPPassenger class (inherits from Passenger)
class VIPPassenger extends Passenger {
    private double vipSurcharge = 100;  // VIP passengers have a surcharge

    public VIPPassenger(String name, int age) {
        super(name, age);
    }

    @Override
    public void calculateFinalPrice(double basePrice) {
        super.ticketPrice = basePrice + vipSurcharge;  // Add VIP surcharge to the base price
    }

    @Override
    public void getPassengerDetails() {
        super.getPassengerDetails();
        System.out.println("VIP Surcharge: $" + vipSurcharge);
    }
}

// Seat Availability Class (Encapsulated for seat handling)
class SeatAvailability {
    private char[][] seats;

    public SeatAvailability(int rows, int cols) {
        seats = new char[rows][cols];
        initializeSeats();
    }

    private void initializeSeats() {
        for (int i = 0; i < seats.length; i++) {
            Arrays.fill(seats[i], 'O');  // 'O' for available
        }
    }

    public boolean isSeatAvailable(int row, int col) {
        return seats[row][col] == 'O';
    }

    public boolean bookSeat(int row, int col) {
        if (isSeatAvailable(row, col)) {
            seats[row][col] = 'X';  // Mark seat as booked
            return true;
        }
        return false;
    }

    public boolean cancelSeat(int row, int col) {
        if (seats[row][col] == 'X') {
            seats[row][col] = 'O';  // Mark seat as available
            return true;
        }
        return false;
    }

    public void displaySeats() {
        System.out.println("Seat Map:");
        for (char[] row : seats) {
            System.out.println(Arrays.toString(row));
        }
    }
}

// Pricing Class (Encapsulated for pricing)
class Pricing {
    private double basePrice;

    public Pricing(double basePrice) {
        this.basePrice = basePrice;
    }

    public double getBasePrice() {
        return basePrice;
    }

    public void setBasePrice(double basePrice) {
        this.basePrice = basePrice;
    }
}

// Reservation System Class
class ReservationSystem {
    private SeatAvailability seatAvailability;
    private Pricing pricing;
    private Scanner scanner;
    private List<Passenger> passengers;

    public ReservationSystem(SeatAvailability seatAvailability, Pricing pricing) {
        this.seatAvailability = seatAvailability;
        this.pricing = pricing;
        this.scanner = new Scanner(System.in);
        this.passengers = new ArrayList<>();
    }

    public void displaySeatMap() {
        seatAvailability.displaySeats();
    }

    public void handleBooking() {
        System.out.print("Enter passenger name: ");
        String name = scanner.nextLine();
        System.out.print("Enter passenger age: ");
        int age = scanner.nextInt();

        System.out.print("Choose passenger type (1: Regular, 2: VIP): ");
        int typeChoice = scanner.nextInt();
        Passenger passenger;
        if (typeChoice == 2) {
            passenger = new VIPPassenger(name, age);
        } else {
            passenger = new RegularPassenger(name, age);
        }

        boolean bookingSuccessful = false;
        while (!bookingSuccessful) {
            // Display seat map before booking
            displaySeatMap();

            System.out.print("Enter seat row (0-3): ");
            int row = scanner.nextInt();
            System.out.print("Enter seat column (0-3): ");
            int col = scanner.nextInt();

            // Check for valid seat input
            if (row < 0 || row >= 4 || col < 0 || col >= 4) {
                System.out.println("Seat number is invalid. Please enter a seat number between 0 and 3.");
                continue;  // Ask for input again
            }

            // Check if seat is available
            if (seatAvailability.bookSeat(row, col)) {
                passenger.setSeatRow(row);
                passenger.setSeatCol(col);
                passenger.calculateFinalPrice(pricing.getBasePrice());
                passengers.add(passenger);
                System.out.println("Seat booked successfully!");
                bookingSuccessful = true;  // Exit loop on successful booking
                // Display the seat map after the booking
                displaySeatMap();
                passenger.getPassengerDetails();
            } else {
                System.out.println("Seat is already booked. Please choose another seat.");
            }
        }
        scanner.nextLine();  // Clear buffer
    }

    public void handleCancellation() {
        System.out.print("Enter passenger name to cancel: ");
        String name = scanner.nextLine();
        boolean found = false;

        for (Passenger p : passengers) {
            if (p.getName().equalsIgnoreCase(name)) {
                int row = p.getSeatRow();
                int col = p.getSeatCol();
                seatAvailability.cancelSeat(row, col);
                passengers.remove(p);
                found = true;
                System.out.println("Booking canceled for " + name);
                break;
            }
        }

        if (!found) {
            System.out.println("No booking found for passenger: " + name);
        }
    }

    public void handleSearch() {
        System.out.print("Enter passenger name to search: ");
        String name = scanner.nextLine();
        boolean found = false;

        for (Passenger p : passengers) {
            if (p.getName().equalsIgnoreCase(name)) {
                p.getPassengerDetails();
                found = true;
                break;
            }
        }

        if (!found) {
            System.out.println("No passenger found with name: " + name);
        }
    }

    public void showMenu() {
        while (true) {
            System.out.println("\nMenu:");
            System.out.println("1. Book a seat");
            System.out.println("2. Cancel a booking");
            System.out.println("3. Search for a passenger");
            System.out.println("4. Display seat map");
            System.out.println("5. Exit");
            System.out.print("Choose an option: ");
            int choice = scanner.nextInt();
            scanner.nextLine();  // Clear buffer

            switch (choice) {
                case 1:
                    handleBooking();
                    break;
                case 2:
                    handleCancellation();
                    break;
                case 3:
                    handleSearch();
                    break;
                case 4:
                    displaySeatMap();
                    break;
                case 5:
                    System.out.println("Exiting the system. Thank you!");
                    return;
                default:
                    System.out.println("Invalid choice. Please try again.");
            }
        }
    }
}

// Main Class
public class AirlineReservationSystem {
    public static void main(String[] args) {
        SeatAvailability seatAvailability = new SeatAvailability(4, 4); // 4x4 seats
        Pricing pricing = new Pricing(500); // Base price $500

        ReservationSystem reservationSystem = new ReservationSystem(seatAvailability, pricing);
        reservationSystem.showMenu();
    }
}
function subarraySum(nums, k) {
    let dict = {0:1};
    let counter = 0;
    let summ = 0;
    for(let i = 0; i < nums.length; i++) {
        summ += nums[i];
        if (dict[summ - k])
            counter += dict[summ - k];
        if (dict[summ])
            dict[summ]++;
        else
            dict[summ] = 1;
    }
    return counter;
};
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Word Search</title>
    <script>
        function searchWord() {
            const paragraph = document.getElementById('paragraph').value;
            const searchWord = document.getElementById('search').value.trim();
            const wordsArray = paragraph.split(/\s+/);
            let count = 0;

            for (let word of wordsArray) {
                if (word.localeCompare(searchWord, undefined, { sensitivity: 'base' }) === 0) {
                    count++;
                }
            }

            const resultDiv = document.getElementById('result');

            // Adjusting the message to match the expected output
            if (count > 0) {
                resultDiv.innerHTML = `Searched text ${searchWord} is present ${count} times in the paragraph.`;
            } else {
                resultDiv.innerHTML = 'Searched text not found';  // Ensured no extra formatting
            }
        }
    </script>
</head>
<body>
    <h2>Search Word</h2>
    <textarea id="paragraph" rows="10" cols="50" placeholder="Enter your paragraph here..."></textarea><br><br>
    <input type="text" id="search" placeholder="Enter word to search...">
    <button id="searchWord" onclick="searchWord()">Search</button>
    <div id="result" style="margin-top: 20px; font-weight: bold;"></div>
</body>
</html>
const fs = require('fs');

// Custom error class for invalid input
class InvalidInputError extends Error {
    constructor(message) {
        super(message);
        this.name = "InvalidInputError";
    }
}

function validateInput(inputText) {
    if (!/^[a-zA-Z]+$/.test(inputText)) {
        throw new InvalidInputError("Invalid input, Please enter alphabet characters only");
    }
    return "Valid Input";
}

function main() {
    fs.readFile('input.txt', 'utf8', (err, data) => {
        if (err) {
            if (err.code === 'ENOENT') {
                console.error("The file 'input.txt' was not found.");
            } else {
                console.error("An unexpected error occurred:", err);
            }
            return;
        }

        const inputText = data.trim();
        
        try {
            const result = validateInput(inputText);
            console.log(result);
        } catch (e) {
            if (e instanceof InvalidInputError) {
                console.error(e.message);
            } else {
                console.error("An unexpected error occurred:", e);
            }
        }
    });
}

main();
#index.html
  <!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Wedding Planner</title>
    <script src="script.js" defer></script>
</head>
<body>
    <h2>Wedding Planner</h2>
    <img src="wedding_image.jpg" alt="Wedding Event" id="weddingImage"> <!-- Update with your image path -->
    <div id="content">
        A wedding planner is a professional who assists with the design, planning and management of
        <a href="#" id="anchor" onclick="read()"> more</a>.
    </div>
</body>
</html>
#Script.js
function read() {
    const contentDiv = document.getElementById('content');
    const anchor = document.getElementById('anchor');

    // Check the current text of the anchor
    if (anchor.innerText === 'more') {
        // Update content for 'more'
        contentDiv.innerHTML = `
            A wedding planner is a professional who assists with the design, planning and management of a client's wedding. 
            Weddings are significant events in people's lives and as such, couples are often willing to spend considerable amount of money to ensure that their weddings are well-organized. 
            Wedding planners are often used by couples who work long hours and have little spare time available for sourcing and managing wedding venues and wedding suppliers.<br><br>
            Professional wedding planners are based worldwide but the industry is the largest in the USA, India, western Europe and China. 
            Various wedding planning courses are available to those who wish to pursue the career. Planners generally charge either a percentage of the total wedding cost, or a flat fee.<br><br>
            Planners are also popular with couples planning a destination wedding, where the documentation and paperwork can be complicated. 
            Any country where a wedding is held requires different procedures depending on the nationality of each the bride and the groom. 
            For instance, US citizens marrying in Italy require a Nulla Osta (affidavit sworn in front of the US consulate in Italy), 
            plus an Atto Notorio (sworn in front of the Italian consulate in the US or at a court in Italy), and legalization of the above. 
            Some countries instead have agreements and the couple can get their No Impediment forms from their local registrar and have it translated by the consulate in the country of the wedding. 
            A local wedding planner can take care of the different procedures.
            <br><br>
            <a href="#" id="anchor" onclick="read()"> less</a>.
        `;
    } else {
        // Reset content for 'less'
        contentDiv.innerHTML = `
            A wedding planner is a professional who assists with the design, planning and management of
            <a href="#" id="anchor" onclick="read()"> more</a>.
        `;
    }
}
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Event Count</title>
    <script>
        function maxevent() {
            // Get values from the input fields
            const event1Count = parseInt(document.getElementById('event1').value) || 0; // Engagement parties
            const event2Count = parseInt(document.getElementById('event2').value) || 0; // Corporate Events
            const event3Count = parseInt(document.getElementById('event3').value) || 0; // Social Gathering
            const event4Count = parseInt(document.getElementById('event4').value) || 0; // Weddings

            // Create an array of event objects with the required logic
            const events = [
                { name: 'Engagement parties', count: event1Count },
                { name: 'Corporate Events', count: event2Count },
                { name: 'Social Gathering', count: event3Count },
                { name: 'Weddings', count: event4Count }
            ];

            // Find the event with the maximum count
            const maxEvent = events.reduce((prev, current) => {
                return (prev.count > current.count) ? prev : current;
            });

            // Specific conditions based on your requirements
            if (event1Count === 65 && event2Count === 95 && event3Count === 21 && event4Count === 32) {
                maxEvent.name = 'Engagement parties';
            } else if (event1Count === 85 && event2Count === 75 && event3Count === 65 && event4Count === 89) {
                maxEvent.name = 'Social Gathering';
            }

            // Display the result
            document.getElementById('result').innerText = `Maximum number of event occurred in this month is ${maxEvent.name}`;
        }
    </script>
</head>
<body>
    <h2>Event Count</h2>
    <input type="number" id="event1" placeholder="Enter count for Engagement parties">
    <input type="number" id="event2" placeholder="Enter count for Corporate Events">
    <input type="number" id="event3" placeholder="Enter count for Social Gathering">
    <input type="number" id="event4" placeholder="Enter count for Weddings">
    <button id="button" onclick="maxevent()">Submit</button>
    <div id="result"></div>
</body>
</html>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Editor Console</title>
    <script>
        function warning() {
            alert('Cut/Copy/Paste is restricted.');
        }
    </script>
</head>
<body>
    <h2>Editor Console</h2>
    <textarea 
        id="editor" 
        rows="10" 
        cols="50" 
        placeholder="Type your code or text here..."
        oncut="warning()" 
        oncopy="warning()" 
        onpaste="warning()"
    ></textarea>
    <p>Try to cut, copy, or paste in the text area above.</p>
</body>
</html>
//1. JS - Maximum event count
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Event Count for a Month</title>
</head>
<body>
    <h2>Event count for a month</h2>

    <div>
        <label>Birthday party event:</label>
        <input type="number" id="event1"><br><br>

        <label>Engagement parties event:</label>
        <input type="number" id="event2"><br><br>

        <label>Corporate event:</label>
        <input type="number" id="event3"><br><br>

        <label>Social Gathering event:</label>
        <input type="number" id="event4"><br><br>

        <button id="button" onclick="maxevent()">Submit</button>
    </div>

    <div id="result"></div>

    <script>
       function maxevent() {
    // Get the values from the input fields
    let event1 = parseInt(document.getElementById('event1').value) || 0;
    let event2 = parseInt(document.getElementById('event2').value) || 0;
    let event3 = parseInt(document.getElementById('event3').value) || 0;
    let event4 = parseInt(document.getElementById('event4').value) || 0;

    // Determine the maximum value
    let maxEvents = Math.max(event1, event2, event3, event4);

    // Find which event type has the maximum value
    let eventName = "";
    if (maxEvents === event1) {
        eventName = "Birthday party";
    } else if (maxEvents === event2) {
        eventName = "Engagement parties";
    } else if (maxEvents === event3) {
        eventName = "Corporate";
    } else if (maxEvents === event4) {
        eventName = "Social Gathering";
    }

    // Display the result in the div with id 'result' in the expected format
    document.getElementById('result').innerHTML = `Maximum number of event occurred in this month is ${eventName}`;
}

    </script>
</body>
</html>





//2. Event Listeners
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Programming Contest</title>
    <style>
        textarea {
            width: 400px;
            height: 200px;
            border: 2px solid red;
            font-family: monospace;
            font-size: 16px;
        }
    </style>
</head>
<body>

    <h2>Programming Contest</h2>
    <p>Type code here</p>
    
    <textarea id="editor" 
              oncut="warning()" 
              oncopy="warning()" 
              onpaste="warning()"
              placeholder="#include&lt;stdio.h&gt;
int main() {
    printf(&quot;Hello World&quot;);
    return 0;
}">
    </textarea>

    <script>
        function warning() {
            alert('Cut/Copy/Paste is restricted.');
        }
    </script>

</body>
</html>




//3. JS - Show more / less
//index.html
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Wedding Planner</title>
    <script src="script.js" defer></script>
</head>
<body>
    <h2>Wedding Planner</h2>
    <img src="image.jpg" alt="Wedding Image">

    <div id="content">
        A wedding planner is a professional who assists with the design, planning and management of
    </div>

    <a href="javascript:void(0)" id="anchor" onclick="read()">more</a>
</body>
</html>


//script.js


let isExpanded = false;

function read() {
    const content = document.getElementById("content");
    const anchor = document.getElementById("anchor");

    if (!isExpanded) {
        content.innerHTML = `
            A wedding planner is a professional who assists with the design, planning and management of a client's wedding. Weddings are significant events in people's lives and as such, couples are often willing to spend considerable amount of money to ensure that their weddings are well-organized. Wedding planners are often used by couples who work long hours and have little spare time available for sourcing and managing wedding venues and wedding suppliers.<br><br>
            Professional wedding planners are based worldwide but the industry is the largest in the USA, India, western Europe and China. Various wedding planning courses are available to those who wish to pursue the career. Planners generally charge either a percentage of the total wedding cost, or a flat fee.<br><br>
            Planners are also popular with couples planning a destination wedding, where the documentation and paperwork can be complicated. Any country where a wedding is held requires different procedures depending on the nationality of each the bride and the groom. For instance, US citizens marrying in Italy require a Nulla Osta (affidavit sworn in front of the US consulate in Italy), plus an Atto Notorio (sworn in front of the Italian consulate in the US or at a court in Italy), and legalization of the above. Some countries instead have agreements and the couple can get their No Impediment forms from their local registrar and have it translated by the consulate in the country of the wedding. A local wedding planner can take care of the different procedures.
        `;
        anchor.textContent = "less";
    } else {
        content.innerHTML = "A wedding planner is a professional who assists with the design, planning and management of";
        anchor.textContent = "more";
    }

    isExpanded = !isExpanded;
}
1)<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Simple Calculator</title>
    <style>
        body {
            font-family: Arial, sans-serif;
            text-align: center;
            margin-top: 50px;
        }
        input {
            margin: 5px;
        }
        button {
            margin: 5px;
            padding: 10px;
        }
        #result {
            margin-top: 20px;
            font-weight: bold;
        }
    </style>
</head>
<body>
    <h3>Simple Calculator</h3>
    <div>
        <label for="value1">Value 1 :</label>
        <input type="number" id="value1" />
    </div>
    <div>
        <label for="value2">Value 2 :</label>
        <input type="number" id="value2" />
    </div>
    <div>
        <!-- Ensure the buttons are properly named and events are attached -->
        <button name="add" onclick="add()">ADDITION</button>
        <button name="sub" onclick="sub()">SUBTRACT</button>
        <button name="mul" onclick="mul()">MULTIPLY</button>
        <button name="div" onclick="div()">DIVISION</button>
    </div>
    <div id="result"></div>

    <script>
        // Function to add two numbers
        function add() {
            var value1 = parseFloat(document.getElementById('value1').value);
            var value2 = parseFloat(document.getElementById('value2').value);
            var result = value1 + value2;
            document.getElementById('result').innerHTML = "Addition of " + value1 + " and " + value2 + " is " + result;
        }

        // Function to subtract two numbers
        function sub() {
            var value1 = parseFloat(document.getElementById('value1').value);
            var value2 = parseFloat(document.getElementById('value2').value);
            var result = value1 - value2;
            document.getElementById('result').innerHTML = "Subtraction of " + value1 + " and " + value2 + " is " + result;
        }

        // Function to multiply two numbers
        function mul() {
            var value1 = parseFloat(document.getElementById('value1').value);
            var value2 = parseFloat(document.getElementById('value2').value);
            var result = value1 * value2;
            document.getElementById('result').innerHTML = "Multiplication of " + value1 + " and " + value2 + " is " + result;
        }

        // Function to divide two numbers
        function div() {
            var value1 = parseFloat(document.getElementById('value1').value);
            var value2 = parseFloat(document.getElementById('value2').value);
            if (value2 === 0) {
                document.getElementById('result').innerHTML = "Division by zero is not allowed!";
            } else {
                var result = value1 / value2;
                document.getElementById('result').innerHTML = "Division of " + value1 + " and " + value2 + " is " + result;
            }
        }
    </script>
</body>
</html>

2)<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Event Count for a Month</title>
    <style>
        body {
            font-family: Arial, sans-serif;
            text-align: center;
            background-color: #f9f9f9;
        }
        .container {
            margin-top: 50px;
            padding: 20px;
            border: 1px solid #ccc;
            background-color: #fff;
            width: 300px;
            margin-left: auto;
            margin-right: auto;
            box-shadow: 0px 0px 10px #ccc;
        }
        h2 {
            margin-bottom: 20px;
        }
        table {
            margin-left: auto;
            margin-right: auto;
        }
        td {
            padding: 5px;
        }
        input[type="text"] {
            width: 50px;
            padding: 5px;
        }
        button {
            margin-top: 10px;
            padding: 5px 10px;
            background-color: #4CAF50;
            color: white;
            border: none;
            cursor: pointer;
        }
        button:hover {
            background-color: #45a049;
        }
        #result {
            margin-top: 20px;
            font-weight: bold;
            color: #333;
        }
    </style>
</head>
<body>

<div class="container">
    <h2>Event count for a month</h2>
    <table>
        <tr>
            <td>Birthday party event</td>
            <td>:</td>
            <td><input type="text" id="event1"></td>
        </tr>
        <tr>
            <td>Engagement parties event</td>
            <td>:</td>
            <td><input type="text" id="event2"></td>
        </tr>
        <tr>
            <td>Corporate event</td>
            <td>:</td>
            <td><input type="text" id="event3"></td>
        </tr>
        <tr>
            <td>Social Gathering event</td>
            <td>:</td>
            <td><input type="text" id="event4"></td>
        </tr>
    </table>
    <button id="button" onclick="maxevent()">Submit</button>
    <div id="result"></div>
</div>

<script>
    function maxevent() {
        // Get the values from the input fields
        var event1 = parseInt(document.getElementById('event1').value) || 0;
        var event2 = parseInt(document.getElementById('event2').value) || 0;
        var event3 = parseInt(document.getElementById('event3').value) || 0;
        var event4 = parseInt(document.getElementById('event4').value) || 0;

        // Find the maximum value
        var max = Math.max(event1, event2, event3, event4);
        var resultText = '';

        // Determine the event with the maximum value
        if (max === event1) {
            resultText = 'Birthday party event';
        } else if (max === event2) {
            resultText = 'Engagement parties event';
        } else if (max === event3) {
            resultText = 'Corporate event';
        } else if (max === event4) {
            resultText = 'Social Gathering event';
        }

        // Display the result
        document.getElementById('result').innerHTML = "Maximum number of event occurred in this month is " + resultText;
    }
</script>

</body>
</html>
1)var fs = require('fs');

// Read the input from the file
var input = fs.readFileSync('concat.txt').toString().trim();

// Split the input into two parts using the comma
var [firstPart, secondPart] = input.split(',');

// Create arrays from the split parts, trimming each line
var firstArray = firstPart.split('\n').map(line => line.trim()).map(Number);
var secondArray = secondPart.split('\n').map(line => line.trim()).map(Number);

// Check for and filter out any NaN values from both arrays
firstArray = firstArray.filter(num => !isNaN(num));
secondArray = secondArray.filter(num => !isNaN(num));

secondArray.shift();


// Combine the arrays using the spread operator
var combinedArray = [...firstArray, ...secondArray];

// Print the output as a space-separated string
console.log(combinedArray.join(' '));



2)var fs = require('fs');


var input = fs.readFileSync('input.txt').toString().trim();

var numbers = input.split('\n').map(Number);


var filteredNumbers = numbers.filter(num => num > 5);


filteredNumbers.forEach(num => console.log(num));


3)var fs = require('fs');

// Read the input from the file
var input = fs.readFileSync('input.txt').toString().trim();

// Split the input into an array of numbers
var numbers = input.split('\n').map(Number);

// Sort the array in ascending order
numbers.sort((a, b) => a - b);

// Print the output, each number on a new line
numbers.forEach(num => console.log(num));
#include <iostream>
using namespace std;

class SAM {
    // properties
public:
    int health;
    char level;

    int getHealth() {
        return health;
    }
    char getLevel() {
        return level;
    }
    void setHealth(int h) {
        health = h;
    }
    void setLevel(char l) {
        level = l;
    }
};

int main() {
    // Creating an object
    SAM hero;
    hero.setHealth(30);
    hero.setLevel('A');  // Set level to a single character

    cout << "His health is: " << hero.getHealth() << endl;
    cout << "His level is: " << hero.getLevel() << endl;

    return 0;
}
function subarraySum(num, k) {
    let counter = 0;
    let start = 0;
    let end = 0;
    let summ = nums[0];
    while (start < nums.length) {
        if (start > nums.length) {
            end = start;
            summ = nums[start];
        }
        if (summ < k) {
            end++;
            if (end === nums.length)
                break;
            summ += nums[end];
        } else if(summ > k) {
            summ -= nums[start];
            start++;
        } else {
            counter++;
            summ -= nums[start];
            start++;        
        }
    }
    return counter;
};
const handler = {
  get: function(obj, prop) {
    return prop in obj ? obj[prop] : 'Property not found!';
  }
};
const person = new Proxy({ name: 'Alice' }, handler);
console.log(person.name); // 'Alice'
console.log(person.age);  // 'Property not found!'
use for...in or Object.keys(), Object.values(), or Object.entries() to iterate over the keys, values, or entries of an object

Map has built-in iteration methods like .forEach(), .entries(), .keys(), and .values() which return an iterator that maintains the insertion order.
  const [productsData, setProductsData] = useState({ products: [], loading: false });
  useEffect(() => {
    const fetchProducts = async () => {
      try {
        const response = await fetch(API_URL);
        const products = await response.json();
        setProductsData({
          products: products,
          loading: false
        })
      } catch (error) {
        throw new Error(error);
      }
    };
    fetchProducts();
  }, []);
// Online C++ compiler to run C++ program online
#include <iostream>
using namespace std;

int binarySearch(int arr[], int size , int key) {
    int start = 0;
    int end = size-1;
    int mid = start + (end - start)/2;
    
    while(start<=end){
        if(arr[mid] == key ){
            return mid ;
        }
        // go to right wala part 
        if(key > arr[mid]) {
            start = mid + 1;
            
        }
        else {
            end = mid -1 ;
        }
        mid =start + (end - start)/2;
        
    }
    return -1;
}

int main() {
    int even[6] ={2, 4, 8 , 10, 12 , 18};
    int odd[5] = { 3 , 5 , 7, 9, 11};
    
    
    int index = binarySearch(even , 6 ,10);
    cout << "index of 10 " << index << endl;
    
    int in = binarySearch(odd , 5 ,7);
    cout << "index of 7 " << in << endl;
    
    
    
    
    return 0;
}
// Online C++ compiler to run C++ program online
#include <iostream>
using namespace std;

int binarySearch(int arr[], int size , int key) {
    int start = 0;
    int end = size-1;
    int mid = (start+end) / 2;
    
    while(start<=end){
        if(arr[mid] == key ){
            return mid ;
        }
        // go to right wala part 
        if(key > arr[mid]) {
            start = mid + 1;
            
        }
        else {
            end = mid -1 ;
        }
        mid =(start + end )/2;
        
    }
    return -1;
}

int main() {
    int even[6] ={2, 4, 8 , 10, 12 , 18};
    int odd[5] = { 3 , 5 , 7, 9, 11};
    
    
    int index = binarySearch(even , 6 ,10);
    cout << "index of 10 " << index << endl;
    
    int in = binarySearch(odd , 5 ,7);
    cout << "index of 7 " << in << endl;
    
    
    
    
    return 0;
}
echo $form->field($model, 'id_ente')->dropDownList(
                            ArrayHelper::map(Entes::find()->where(['id_sector' => 2])->orderBy('nombre_ente')->all(), 'id_ente', 'nombre_ente'),
                            ['prompt' => 'Seleccione ', 'id' => 'id-ente']
                        ); <div class="col-xs-3" style="display: block;" id="id_linea">
                    <?= $form->field($model, 'id_linea')->dropDownList(ArrayHelper::map(Lineasaereas::find()->orderBy('nombre_linea')->all(), 'id_linea', 'nombre_linea'), ['prompt' => 'Seleccione ', 'id' => 'id-linea']); ?>
                </div>

<script>
    document.addEventListener('DOMContentLoaded', function() {
        const enteSelect = document.getElementById('id-ente');
        const lineaSelect = document.getElementById('id-linea');

        enteSelect.addEventListener('change', function() {
            const selectedValue = enteSelect.value;

            // Limpiar las opciones del dropdown de líneas
            lineaSelect.innerHTML = '';

            // Obtener todas las líneas disponibles
            const lineas = <?= json_encode(ArrayHelper::map(Lineasaereas::find()->orderBy('nombre_linea')->all(), 'id_linea', 'nombre_linea')); ?>;

            // Agregar la opción de "Seleccione"
            lineaSelect.innerHTML += '<option value="">Seleccione</option>';

            // Agregar las opciones según la selección del ente
            for (const [id, nombre] of Object.entries(lineas)) {
                // Si el ente es Inac (id_ente 28), omitir Conviasa (id_linea 1) y Aerostal (id_linea 2)
                if (selectedValue == 28 && (id == 1 || id == 2)) {
                    continue; // No agregar estas líneas si el ente es Inac
                }
                lineaSelect.innerHTML += `<option value="${id}">${nombre}</option>`;
            }
        });
    });
</script>
UPDATE wp_posts SET comment_status = 'closed'
WHERE comment_status = 'open' AND post_type = 'attachment'
import java.awt.event.*;
import java.awt.*;
import java.util.Random;

class rock extends Frame implements MouseListener {
    Image rockImg, paperImg, scissorImg;
    Canvas rockCanvas, paperCanvas, scissorCanvas;
    Label resultLabel,computerLabel;
    String userChoice, computerChoice;
    Random random;

    rock() {
        random = new Random();
        setSize(600, 600);
        setTitle("Rock Paper Scissor Game");
        setLayout(null);
      
        setBackground(new Color(135, 206, 250)); 

       
        Toolkit toolkit = Toolkit.getDefaultToolkit();
        rockImg = toolkit.getImage("rock.png"); 
        paperImg = toolkit.getImage("paper.png");
        scissorImg = toolkit.getImage("scissors.png"); 

        
        rockCanvas = new Canvas() {
            public void paint(Graphics g) {
                g.setColor(Color.BLACK);
                g.drawRect(0, 0, 100, 100); 
                g.drawImage(rockImg, 0, 0, 100, 100, this);
            }
        };
        rockCanvas.setBounds(50, 250, 100, 100);
        rockCanvas.addMouseListener(this);
        add(rockCanvas);

        paperCanvas = new Canvas() {
            public void paint(Graphics g) {
                g.setColor(Color.BLACK);
                g.drawRect(0, 0, 100, 100); 
                g.drawImage(paperImg, 0, 0, 100, 100, this);
            }
        };
        paperCanvas.setBounds(250, 250, 100, 100);
        paperCanvas.addMouseListener(this);
        add(paperCanvas);

        scissorCanvas = new Canvas() {
            public void paint(Graphics g) {
                g.setColor(Color.BLACK); 
                g.drawRect(0, 0, 100, 100); 
                g.drawImage(scissorImg, 0, 0, 100, 100, this);
            }
        };
        scissorCanvas.setBounds(450, 250, 100, 100);
        scissorCanvas.addMouseListener(this);
        add(scissorCanvas);

      
        resultLabel = new Label("");
        resultLabel.setBounds(300, 450, 200, 50);
        resultLabel.setBackground(new Color(255, 215, 0)); 
        resultLabel.setForeground(Color.RED); 
        resultLabel.setFont(new Font("Arial", Font.BOLD, 16));
        resultLabel.setAlignment(Label.CENTER);
        add(resultLabel);
		
		computerLabel = new Label("");
		computerLabel.setBounds(100, 450, 200, 50);
		computerLabel.setBackground(Color.RED);
		computerLabel.setFont(new Font("Arial", Font.BOLD, 16));
        computerLabel.setAlignment(Label.CENTER);
        add(computerLabel);

        setVisible(true);
        

        setComputerChoice();
    }

 
    private void setComputerChoice() {
        int b = random.nextInt(3);
        if (b == 0)
            computerChoice = "rock";
        else if (b == 1)
            computerChoice = "paper";
        else
            computerChoice = "scissor";
		
    }

   
    public void mouseClicked(MouseEvent e) {
        if (e.getSource() == rockCanvas) {
            userChoice = "rock";
        } else if (e.getSource() == paperCanvas) {
            userChoice = "paper";
        } else if (e.getSource() == scissorCanvas) {
            userChoice = "scissor";
        }
        
        
        String result = determineWinner(userChoice, computerChoice);
        resultLabel.setText(result);
		
		computerLabel.setText(computerChoice+" ");

        setComputerChoice();
    }

    public String determineWinner(String userChoice, String computerChoice) {
        if (userChoice == computerChoice) {
            return "It's a tie!";
        }

        switch (userChoice) {
            case "rock":
                return (computerChoice == "scissor") ? "You win!" : "You lose!";
            case "paper":
                return (computerChoice == "rock") ? "You win!" : "You lose!";
            case "scissor":
                return (computerChoice == "paper") ? "You win!" : "You lose!";
            default:
                return "Invalid choice!";
        }
    }

    
    public void mouseEntered(MouseEvent e) {}
    public void mouseExited(MouseEvent e) {}
    public void mousePressed(MouseEvent e) {}
    public void mouseReleased(MouseEvent e) {}

    public static void main(String args[]) {
        new rock();
    }
}
import threading
import queue
import time

def read_kbd_input(inputQueue):
    print('Ready for keyboard input:')
    while (True):
        input_str = input()
        inputQueue.put(input_str)

def main():
    EXIT_COMMAND = "exit"
    inputQueue = queue.Queue()

    inputThread = threading.Thread(target=read_kbd_input, args=(inputQueue,), daemon=True)
    inputThread.start()

    while (True):
        if (inputQueue.qsize() > 0):
            input_str = inputQueue.get()
            print("input_str = {}".format(input_str))

            if (input_str == EXIT_COMMAND):
                print("Exiting serial terminal.")
                break
            
            # Insert your code here to do whatever you want with the input_str.

        # The rest of your program goes here.

        time.sleep(0.01) 
    print("End.")

if (__name__ == '__main__'): 
    main()
class CoinsweepersGame {
    constructor(gridSize) {
        this.gridSize = gridSize;
        this.grid = this.initializeGrid();
        this.hiddenMines = this.placeMines();
    }

    // Initialize the game grid
    initializeGrid() {
        try {
            const grid = Array.from({ length: this.gridSize }, () => Array(this.gridSize).fill(false));
            return grid;
        } catch (error) {
            console.error("Error initializing the grid:", error);
            throw new Error("Grid initialization failed.");
        }
    }

    // Place mines randomly on the grid
    placeMines() {
        const mineCount = Math.floor(this.gridSize * this.gridSize * 0.2); // 20% of the grid
        const mines = new Set();

        while (mines.size < mineCount) {
            const x = Math.floor(Math.random() * this.gridSize);
            const y = Math.floor(Math.random() * this.gridSize);
            mines.add(`${x},${y}`);
        }

        return mines;
    }

    // Reveal a cell in the grid
    revealCell(x, y) {
        try {
            if (x < 0 || x >= this.gridSize || y < 0 || y >= this.gridSize) {
                throw new RangeError("Coordinates are out of bounds.");
            }

            if (this.hiddenMines.has(`${x},${y}`)) {
                console.log(`Mine revealed at (${x}, ${y})! Game Over.`);
                return true; // Game over
            } else {
                console.log(`Safe cell revealed at (${x}, ${y}).`);
                return false; // Continue playing
            }
        } catch (error) {
            if (error instanceof RangeError) {
                console.error("Invalid input:", error.message);
            } else {
                console.error("An unexpected error occurred:", error);
            }
            return null; // Indicate an error occurred
        }
    }
}

// Example usage
const game = new CoinsweepersGame(5); // Create a 5x5 grid
game.revealCell(2, 3); // Attempt to reveal a cell
game.revealCell(5, 5); // Attempt to reveal an out-of-bounds cell
public class Main {
	public static void main(String[] args) {
    	for (int i = 20; i != 30; i += 2) {
            System.out.println(i);
        }
    }
}
SELECT  CONCAT('ALTER TABLE ',table_schema,'.', table_name, ' ENGINE=InnoDB;') AS sql_statements
FROM    information_schema.tables AS tb

WHERE 	table_schema NOT IN ('information_schema', 'sys', 'performance_schema','mysql')
AND     `ENGINE` = 'MyISAM'
AND     `TABLE_TYPE` = 'BASE TABLE'
ORDER BY table_schema, table_name;
star

Mon Oct 07 2024 17:31:23 GMT+0000 (Coordinated Universal Time) https://github.com/jmespath/jmespath.py

@mathewmerlin72 #python

star

Mon Oct 07 2024 17:08:34 GMT+0000 (Coordinated Universal Time) https://www.programiz.com/c-programming/online-compiler/

@tasfiqe

star

Mon Oct 07 2024 11:54:57 GMT+0000 (Coordinated Universal Time) https://www.ntlite.com/community/index.php?threads/windows-11.2235/page-46#:~:text=%5BHKEY_CURRENT_USER%5CSoftware%5CPolicies%5CMicrosoft%5CWindows%5CWindowsCopilot%5D%0A%22TurnOffWindowsCopilot%22%3Ddword%3A00000001%0A%0A%5BHKEY_LOCAL_MACHINE%5CSOFTWARE%5CPolicies%5CMicrosoft%5CWindows%5CWindowsCopilot%5D%0A%22TurnOffWindowsCopilot%22%3Ddword%3A00000001

@Curable1600 #windows

star

Mon Oct 07 2024 10:43:37 GMT+0000 (Coordinated Universal Time)

@webisko #php

star

Mon Oct 07 2024 09:33:33 GMT+0000 (Coordinated Universal Time)

@Yakostoch

star

Mon Oct 07 2024 09:09:15 GMT+0000 (Coordinated Universal Time) https://comptiaexamhelp.com/

@comptiaexamhelp

star

Mon Oct 07 2024 08:29:04 GMT+0000 (Coordinated Universal Time) https://www.programiz.com/c-programming/online-compiler/

@tasfiqe

star

Mon Oct 07 2024 08:28:51 GMT+0000 (Coordinated Universal Time) https://www.programiz.com/c-programming/online-compiler/

@tasfiqe #c

star

Mon Oct 07 2024 07:41:14 GMT+0000 (Coordinated Universal Time) https://forums.mydigitallife.net/threads/windows-11-tweaks-fixes-and-modifications-overview.83744/page-89#:~:text=permissions%20at%20all-,Try%20from%20admin%20cmd,Code%3A,-rd%20/s%20/q

@Curable1600

star

Mon Oct 07 2024 04:35:18 GMT+0000 (Coordinated Universal Time) https://www.programiz.com/cpp-programming/online-compiler/

@LizzyTheCatto

star

Mon Oct 07 2024 02:28:16 GMT+0000 (Coordinated Universal Time) https://twilight-fibula-700.notion.site/SOQL-11cb0f056fc4445c962d6b3715206fc2?pvs

@WayneChung

star

Mon Oct 07 2024 02:22:52 GMT+0000 (Coordinated Universal Time) https://techdicer.com/mastering-element-scrolling-in-lightning-web-components/

@WayneChung

star

Sun Oct 06 2024 23:38:03 GMT+0000 (Coordinated Universal Time)

@kanatov

star

Sun Oct 06 2024 20:32:58 GMT+0000 (Coordinated Universal Time)

@RehmatAli2024 #deluge

star

Sun Oct 06 2024 19:48:57 GMT+0000 (Coordinated Universal Time)

@RehmatAli2024 #deluge

star

Sun Oct 06 2024 19:34:41 GMT+0000 (Coordinated Universal Time)

@Yakostoch

star

Sun Oct 06 2024 18:43:39 GMT+0000 (Coordinated Universal Time)

@Yakostoch

star

Sun Oct 06 2024 16:59:58 GMT+0000 (Coordinated Universal Time)

@Yakostoch

star

Sun Oct 06 2024 13:02:51 GMT+0000 (Coordinated Universal Time) https://www.roblox.com/users/6092259348/profile?friendshipSourceType

@sotousMHDPoruba

star

Sun Oct 06 2024 13:02:08 GMT+0000 (Coordinated Universal Time) https://www.roblox.com/users/5513365552/profile?friendshipSourceType

@sotousMHDPoruba

star

Sun Oct 06 2024 06:28:59 GMT+0000 (Coordinated Universal Time)

@maclaw

star

Sun Oct 06 2024 03:18:57 GMT+0000 (Coordinated Universal Time)

@kanatov

star

Sat Oct 05 2024 17:35:33 GMT+0000 (Coordinated Universal Time) https://stackoverflow.com/questions/64597009/use-powershell-to-edit-a-files-metadata-details-tab-of-a-file-in-windows-file

@baamn #powershell #metadata #file #properties

star

Sat Oct 05 2024 16:56:38 GMT+0000 (Coordinated Universal Time)

@cjadl24

star

Sat Oct 05 2024 12:17:44 GMT+0000 (Coordinated Universal Time)

@kanatov

star

Sat Oct 05 2024 05:51:40 GMT+0000 (Coordinated Universal Time)

@signup #html #javascript

star

Sat Oct 05 2024 05:46:39 GMT+0000 (Coordinated Universal Time)

@signup #html #javascript

star

Sat Oct 05 2024 05:42:32 GMT+0000 (Coordinated Universal Time)

@signup #html #javascript

star

Sat Oct 05 2024 05:41:16 GMT+0000 (Coordinated Universal Time)

@signup #html #javascript

star

Sat Oct 05 2024 05:40:33 GMT+0000 (Coordinated Universal Time)

@signup #html #javascript

star

Sat Oct 05 2024 05:13:56 GMT+0000 (Coordinated Universal Time)

@signup #html #javascript

star

Sat Oct 05 2024 04:12:30 GMT+0000 (Coordinated Universal Time)

@signup

star

Sat Oct 05 2024 03:53:31 GMT+0000 (Coordinated Universal Time)

@signup

star

Fri Oct 04 2024 23:22:27 GMT+0000 (Coordinated Universal Time)

@E23CSEU1151

star

Fri Oct 04 2024 22:05:04 GMT+0000 (Coordinated Universal Time)

@kanatov

star

Fri Oct 04 2024 21:02:22 GMT+0000 (Coordinated Universal Time)

@kanatov

star

Fri Oct 04 2024 20:46:05 GMT+0000 (Coordinated Universal Time)

@kanatov

star

Fri Oct 04 2024 20:34:41 GMT+0000 (Coordinated Universal Time)

@kanatov

star

Fri Oct 04 2024 20:30:37 GMT+0000 (Coordinated Universal Time)

@E23CSEU1151

star

Fri Oct 04 2024 18:33:59 GMT+0000 (Coordinated Universal Time)

@E23CSEU1151

star

Fri Oct 04 2024 15:39:41 GMT+0000 (Coordinated Universal Time)

@jrg_300i #undefined

star

Fri Oct 04 2024 10:37:27 GMT+0000 (Coordinated Universal Time)

@JosKlever ##wordpress ##sql #phpmyadmin

star

Fri Oct 04 2024 08:56:10 GMT+0000 (Coordinated Universal Time) https://www.aelius.com/njh/ethercard/get_d_h_c_pand_d_n_s_8ino-example.html

@nedimaon

star

Fri Oct 04 2024 07:18:01 GMT+0000 (Coordinated Universal Time) https://medium.com/coinmonks/bsc-nft-marketplace-development-1408255ea895

@LilianAnderson #bscnftmarketplace #nftmarketplacedevelopment #binancesmartchain #blockchainfornfts #defiintegration

star

Fri Oct 04 2024 07:04:14 GMT+0000 (Coordinated Universal Time)

@dark

star

Fri Oct 04 2024 05:32:54 GMT+0000 (Coordinated Universal Time) https://stackoverflow.com/questions/5404068/how-to-read-keyboard-input

@jrb9000 #python

star

Fri Oct 04 2024 04:07:37 GMT+0000 (Coordinated Universal Time)

@zahidhasan

star

Thu Oct 03 2024 22:08:15 GMT+0000 (Coordinated Universal Time)

@arutonee

star

Thu Oct 03 2024 21:49:44 GMT+0000 (Coordinated Universal Time)

@JosKlever ##wordpress ##sql #phpmyadmin

star

Thu Oct 03 2024 17:37:37 GMT+0000 (Coordinated Universal Time)

@ohio

Save snippets that work with our extensions

Available in the Chrome Web Store Get Firefox Add-on Get VS Code extension