Snippets Collections
curl --location --request POST 'https://api.insplay.eu/products' 

--header 'Content-Type: application/json' --data-raw '{"params":{

    "api_key": "Your API Key",

    "language": "et_EE"

}}'
<?php
//PHP cURL extension is needed
define('API_URL', 'https://api.insplay.eu/');
define('API_METHOD', 'products');

define('API_KEY', 'Your API key here');
define('API_LANGUAGE', 'et_EE');

function getCURL($url, $fields = array(), $headers = array()) {
	$ch = curl_init();

	$options[CURLOPT_URL] = $url;
	$options[CURLOPT_POST] = count($fields);
	$options[CURLOPT_POSTFIELDS] = json_encode($fields);
	$options[CURLOPT_RETURNTRANSFER] = true;

	if (is_array($headers) and count($headers)) {
		foreach ($headers as $k => $v) {
			$options[$k] = $v;
		}
	}

	curl_setopt_array($ch, $options);

	$result = curl_exec($ch);
	curl_close($ch);
	return $result;
}

$url = API_URL.API_METHOD;
$fields = array(
	'params' => array(
		'api_key' => API_KEY,
		'language' => API_LANGUAGE
	)
);
$headers = array(
	CURLOPT_HTTPHEADER => array('Content-Type: application/json')
);
$APIResult = json_decode(getCURL($url, $fields, $headers));

print_r($APIResult);

if (isset($API['result']) and isset($API['result']['data'])) {
	foreach ($API['result']['data'] as $product_id=>$val) {
		foreach ($val['additional_images'] as $k=>$v) {
			$fn = DATA_DIR.'product_'.$product_id.'_'.$k.'.jpg';
			$fp = fopen($fn, 'wb');
			fwrite($fp, base64_decode($val['image_base64']));
			fclose($fp);
			echo '<a href="'.$fn.'" target="_blank">'.$fn.'</a><br />';
		}
		$fn = DATA_DIR.'product_'.$product_id.'.jpg';
		$fp = fopen($fn, 'wb');
		fwrite($fp, base64_decode($val['main_image_base64']));
		fclose($fp);
		echo '<a href="'.$fn.'" target="_blank">'.$fn.'</a><br />';
	}
}
exit;
?>
import requests
import json

API_URL = "https://api.insplay.eu"
API_METHOD = "products"
API_ENDPOINT = "{}/{}".format(API_URL, API_METHOD)
API_KEY5 = "Your API Key",
data = {
    "api_key": "Your API Key",
    "language": "et_EE",
}
headers = {"content-type": "application/json"}
payload = {"params": data}
response = requests.post(API_ENDPOINT, data=json.dumps(payload), headers=headers)
print(response.json())
# Development
flutter run --flavor development --target lib/main_development.dart

# Staging
flutter run --flavor staging --target lib/main_staging.dart

# Production
flutter run --flavor production --target lib/main_production.dart
# Create a new Flutter app named my_app
very_good create flutter_app my_app --desc "My new Flutter app"

# Create a new Flutter app named my_app with a custom org
very_good create flutter_app my_app --desc "My new Flutter app" --org "com.custom.org"
dart pub global activate very_good_cli
dart pub global activate very_good_cli
[
  {
    "notificationSettingId": 1,
    "notificationSettingTypeId": 182,
    "notificationSettingType": "Email",
    "userResponse": [
      {
        "notificationOptionId": 4,
        "settingName": "Updates",
        "description": "Get notified for new feature introduced in app.",
        "isSelected": true
      },
      {
        "notificationOptionId": 1,
        "settingName": "Reminder Emails",
        "description": "Get remainders for subscribed events, membership renewals or any dues.",
        "isSelected": true
      },
      {
        "notificationOptionId": 2,
        "settingName": "Announcements",
        "description": "Notified important updates, news, or announcements.",
        "isSelected": false
      },
      {
        "notificationOptionId": 3,
        "settingName": "Poll or Survey",
        "description": "Get notified for participation in poll or survey.",
        "isSelected": true
      }
    ],
    "jUserResponse": null
  },
  {
    "notificationSettingId": 0,
    "notificationSettingTypeId": 183,
    "notificationSettingType": "Push",
    "userResponse": [
      {
        "notificationOptionId": 5,
        "settingName": "Events",
        "description": "Get notified about upcoming events.",
        "isSelected": true
      },
      {
        "notificationOptionId": 6,
        "settingName": "Documents",
        "description": "Receive document uploads and updates.",
        "isSelected": true
      },
      {
        "notificationOptionId": 7,
        "settingName": "Members & Committees",
        "description": "Stay informed about invitations.",
        "isSelected": true
      },
      {
        "notificationOptionId": 9,
        "settingName": "Fundraise",
        "description": "Stay informed about fundraising initiatives.",
        "isSelected": true
      },
      {
        "notificationOptionId": 10,
        "settingName": "Survey",
        "description": "Receive survey/poll participation requests.",
        "isSelected": true
      },
      {
        "notificationOptionId": 11,
        "settingName": "Payments",
        "description": "Get notified membership renewals and dues.",
        "isSelected": true
      },
      {
        "notificationOptionId": 12,
        "settingName": "Bills",
        "description": "Get notified with dues raised by admin.",
        "isSelected": true
      }
    ],
    "jUserResponse": null
  },
  {
    "notificationSettingId": 0,
    "notificationSettingTypeId": 184,
    "notificationSettingType": "All Notifications",
    "userResponse": [
      {
        "notificationOptionId": 13,
        "settingName": "All Notifications",
        "description": "All notification setting",
        "isSelected": false
      }
    ],
    "jUserResponse": null
  }
]
In JavaScript, there are many built-in constructors that create objects. A constructor is like a regular function, but starts with a capital letter, and is initialized with the new operator.

For example, you can use the Date() constructor with the new operator to create a new Date object that returns a string with the current date and time:

const currentDate = new Date();
console.log(currentDate);

// Output:
// Mon Aug 23 2021 15:31:00 GMT-0400 (Eastern Daylight Time)

The Date object has a number of methods that allow you to get the date and time in different formats.

One of those is the .getDate() method, which returns a number between 1 and 31 that represents the day of the month for that date. For example:

const date = new Date();
const dayOfTheMonth = date.getDate();
console.log(dayOfTheMonth); // 20

The .getMonth() method returns a number between 0 and 11. This represents the month for the date provided, where 0 is January and 11 is December. Because the number this method returns is zero-based, you need to add 1 to it to get the expected month number.

The .getFullYear() method returns a number which represents the year for the provided date.

The .getHours() method returns a number between 0 and 23. This represents the hour for the provided date, where 0 is midnight and 23 is 11 p.m.

The .getMinutes() method returns a number between 0 and 59 which represents the minutes for the provided date.

n JavaScript, the change event is used to detect when the value of an HTML element has changed:

element.addEventListener("change", () => {
    
});

A switch statement is used to compare an expression against multiple possible values and execute different code blocks based on the match. It's commonly used for branching logic.

For example, here's how to compare the expression dayOfWeek against possible values:

switch (dayOfWeek) {
  case 1:
    console.log("It's Monday!");
    break;
  case 2:
    console.log("It's Tuesday!");
    break;
  // ...cases for other workdays
  default:
    console.log("It's the weekend!");
}
    
You can add a case clause in the switch statement that checks for a match against the expression expr, followed by code to run if there's a match. Here's an example where the case clause checks that expr is equal to the string "case123":

switch (expr) {
  case 'case123':
    // Write your logic here
}
    
If your switch statement is going to have multiple cases, it is best practice to include a break statement.

The break statement will tell the JavaScript interpreter to stop executing statements. Without adding a break statement at the end of each case block, the program will execute the code for all matching cases:

switch (someVariable) {
  case 'case123':
    // Write your logic here
    break; // Terminates the switch statement
}
    
In a switch statement, the default case is executed when none of the previous case conditions match the value being evaluated. It serves as a catch-all for any other possible cases. For example:

const dayOfWeek = 7;

switch (dayOfWeek) {
  case 1:
    console.log("It's Monday!");
    break;
  case 2:
    console.log("It's Tuesday!");
    break;
  // ...cases for other workdays
  default:
    console.log("It's the weekend!");
}
    
The split() method is used to divide a string into substrings based on a specified separator. It then returns these substrings as elements of an array.

Here is an example of taking the words "Hello World" and returning an array of one element:

const greeting = "Hello World";
greeting.split(); // ["Hello World"]
    
The split method takes in a parameter known as a separator. The separator is used to tell the computer where each split should occur.

Here is an example of using an empty string as a separator:

// returns ["h", "e", "l", "l", "o"]
"hello".split(""); 
Other examples of separators can include a space " ", or a hyphen "-". If you don't provide a separator, the method will return an array with the original string as the only element.
    
To reverse an array of elements, you can use the reverse method. This method reverses the order of the elements in the array in place. The first element becomes the last, and the last element becomes the first.

Here is an example of using the reverse method:

// returns [5, 4, 3, 2, 1]
[1, 2, 3, 4, 5].reverse(); 
    
The join method takes an array of elements and joins them into a string. Similar to the split method, the join method also takes an optional separator. If you don't provide a separator, the default separator is a comma.

Here is an example of using the join method:

// returns "1-2-3-4-5"
[1, 2, 3, 4, 5].join("-");
    
class DisjoinSet
{
public:
    vector<int> rank, parent, size;
    int components;

public:
    DisjoinSet(int n)
    {
        rank.resize(n + 1, 0);
        parent.resize(n + 1);
        size.resize(n + 1, 1);
        components = n;
        for (int i = 0; i <= n; i++)
        {
            parent[i] = i;
        }
    }

    int findUltParent(int node)
    {
        if (node == parent[node])
        {
            return node;
        }
        return parent[node] = findUltParent(parent[node]);
    }

    void unionByRank(int u, int v)
    {
        int ulp_u = findUltParent(u);
        int ulp_v = findUltParent(v);
        if (ulp_u == ulp_v)
            return;
        if (rank[ulp_u] < rank[ulp_v])
        {
            parent[ulp_v] = ulp_u;
        }
        else if (rank[ulp_u] > rank[ulp_v])
        {
            parent[ulp_v] = ulp_u;
        }
        else
        {
            parent[ulp_v] = ulp_u;
            rank[ulp_u]++;
        }
    }
    void unionBySize(int u, int v)
    {
        int ulp_u = findUltParent(u);
        int ulp_v = findUltParent(v);
        if (ulp_u == ulp_v)
            return;

        if (size[ulp_u] < size[ulp_v])
        {
            parent[ulp_u] = parent[ulp_v];
            size[ulp_u] += size[ulp_v];
        }
        else
        {
            parent[ulp_v] = parent[ulp_u];
            size[ulp_v] += size[ulp_u];
        }
        components--;
    }
};
//findUltParent(u) or findUltParent(v)
//unionBySize(u, v)
//DisjoinSet ds = DisjoinSet(n)
Feeling anxious about online exams? Get valuable online exam help with MyAssignmentHelp.Co.Uk! Learn tips, strategies, and discover resources to maximize your preparation and boost your confidence on exam day.
function numberToWords(n)
{
    let limit = 1000000000000, t = 0
    // If zero console.log zero
    if (n == 0)
    {
        console.log("zero")
        return
    }
    // Array to store the powers of 10
    let multiplier = ["", "Trillion", "Billion", "Million", "Thousand"]
 
    // Array to store numbers till 20
    let first_twenty = ["", "One", "Two",
                    "Three", "Four", "Five",
                    "Six", "Seven", "Eight",
                    "Nine", "Ten", "Eleven",
                    "Twelve", "Thirteen", "Fourteen",
                    "Fifteen", "Sixteen", "Seventeen",
                    "Eighteen", "Nineteen"]
 
    // Array to store multiples of ten
    let tens = ["", "Twenty", "Thirty", "Forty", "Fifty",
            "Sixty", "Seventy", "Eighty", "Ninety"]
 
    // If number is less than 20, console.log without any
    if (n < 20)
    {
        console.log(first_twenty[n])
        return
    }
    let answer = ""
    let i = n
    while(i > 0)
    {
        /*
        Store the value in multiplier[t], i.e n = 1000000,
        then r = 1, for multiplier(million), 0 for multipliers(trillion and billion)
        multiplier here refers to the current accessible limit
        */
        let curr_hun = Math.floor(i / limit)
 
        // It might be possible that the current multiplier is bigger than your number
        while (curr_hun == 0)
        {
            // Set i as the remainder obtained when n was divided by the limit
            i %= limit
 
            // Divide the limit by 1000, shifts the multiplier
            limit /= 1000
 
            // Get the current value in hundreds, as English system works in hundreds
            curr_hun = Math.floor(i / limit)
 
            // Shift the multiplier
            t += 1
        }
 
        let flr = Math.floor(curr_hun / 100);
 
        // If current hundred is greater than 99, Add the hundreds' place
        if (curr_hun > 99)
            answer += (first_twenty[flr] + " tensundred ")
 
        // Bring the current hundred to tens
        curr_hun = curr_hun % 100
 
        // If the value in tens belongs to [1,19], add using the first_twenty
        if (curr_hun > 0 && curr_hun < 20)
            answer += (first_twenty[curr_hun] + " ")
 
        // If curr_hun is now a multiple of 10, but not 0
        // Add the tens' value using the tens array
        else if (curr_hun % 10 == 0  &&  curr_hun != 0){
            flr = Math.floor(curr_hun / 10);
            answer += (tens[flr - 1] + " ")
        }
 
        // If the value belongs to [21,99], excluding the multiples of 10
        // Get the ten's place and one's place, and console.log using the first_twenty array
        else if (curr_hun > 19  &&  curr_hun < 100){
            flr = Math.floor(curr_hun / 10);
            answer += (tens[flr - 1] + " " +
                       first_twenty[curr_hun % 10] + " ")
        }
 
        // If Multiplier has not become less than 1000, shift it
        if (t < 4)
            answer += (multiplier[t] + " ")
             
        i = i % limit
        limit = Math.floor(limit / 1000)
    }
 
    console.log(answer)
}
 
// Input 1
let n = 36
 
numberToWords(n)
n = 123456789
 
// Input 2
numberToWords(n)
n = 10101010110001
 
// Input 3
numberToWords(n)
 
// Input 4
n = 999999999
numberToWords(n)
 
<?php

function numToWordsRec($number) {
    $words = array(
        0 => 'zero', 1 => 'one', 2 => 'two',
        3 => 'three', 4 => 'four', 5 => 'five',
        6 => 'six', 7 => 'seven', 8 => 'eight',
        9 => 'nine', 10 => 'ten', 11 => 'eleven',
        12 => 'twelve', 13 => 'thirteen', 
        14 => 'fourteen', 15 => 'fifteen',
        16 => 'sixteen', 17 => 'seventeen', 18 => 'eighteen',
        19 => 'nineteen', 20 => 'twenty', 30 => 'thirty',
        40 => 'forty', 50 => 'fifty', 60 => 'sixty',
        70 => 'seventy', 80 => 'eighty',
        90 => 'ninety'
    );

    if ($number < 20) {
        return $words[$number];
    }

    if ($number < 100) {
        return $words[10 * floor($number / 10)] .
               ' ' . $words[$number % 10];
    }

    if ($number < 1000) {
        return $words[floor($number / 100)] . ' hundred ' 
               . numToWordsRec($number % 100);
    }

    if ($number < 1000000) {
        return numToWordsRec(floor($number / 1000)) .
               ' thousand ' . numToWordsRec($number % 1000);
    }

    return numToWordsRec(floor($number / 1000000)) .
           ' million ' . numToWordsRec($number % 1000000);
}

// Example usage:
$number = 1234567;
echo "Number $number in words: "
     . numToWordsRec($number);

?>
The spread operator (...) allows you to copy all elements from one array into another. It can also be used to concatenate multiple arrays into one. In the example below, both arr1 and arr2 have been spread into combinedArr:

const arr1 = [1, 2, 3];
const arr2 = [4, 5, 6];

const combinedArr = [...arr1, ...arr2];
console.log(combinedArr); // Output: [1, 2, 3, 4, 5, 6]

An arrow function is an anonymous function expression and a shorter way to write functions. Anonymous means that the function does not have a name. Arrow functions are always anonymous.

Here is the basic syntax:

() => {}
To create a named arrow function, you can assign the function to a variable:

const exampleFunction = () => {
  // code goes here
}

To call a named arrow function expression, you can reference the function by its name.

exampleArrowFunction();

Just like regular functions, arrow functions can accept multiple parameters.

Here is an example of a named arrow function with one parameter:

const greet = (name) => {
  console.log(`Hello, ${name}!`);
};
If the function only has one parameter, you can omit the parentheses around the parameter list like this:

const greet = name => {
  console.log(`Hello, ${name}!`);
};

Just like regular functions, arrow functions can return values.

Here is an example of an arrow function returning the result of multiplying two numbers:

const multiplyTwoNumbers = (num1, num2) => {
  return num1 * num2;
}

// Output: 12
console.log(multiplyTwoNumbers(3, 4)); 

If the arrow function is returning a simple expression, you can omit the return keyword and the curly braces {}. This is called an implicit return.

const multiplyTwoNumbers = (num1, num2) => num1 * num2;
If your arrow function has multiple lines of code in the function body, then you need to use the return keyword and the curly braces {}.

const getTax = (price) => {
  const taxRate = 0.08;
  const tax = price * taxRate;
  return tax;
};

The map() method is used to iterate through an array and return a new array. It's helpful when you want to create a new array based on the values of an existing array. For example:

const numbers = [1, 2, 3];
const doubledNumbers = numbers.map((number) => number * 2); // doubledNumbers will be [2, 4, 6]
Notice that the map() method takes a function as an argument. This is called a callback function, which is a function that is passed to another function as an argument. In the example above, the callback function is (number) => number * 2, and it's run on each element in the numbers array. The map() method then returns a new array with the results.

Right now the songsHTML is an array. If you tried to display this as is, you would see the songs separated by commas. This is not the desired outcome because you want to display the songs as a list. To fix this, you will need to join the array into a single string by using the join() method.

The join() method is used to concatenate all the elements of an array into a single string. It takes an optional parameter called a separator which is used to separate each element of the array. For example:

const exampleArr = ["This", "is", "a", "sentence"];
const sentence = exampleArr.join(" "); // Separator takes a space character
console.log(sentence); // Output: "This is a sentence"

Optional chaining (?.) helps prevent errors when accessing nested properties that might be null or undefined. For example:

const user = {
  name: "Quincy",
  address: {
    city: "San Francisco",
    state: "CA",
    country: "USA",
  },
};

// Accessing nested properties without optional chaining
const state = user.address.state; // CA

// Accessing a non-existent nested property with optional chaining
const zipCode = user.address?.zipCode; // Returns undefined instead of throwing an error

The sort() method converts elements of an array into strings and sorts them in place based on their values in the UTF-16 encoding.

const names = ["Tom", "Jessica", "Quincy", "Naomi"];
names.sort() // ["Jessica", "Naomi", "Quincy", "Tom"]

To sort the songs in alphabetical order by title, you will need to pass in a compare callback function into your sort() method.

Here is an example of sorting a list of fruits by name.

const fruits = [
  { name: "Apples", price: 0.99 },
  { name: "Blueberries", price: 1.49 },
  { name: "Grapes", price: 2.99 },
];

fruits.sort((a, b) => {
  if (a.name < b.name) {
    return -1;
  }

  if (a.name > b.name) {
    return 1;
  }

  return 0;
});

The sort() method accepts a compare callback function that defines the sort order.

In this example, the first condition (a.name < b.name) checks if the name of the first fruit is less than the name of the second fruit. If so, the first fruit is sorted before the second fruit.

Strings are compared lexicographically which means they are compared character by character. For example, "Apples" is less than "Bananas" because "A" comes before "B" in the alphabet.

The reason why this example is returning numbers is because the sort() method is expecting a number to be returned. If you return a negative number, the first item is sorted before the second item.

const fruits = [
  { name: "Apples", price: 0.99 },
  { name: "Blueberries", price: 1.49 },
  { name: "Grapes", price: 2.99 },
];

fruits.sort((a, b) => {
  if (a.name < b.name) {
    return -1;
  }

  if (a.name > b.name) {
    return 1;
  }

  return 0;
});

The find() method retrieves the first element within an array that fulfills the conditions specified in the provided callback function. If no element satisfies the condition, the method returns undefined.

In the example below, the find() method is used to find the first number greater than 25:

const numbers = [10, 20, 30, 40, 50];

// Find the first number greater than 25
const foundNumber = numbers.find((number) => number > 25);
console.log(foundNumber); // Output: 30

To get the index for the current song, you can use the indexOf() method. The indexOf() array method returns the first index at which a given element can be found in the array, or -1 if the element is not present.

const animals = ["dog", "cat", "horse"];
animals.indexOf("cat") // 1

The forEach method is used to loop through an array and perform a function on each element of the array. For example, suppose you have an array of numbers and you want to log each number to the console.

const numbers = [1, 2, 3, 4, 5];

// Using forEach to iterate through the array
numbers.forEach((number) => {
  console.log(number); // 1, 2, 3, 4, 5
});

textContent sets the text of a node and allows you to set or retrieve the text content of an HTML element.

<div id="example">This is some text content</div>
Example Code
const element = document.getElementById('example');
console.log(element.textContent); // Output: This is some text content

In earlier steps, you learned how to work with the sort() method to sort the songs in alphabetical order. Another use case for the callback function is to randomize an array.

One way to randomize an array of items would be to subtract 0.5 from Math.random() which produces random values that are either positive or negative. This makes the comparison result a mix of positive and negative values, leading to a random ordering of elements.

const names = ["Tom", "Jessica", "Quincy", "Naomi"];
names.sort(() => Math.random() - 0.5);

createElement() is a DOM method you can use to dynamically create an element using JavaScript. To use createElement(), you call it, then pass in the tag name as a string:

// syntax
document.createElement(tagName)

// example
document.createElement('div')

You can also assign it to a variable:

const divElement = document.createElement('div')

Now that you've created the button, you need to assign it a text. To do this, you need to use the createTextNode() method of DOM.

The createTextNode() method is used to create a text node. To use it, you call it and pass in the text as a string:

document.createTextNode("your text")

You can also assign it to a variable:

const myText = document.createTextNode("your text")

Now that you've created the resetButton, you need to assign it an id and aria-label attributes. JavaScript provides the id and ariaLabel properties you need to use for this.

For example, element.id would set an id attribute, and element.ariaLabel would set an aria-label attribute. Both of them accept their values as a string.

appendChild() lets you add a node or an element as the child of another element. In the example below, the text "Click me" would be attached to the button:

const parentElement = document.createElement("button")
const parentElementText = document.createTextNode("Click me")

// attach the text "Click me" to the button
parentElement.appendChild(parentElementText)

function custom_modify_query( $query ) {
    if ( ! is_admin() && $query->is_main_query() ) {
        if ( is_shop() ) {
            $query->set( 'posts_per_page', 12 );
        }
    }
}
add_action( 'pre_get_posts', 'custom_modify_query' );
// Check product has sale
function is_product_on_sale($product_id) {
    $product = wc_get_product($product_id);

    if ($product->is_on_sale()) {
        return true; 
    }

    if ($product->is_type('variable')) {
        $variants = $product->get_children();

        foreach ($variants as $variant_id) {
            $variant = wc_get_product($variant_id);
            if ($variant->is_on_sale()) {
                return true;
            }
        }
    }

    return false;
}
// Check product has sale
function count_sale_products() {
    $transient_key = 'count_sale_products';
    $cached_count = get_transient($transient_key);
    if ($cached_count !== false) {
        return $cached_count;
    } else {
        $products = wc_get_products(['return' => 'ids', 'status' => 'publish', 'limit' => -1, 'type' => array('simple', 'variable', 'bundle', 'external', 'grouped')]);
        $saleProduct = [];
        foreach ($products as $product_id) {
            if (is_product_on_sale($product_id)) {
                $saleProduct[] = $product_id;
            }
        }
        $sale_count = count($saleProduct);
        set_transient($transient_key, $sale_count, 5 * MINUTE_IN_SECONDS);
        return $sale_count;
    }
}
function get_discounted_variants_of_product($product_id) {
    $product = wc_get_product($product_id);

    if ($product->is_type('variable')) {
        $variants = $product->get_children();

        $discounted_variants = array();

        foreach ($variants as $variant_id) {
            $variant = wc_get_product($variant_id);
			//print_r($variant->status); die;
			if( $variant->status == 'publish')
				$discounted_variants[] = array(
					'id' => $variant->get_id(),
					'sale_price' => $variant->get_sale_price(),
					'regular_price' => $variant->get_regular_price(),
					'name' => $variant->get_name(),
					'sku' => $variant->get_sku(),
				);
        }

        return $discounted_variants;
    }
    return false;
}

function getStockStatusCountProduct($instock = true){
	$stock_status = 'instock';
	if(!$instock) $stock_status = 'outofstock';
	$args = array(
		'stock_status' => $stock_status,
		'limit' => -1,
		'status' => 'publish',
		'type' => array('simple', 'variable'),
	);
	$products = wc_get_products( $args );
	return count($products);
}
function customRatingScoreHTML($productID){
	$product = wc_get_product($productID);
	$average      = $product->get_average_rating();
	$rating_whole = floor($average);
	$rating_fraction = $average - $rating_whole;
	$flug = 0;
	for($i = 1; $i <= 5; $i++){
		if( $i <= $rating_whole ){
			echo '<i class="fas fa-star"></i>';
		}
		else{
			if( $rating_fraction > 0 && $flug == 0 ){
				 echo '<i class="fas fa-star-half-alt"></i>';
				$flug = 1;
			}
			else{
				echo '<i class="far fa-star empty"></i>';
			}
		}
	}
}
function customShopGridShortcode($atts=[]){
	ob_start();
	$availability = isset($_GET['availability'])?$_GET['availability']:'instock';
	$category = isset($_GET['category'])?$_GET['category']:'';
	$tag = isset($_GET['tg'])?$_GET['tg']:'';
	//$on_sale = isset($_GET['on_sale'])?$_GET['on_sale']:'';
	$orderBy = isset($_GET['orderby'])?$_GET['orderby']:'';
	$keyword = isset($_GET['s'])?$_GET['s']:'';
	$paged = max(get_query_var('paged'),1);
	$args = [
		'post_type' => ['product'],
		'paged' => $paged,
		'posts_per_page' => 12,
	];
	if(!empty($category) && $category!= 'all')
		$args['tax_query'] = [
			'relation' => 'AND',  
			[
				'taxonomy' => 'product_cat',
				'field' => 'slug',
				'terms' => array( $category ), 
			],
		];
	if(!empty($tag)){
		if(array_key_exists ('tax_query',$args)){
			$args['tax_query'][] = [
				'taxonomy' => 'product_tag',
				'field' => 'slug',
				'terms' => array( $tag ), 
			];
		}
		else{
			$args['tax_query'] = [
				'relation' => 'AND',  
				[
					'taxonomy' => 'product_tag',
					'field' => 'slug',
					'terms' => array( $tag ), 
				],
			];
		}
	}
// 	if(!empty($on_sale) && $on_sale == 1){
		
// 	}
	if(!empty($availability)){
		if($availability == 'sale'){
			$products = wc_get_products( ['return' => 'ids','status' => 'publish','limit' => -1,'type' => array('simple', 'variable', 'bundle','external','grouped')] );
			$saleProduct = [];
			foreach($products as $vv){
				if(is_product_on_sale($vv)){
					$saleProduct[] = $vv;
				}
			}
			if(!empty($saleProduct))
				$args['post__in'] = $saleProduct;
			else
				$args['post__in'] = [0];
			
// 			if(array_key_exists('tax_query',$args)){
// 				$args['tax_query'][] = [
// 					 'key' => '_sale_price',
// 					 'value' => '',
// 					 'compare' => '!='
// 				];
// 			}
// 			else{
// 				$args['tax_query'] = [
// 					'relation' => 'AND',  
// 					[
// 						'key' => '_sale_price',
//                 		'value' => '',
//                 		'compare' => '!='
// 					],
// 				];
// 			}
		}
		else{
			$products = wc_get_products( ['stock_status' => $availability,'return' => 'ids','status' => 'publish','limit' => -1,'type' => array('simple', 'variable', 'bundle','external','grouped')] );
			if(!empty($products))
				$args['post__in'] = $products;
			else
				$args['post__in'] = [0];
		}
		
		//print_r($products);
		
	}
	if(!empty($orderBy)){
		if($orderBy == 'popularity'){
			$args['meta_key'] = 'total_sales';
			$args['orderby'] = 'meta_value_num';
			$args['order'] = 'DESC';
		}
		if($orderBy == 'rating'){
			$args['meta_key'] = '_wc_average_rating';
			$args['orderby'] = 'meta_value_num';
			$args['order'] = 'DESC';
		}
		if($orderBy == 'date'){
			$args['orderby'] = 'date';
			$args['order'] = 'DESC';
		}
		if($orderBy == 'price'){
			$args['meta_key'] = '_price';
			$args['orderby'] = 'meta_value_num';
			$args['order'] = 'ASC';
		}
		if($orderBy == 'price-desc'){
			$args['meta_key'] = '_price';
			$args['orderby'] = 'meta_value_num';
			$args['order'] = 'DESC';
		}
	}
	if(!empty($keyword)){
		$args['s'] = $keyword;
	}
	if(isset($_GET['dev']))
		print_r($args);
	$the_query = new WP_Query( $args );
?>

<div class="customShopGrid-wrap">
	<form id="frmFilterProduct" method="GET" action="">
		<div class="frmFilterProduct-ajax">
			<?php 
				$sort_arr = [
						'menu_order' => __('Default Sorting'),	
						'popularity' => __('Best Selling'),
						'rating' => __('Average Rating'),
						'date' => __('Latest Product'),
						'price' => __('Price Low To High'),
						'price-desc' => __('Price High To Low'),
				];
			?>
			<div class="customShopGrid-order-wrap">
				<div class="customShopGrid-order orderbyPC">
					<span>Sort By:</span>
					<select id="orderby" class="slOrder" name="orderby">
						<?php foreach($sort_arr as $key => $value):?>
						<option value="<?php echo $key; ?>" <?php if($orderBy == $key) echo 'selected'?>><?php echo $value; ?></option>
						<?php endforeach; ?>
					</select>
				</div>
			</div>
	<div class="customShopGrid">
		
		<div class="customShopGrid-left">
			<div class="customShopGrid-filter">
				<div class="customShopGrid-filter-top customShopGrid-filter-space">
					<h2 class="customShopGrid-filter-heading">Filter Products</h2>
					<img src="https://vancitylabs.co/wp-content/uploads/2024/04/setting-ic.svg" />
				</div>
				<div class="customShopGrid-filter-list">
					
					<div class="customShopGrid-filter-group">
						<div class="customShopGrid-filter-group-head customShopGrid-filter-space">
							<h3 class="customShopGrid-filter-heading">Availability</h3>
						</div>
						<div class="customShopGrid-filter-group-content">
							<ul>
								<li>
									<label class="custom-checkbox">
										<input id="Availability-instock" class="filter-checkbox" type="checkbox" name="availability" value="instock" <?php if($availability == 'instock') echo 'checked' ?> />
										<span style='font-size: 18px'>In Stock (<?php echo getStockStatusCountProduct()?>)</span>
									</label>
								</li>
								<li>
									<label class="custom-checkbox">
										<input id="Availability-outstock" class="filter-checkbox" type="checkbox" name="availability" value="outofstock" <?php if($availability == 'outofstock') echo 'checked' ?> />
										<span style='font-size: 18px'>Out of Stock (<?php echo getStockStatusCountProduct(false)?>)</span>
									</label>
								</li>
								<li>
									<label class="custom-checkbox">
										<input id="Availability-outstock" class="filter-checkbox" type="checkbox" name="availability" value="sale" <?php if($availability == 'sale') echo 'checked' ?> />
										<span style='font-size: 18px'>On Sale (<?php echo count_sale_products();?>)</span>
									</label>
								</li>
							</ul>
						</div>
					</div>
					<!--end group-->
					<?php  
						$cats = get_terms([
							'taxonomy' => 'product_cat',
							'hide_empty' => true,
							'parent'   => 0,
						]);
						if(!empty($cats)):
					?>
					<div class="customShopGrid-filter-group">
						<div class="customShopGrid-filter-group-head customShopGrid-filter-space">
							<h3 class="customShopGrid-filter-heading">Categories</h3>
						</div>
						<div class="customShopGrid-filter-group-content">
							<ul>
								<li>
									<label class="custom-checkbox">	
										<input class="filter-checkbox" type="checkbox" name="category" value="all" <?php if($category == 'all') echo 'checked' ?> />
										<span style='font-size: 18px'>All</span>
									</label>
								</li>
								<?php 
									foreach ($cats as $key => $value): 
									$childs = get_term_children( $value->term_id, 'product_cat' );
									$isChildOpen = false;
									if(!empty($childs)): 
										foreach($childs as $child):
											$child = get_term_by('id',$child,'product_cat');
											
											//print_r($category);
											if($category == $child->slug){
												$isChildOpen =  true;
												break;
											}
										endforeach;
									endif;
									
								?>
									<li class="<?php if(!empty($childs)) echo 'has-child'; ?>">
										<?php if(!empty($childs)):?>
											<div class="custom-checkbox">
										<?php else: ?>	
											<label class="custom-checkbox">	
										<?php endif;?>	
											<input class="filter-checkbox" type="checkbox" name="category" value="<?php echo $value->slug ?>" <?php if($category == $value->slug) echo 'checked' ?> />
												
											<span style='font-size: 18px'><?php echo $value->name ?> (<?php echo $value->count ?>)</span>
										<?php if(!empty($childs)):?>
											</div>
										<?php else: ?>
											</label>
										<?php endif;?>			
										<?php if(!empty($childs)): ?>
										<ul class="customShopGrid-filter-group-content-child" style="<?php if(!$isChildOpen) echo 'display: none;'?>">
											<?php foreach($childs as $child): $child = get_term_by('id',$child,'product_cat'); if($child->count > 0): ?>
												<li>
													<label class="custom-checkbox">
														<input class="filter-checkbox" type="checkbox" name="category" value="<?php echo $child->slug ?>" <?php if($category == $child->slug) echo 'checked' ?> />
														<span style='font-size: 18px'><?php echo $child->name;  ?> (<?php echo $child->count ?>)</span>
													</label>
												</li>
											<?php endif; endforeach ?>
										</ul>
										<?php endif;?>
									</li>
								<?php endforeach ?>
							</ul>
						</div>
					</div>
					<!--end group-->
					<?php endif; ?>
					
					<div class="customShopGrid-filter-reset">
						<a class="customShopGrid-filter-reset-button" href="<?php echo get_permalink( wc_get_page_id( 'shop' ) )?>">Reset Filters</a>
					</div>
				</div>
			</div>
		</div>
		<div class="customShopGrid-right">
			<div class="customShopGrid-order show-mb-flex" hidden>
				<h3 class="customShopGrid-filter-heading">Sort by:</h3>
				<div class="orderbyMB">
				</div>
			</div>
			<!--end group-->
			<?php if ( !empty($keyword) ) :?>
				<p class="customShopGrid-seach-keyword-label">Search results for <span>"<?php echo $keyword; ?>"</span> <a href="https://vancitylabs.co/shop/">Remove</a></p>
			<?php endif; ?>
			<div class="customShopGrid-list">
				
				<?php if ( $the_query->have_posts() ) :?>
				<?php while ( $the_query->have_posts() ) : $the_query->the_post(); ?>
				<div class="customShopGrid-product">
					<div class="customShopGrid-product-inner">
					   <div class="customShopGrid-product-image-wrap">
						   <?php 
						   		$product = wc_get_product(get_the_ID());
								$product_type = $product->get_type();
								if(!$product->is_in_stock()):
						   ?>
						  		<span class="customShopGrid-product-stockout customShopGrid-product-label">Out of stock</span>  
						   <?php endif; ?>
						   <?php if(is_product_on_sale(get_the_ID())):?>
						   		<span class="customShopGrid-product-has-sale customShopGrid-product-label">Sale</span>  
						   <?php endif; ?>
						  <div class="customShopGrid-product-image">
							 <a href="<?php the_permalink();?>" tabindex="0"> 
							 	<?php the_post_thumbnail('medium')?>
							 </a>
						  </div>
					   </div>
					   <div class="customShopGrid-product-content">
						  <div class="customShopGrid-product-content-inner">
							  <div class="customShopGrid-product-ratting-wrap">
								<div class="top-rated-rating">
									<?php 
							   			$types = get_the_terms(get_the_ID(),'product-type');
										$type = '';
										if(!empty($types)) $type = reset($types);
										if(is_object($type)):
											$color = get_field('color',$type);
									?>
								   <span class="customShopGrid-product-type" style="<?php if($color) echo 'background:'.$color;?>"><?php echo $type->name;?></span>
									<?php endif; ?>
								   <span class="customShopGrid-product-ratting">
								   		<span class="customShopGrid-product-user-ratting">
								   			<?php customRatingScoreHTML(get_the_ID());?>              
									   </span>
									   <span class="customShopGrid-product-user-ratting-count" hidden>(<?php echo $product->get_rating_count(); ?>)</span>
									</span>
									<?php 
										$thc = get_field('thc');
										if($thc > 0):
									?>
									<span class="customShopGrid-product-thc"><b>THC</b> <?php echo $thc.'%'?></span>
									<?php endif; ?>
								</div>
							 </div>
							 <h4 class="customShopGrid-product-title"><a href="<?php the_permalink();?>" tabindex="0"><?php the_title();?></a></h4>
							 
							 <?php 
								$add_to_card_id = get_the_ID();
							  	$discounted_variants = get_discounted_variants_of_product(get_the_ID());
								if($discounted_variants):
									$add_to_card_id = $discounted_variants[0]['id'];
							 ?>
							  <select class="customShopGrid-product-list-variable">
							  	<?php 
										foreach($discounted_variants as $key => $value):
											//print_r($value);
											$variable_price = ($value['sale_price']> 0)?$value['sale_price'] : $value['regular_price'];
											$name_parts = explode(' - ', $value['name']);
											//$variable_price = 0;
								?>
								  <option value="<?php echo $value['id']?>" <?php if(strtolower(end($name_parts)) == '28g'){$add_to_card_id = $value['id']; echo 'selected';}?>><?php echo end($name_parts);?> - $<?php echo $variable_price;?></option>
								<?php endforeach;?>
							  </select>
							  <?php else: ?>
							  <div class="customShopGrid-product-price">
								  <?php woocommerce_template_loop_price();?>
							  </div>
							  <?php endif;?>
							  <div class="wrap-btn">
								  <?php if($product_type !== 'bundle'):?>
								 	<a class="pb-btn-style add_to_cart_button ajax_add_to_cart" href="<?php site_url();?>?add-to-cart=<?php echo $add_to_card_id;?>&quantity=1" data-quantity="1" data-product_id="<?php echo $add_to_card_id;?>"><span>Add to cart</span> <img src="https://vancitylabs.co/wp-content/uploads/2024/04/right-arrow.svg" /></a>
								  <?php else: ?>
								  	<a class="pb-btn-style" href="<?php the_permalink(); ?>"><span>Buy Now</span> <img src="https://vancitylabs.co/wp-content/uploads/2024/04/right-arrow.svg" /></a>
								  <?php endif;?>
							  </div>
						  </div>
					   </div>
					</div>
				</div>
				<?php endwhile;?>
				<?php else: ?>
					<p>No product found!</p>
				<?php endif;wp_reset_postdata();?>
				
			</div>
			<?php if($the_query->max_num_pages > 1):?>
			<div class="customShopGrid-pagenavi">
				<?php echo paginate_links(array(
					'total'   => $the_query->max_num_pages,
					'current' => $paged,
					'prev_text' => '<img src="'.CHILD_THEME_URI.'/images/prev-arrow-green.svg" />',
					'next_text' => '<img src="'.CHILD_THEME_URI.'/images/next-arrow-green.svg" />'
				));?>
			</div>
			<?php endif;?>
		</div>
	</div>
	</div>
	</form>
	<script type="text/javascript">
		(function($){
			var sortDiv = $('body').find('#orderby');
			//var spinner = $('')
			$('body').on('change','.filter-checkbox',function(){
				$(this).parents('li').siblings().find('.filter-checkbox').prop('checked', false)
				$('#frmFilterProduct').submit();
			})
			$('body').on('click','.customShopGrid-filter-group-head',function(e){
				$(this).toggleClass('close')
				$(this).parent().find('.customShopGrid-filter-group-content').slideToggle();
			})
			$('body').on('change','.slOrder',function(){
				$('#frmFilterProduct').submit();
			})
			$('body').on('click','.customShopGrid-filter-top',function(e){
				$(this).toggleClass('close')
				$(this).parent().find('.customShopGrid-filter-list').slideToggle();
			})
			$('body').on('click','li.has-child .custom-checkbox',function(e){
				var $div = $(this);
				var divOffset = $div.offset();
				var clickX = e.pageX - divOffset.left;
				if (clickX <= 28) {
					$(this).parents('ul').find('.filter-checkbox').prop('checked', false);
					$(this).find('.filter-checkbox').prop('checked', true)
					$('#frmFilterProduct').submit();
				}
				else{
					$(this).parent().find('.customShopGrid-filter-group-content-child').slideToggle();
				}
			})
			function moveSortDiv(){
				if($(window).innerWidth() < 768){
					if(!$('.orderbyMB .slOrder').length)
						sortDiv.appendTo('.orderbyMB');
				}
				else{
					if(!$('.orderbyPC .slOrder').length)
						sortDiv.appendTo('.orderbyPC');
				}
			}
			moveSortDiv();
			$(window).on('resize',function(){
				moveSortDiv();
			})
			function customAjaxSend(form,fullUrl){
				history.pushState({}, '', fullUrl);
				$.ajax({
					url: fullUrl,
					method: form.attr('method'),
					data: form.serialize(),
					dataType: 'html',
					beforeSend: function () {
						$('.customShopGrid-list').html(`<div class="cspinner">
				<div class="loadingio-spinner" style="/* display: none; */">
					<div class="loadingio-spinner-spinner-gakt1tin5n">
						<div class="ldio-7ufvexzivn">
							<div></div>
							<div></div>
							<div></div>
							<div></div>
							<div></div>
							<div></div>
							<div></div>
							<div></div>
							<div></div>
							<div></div>
							<div></div>
							<div></div>
						</div>
					</div>
				</div>
			</div>`);
						$('.cspinner .loadingio-spinner').show();
						$('.customShopGrid-pagenavi').css('display','none');
					},
					success: function(response) {
						 	const html = $(response);
							const items = html.find('.frmFilterProduct-ajax');
							$('#frmFilterProduct').html(items);
							$('.cspinner .loadingio-spinner').hide();
							$('.customShopGrid-pagenavi').css('display','flex');
// 							if (items.length) {
// 								$('.project-box').html(items);
// 							} else {
// 								$('.project-box').html('<p>Aucun résultat trouvé</p>');
// 							}
							//console.log(response);
							moveSortDiv();
					},
					error: function(jqXHR, textStatus, errorThrown) {
						console.log('Error submitting form');
						console.log(textStatus, errorThrown);
					}
				});
			}
			$('#frmFilterProduct').on('submit', function(e) {
				e.preventDefault(); 
				var form = $(this); 
				var url = form.attr('action'); 
				var fullUrl = url + '?' + form.serialize();
				history.pushState({}, '', fullUrl);
				let currentUrl = window.location.href;
				let newUrl = currentUrl.replace(/page\/\d+\//, '');
				customAjaxSend(form, newUrl);
			});
			$('body').on('click','.customShopGrid-pagenavi a',function(e){
				e.preventDefault();
				var form = $('#frmFilterProduct'); 
				var fullUrl = $(this).attr('href');
				$('html, body').animate({
					scrollTop: $(".customShopGrid-right").offset().top - 300
				}, 1000); // 1000 milliseconds for the scroll animation
				customAjaxSend(form, fullUrl);
// 				setTimeout(function() {
					
// 				}, 200); // 1000 milliseconds delay before starting the scroll
				
			})
		})(jQuery)
	</script>
</div>
<?php	return ob_get_clean();
}
add_shortcode('customShopGrid','customShopGridShortcode');
dependencies {
  implementation("com.google.android.ump:user-messaging-platform:2.2.0")
}
This is a playground to test JavaScript. It runs a completely standard copy of Node.js on a virtual server created just for you. Every one of npm’s 300,000+ packages are pre-installed, so try it out:
This is a playground to test JavaScript. It runs a completely standard copy of Node.js on a virtual server created just for you. Every one of npm’s 300,000+ packages are pre-installed, so try it out:
// Import the functions you need from the SDKs you need

import { initializeApp } from "firebase/app";
 
 
import is not yet supported in RunKit.

import { getAnalytics } from "firebase/analytics";

// TODO: Add SDKs for Firebase products that you want to use

// https://firebase.google.com/docs/web/setup#available-libraries

​

// Your web app's Firebase configuration

// For Firebase JS SDK v7..0 and later, measurementId is optional
20
const firebaseConfig = {

  apiKey: "AIzaSyAG_Fk7ftN5dN7WzmvR4ZKXlDe8aYCZwPw",

  authDomain: "vscode-563f2.firebaseapp.com",

  projectId: "vscode-563f2",

  storageBucket: "vscode-563f2.appspot.com",

  messagingSenderId: "675466337672",

  appId: "1:675466337672:web:ea15fe47d0aee63c2aee3d",

  measurementId: "G-RZ4LJN5S1L"

};

​

// Initialize Firebase

const app = initializeApp(firebaseConfig);

const analytics = getAnalytics(app);
// Let's show where the Internation Space Station currently is.

console.log("Let's see where the ISS is with Node " + process.version);

​

// We can use any package from NPM since they are all built in.

var getJSON = require("async-get-json"); 

​

// And we can use ES7 async/await to pull the ISS's position from the open API.

var result = await getJSON("http://api.open-notify.org/iss-now.json");

​

// RunKit will automatically display the last statement and try to find its best representation:

result.iss_position;
// Let's show where the Internation Space Station currently is.

console.log("Let's see where the ISS is with Node " + process.version);

​

// We can use any package from NPM since they are all built in.

var getJSON = require("async-get-json"); 

​

// And we can use ES7 async/await to pull the ISS's position from the open API.

var result = await getJSON("http://api.open-notify.org/iss-now.json");

​

// RunKit will automatically display the last statement and try to find its best representation:

result.iss_position;
This is a playground to test JavaScript. It runs a completely standard copy of Node.js on a virtual server created just for you. Every one of npm’s 300,000+ packages are pre-installed, so try it out:
import auto from '@rollup/plugin-auto-install';
import resolve from '@rollup/plugin-node-resolve';

export default {
  input: 'src/index.js',
  output: {
    dir: 'output',
    format: 'cjs'
  },
  plugins: [auto(), resolve()]
};
npm install @rollup/plugin-auto-install --save-dev
⨠ Open-source
⇨ Pros
◦ If you are choosing an open-source project as an alternative to crypto.com, you'll enjoy a lot of customization features that are free to use and modify your platform. so the cost will be for development, customization, hosting, and maintenance.

⇨ Cons
◦ Starting your open-source crypto exchange platform takes a lot of time and investment and requires a skilled professional development team.
◦ Basically, open-source software needs proper guidance and monitoring to maintain platform security and update regularly. so that you'll need an expert for security maintenance.
◦ Open source projects, in some scenarios, lag in the incorporation of advanced security options compared to white-label solutions. It takes time to get into more complexity and requires more investment.
◦ For ongoing maintenance and support for your platform, you may use your in-house expert or outsource your needed tech expert in your field.

⨠ crypto.com clone

⇨ Pros
◦ Whereas choosing your crypto.com clone script makes it easy to incorporate your feature-rich platform and provides a faster way to establish your presence in the market
◦ A renowned crypto.com clone solution provider gives your platform more cable without compromising the level of security features.
◦ Integrating a wide range of advanced features and functionalities into your platform is the simplest way to choose white-label crypto.com.
◦ Choosing a white-label solution provider also covers ongoing support and maintenance for your platform if you're facing any outages or maintenance services. 

⇨ Cons
◦ If you choose a white-label solution, you will have to pay a licensing fee, which may lead to recurring costs because of your choice of complexity package level.
◦ In some other solution providers, vendor-locked features are available at cheaper prices. To keep it, it is not usable for your platform growth and it may lead a major threats for the platform upgrade.
◦ Some providers provide their services at a basic level, so it needs improvement for your platform in the competitive market.

The final ultimate decision is entirely your choice because every need and desire has been desired, but not in the case of one legit solution provider who avails greater crypto exchange development for their clients in the competitive market. A company that fills this position Appticz, because of this enterprise, has a lot of hands-on experience handling crypto.com clone scripts or any other script project effortlessly. so if you plan to launch your crypto business take a call from the tech experts; they will reach out and provide a proper business way.
//HTML
<div class="text-center mb-3">
          <div class="profile-photo-wrapper">
            <img src="https://cdn.create.vista.com/api/media/small/248105354/stock-vector-user-vector-icon-grey-background" alt src="assets/images/user.jpg" class="img-fluid rounded-circle profile-photo">
            <div class="edit-photo-wrapper">
              <a href="#" (click)="enableEditMode($event)" class="edit-link">Edit</a>
              <label [class.disabled-icon]="!isEditMode" for="photoUpload" class="photo-upload-icon">
                <i class="bi bi-camera"></i>
              </label>
            </div>
            <input type="file" id="photoUpload" formControlName="photo" class="d-none" (change)="onPhotoChange($event)" [readonly]="!isEditMode" >
          </div>
        </div>

//TS
import { Component, OnInit } from '@angular/core';
import { FormGroup, FormControl, Validators, FormBuilder } from '@angular/forms';
import { MatSnackBar } from '@angular/material/snack-bar';
import { UserProfile } from '../Models/UserProfile';
import { UserService } from '../Services/userprofile.service';
import { Router, ActivatedRoute } from '@angular/router';
import { Location } from '@angular/common';
import { CommonModule } from '@angular/common';
import { ReactiveFormsModule } from '@angular/forms';
import { updateUser } from '../shared/update-user';

declare var $: any; // Import jQuery

@Component({
  selector: 'app-profile-page',
  standalone: true,
  imports: [CommonModule, ReactiveFormsModule],
  templateUrl: './profile-page.component.html',
  styleUrls: ['./profile-page.component.css']
})
export class ProfilePageComponent implements OnInit {
  profileForm: FormGroup;
  user!: updateUser;
  isEditMode = false;
  errorMessage = '';

  constructor(
    private userService: UserService,
    private router: Router,
    private fb: FormBuilder,
    private location: Location) 
  {
    this.profileForm = this.fb.group({
      email: ['', [Validators.required, Validators.email]],
      name: ['', [Validators.required, Validators.minLength(3), Validators.maxLength(20)]],
      surname: ['', [Validators.required, Validators.minLength(3), Validators.maxLength(20)]],
      phoneNumber: ['', [Validators.required, Validators.maxLength(10)]],
      physical_Address: ['', [Validators.required, Validators.maxLength(255)]],
      photo: ['']
    });
  }

  ngOnInit(): void {
    const userId = JSON.parse(localStorage.getItem('User')!).userId;
    console.log('User ID from local storage:', userId);
    this.userService.getUserById(userId).subscribe({
      next: (result) => {
        console.log('User data received:', result);
        this.user = result;
        this.profileForm.patchValue(this.user);
      },
      error: () => {
        console.error('Error fetching user profile:'); // Add error console log
        alert('Error fetching user profile');
      }
    });
    this.isEditMode = false;
  }

  clearForm() {
    this.profileForm.reset();
  }

  enableEditMode(event: Event) {
    event.preventDefault();
    this.isEditMode = true;
    this.profileForm.enable();
  }

  openSaveModal() {
    if (this.profileForm.invalid) {
      this.showValidationErrors();
      $('#errorModal').modal('show');
      return;
    }
    $('#saveConfirmationModal').modal('show');
  }

  showValidationErrors() {
    const invalidFields: string[] = [];
    Object.keys(this.profileForm.controls).forEach(key => {
      const controlErrors = this.profileForm.get(key)?.errors;
      if (controlErrors) {
        Object.keys(controlErrors).forEach(errorKey => {
          invalidFields.push(`${key}: ${errorKey}`);
        });
      }
    });
    this.errorMessage = `Please enter a valid input: ${invalidFields.join(', ')}`;
  }

  dismissModal() {
    $('#saveConfirmationModal').modal('hide');
  }

  dismissErrorModal() {
    $('#errorModal').modal('hide');
  }

  confirmSave() {
    this.dismissModal();
    this.onSubmit();
    this.isEditMode = false; // Disable edit mode after confirmation
  }

  onSubmit() {
    if (this.profileForm.valid) {
      const userId = JSON.parse(localStorage.getItem('User')!).userId;
      this.userService.updateUser(userId,this.profileForm.value).subscribe({
        next: (result) => {
          console.log('User to be updated:', result);
          this.router.navigateByUrl(`/ProfilePage/${userId}`);
          alert('Successfully updated profile');
        },
        error: () => {
          console.error('Error updating user profile:');
          alert('Error updating profile');
        }
      });
    }
  }

  onPhotoChange(event: Event): void {
    if (!this.isEditMode) return;

    const input = event.target as HTMLInputElement;
    if (input.files && input.files[0]) {
      const reader = new FileReader();
      reader.onload = (e: any) => {
        const img = document.querySelector('.profile-photo') as HTMLImageElement;
        img.src = e.target.result;
      };
      reader.readAsDataURL(input.files[0]);
    }
  }

  goBack() {
    const userTypeId = JSON.parse(localStorage.getItem('User')!).userTypeId;
    const userId = JSON.parse(localStorage.getItem('User')!).userId;
    if (userTypeId === 1) {  // Ensure userTypeID is compared as string
      this.router.navigateByUrl(`/OwnerHome/${userId}`);
    } else if (userTypeId === 2) {
      this.router.navigateByUrl(`/EmployeeHome/${userId}`);
    } else if (userTypeId === 3) {
      this.router.navigateByUrl(`/Home/${userId}`);
    }
  }

  changePassword() {
    this.router.navigateByUrl('/ChangePasswordPage');
  }
}
The Alphacodez Cryptocurrency Exchange Script is a robust solution for launching secure and efficient trading platforms, featuring user management, a high-performance trading engine, and wallet integration. It offers advanced security measures and customization options. Ongoing support and maintenance ensure smooth operation.
vector<int> spiralPrint(vector<vector<int>> v, int r, int c) {
  vector<int> ans;
  int count = 0;
  ;
  int total = r * c;
  int startingRow = 0;
  int endingRow = r - 1;
  int startingCol = 0;
  int endingCol = c - 1;

  while (count < total) {
    // print starting row
    for (int i = startingCol; i <= endingCol && count < total; i++) {
      ans.push_back(v[startingRow][i]);
      count++;
    }
    startingRow++;
    // printing ending col
    for (int i = startingRow; i <= endingRow && count < total; i++) {
      ans.push_back(v[i][endingCol]);
      count++;
    }
    endingCol--;
    // printing ending row
    for (int i = endingCol; i >= startingCol && count < total; i--) {
      ans.push_back(v[endingRow][i]);
      count++;
    }
    endingRow--;
    // printing starting col
    for (int i = endingRow; i >= startingRow && count < total; i--) {
      ans.push_back(v[i][startingCol]);
      count++;
    }
    startingCol++;
  }

  return ans;
}
[
    {
        "$match": {
            "challengeId": ObjectId("6674404413958543b594fe6f")
        }
    },
    {
        "$project": {
            "email": "$registrationDetails.email",
            "points": "$overAllImpact.point",
            "WeightImpact": "$overAllImpact.overAllWeightImpact",
            "eventPoints": "$eventPoint",
            "weeklyWeightLog": {
                "$objectToArray": "$weeklyWeightLog"
            }
        }
    },
    {
        "$unwind": "$weeklyWeightLog"
    },
    {
        "$addFields": {
            "weeklyWeightLog.kDate": {
                "$toDate": "$weeklyWeightLog.k"
            }
        }
    },
    {
        "$sort": {
            "weeklyWeightLog.kDate": -1
        }
    }
]
[
    {
        "$match": {
            "mealPlan": {
                "$elemMatch": {
                    "portionMeasure": "Tea Spoon",
                    "dishVariation": "Paneer Paratha"
                }
            }
        }
    },
    {
       $count:"toatal"
    }
]
vector<int> wavePrint(vector<vector<int>> arr, int r, int c) {
  vector<int> ans;
  for (int col = 0; col < c; col++) {
    if (col & 1) {
      // odd index -> bottom to top
      for (int row = r - 1; row >= 0; row--) {
        cout << arr[row][col] << " ";
        ans.push_back(arr[row][col]);
      }
    }
    // 0 or even index -> top to bottom
    else {
      for (int row = 0; row < r; row++) {
        cout << arr[row][col] << " ";
        ans.push_back(arr[row][col]);
      }
    }
  }

  return ans;
}
To access an HTML element with a given id name, you can use the getElementById() method. Here's an example of how to use this method:

<h1 id="title">Main title</h1>
Example Code
const mainTitleElement = document.getElementById('title');

In programming, prefixing a variable with is or has is a common practice to signify that the variable represents a boolean value.

Here are a few examples:

let isRunning = true;
let hasCompleted = false;

Values from an HTML input field are received as strings in JavaScript. You'll need to convert these strings into numbers before performing any calculations.

To match specific characters in a string, you can use Regular Expressions or "regex" for short.

Regex in JavaScript is indicated by a pattern wrapped in forward slashes. The following example will match the string literal "hello":

const regex = /hello/;

In regex, shorthand character classes allow you to match specific characters without having to write those characters in your pattern. Shorthand character classes are preceded with a backslash (\). The character class \s will match any whitespace character.

JavaScript provides a .replace() method that enables you to replace characters in a string with another string. This method accepts two arguments. The first argument is the character sequence to be replaced, which can be either a string or a regex pattern. The second argument is the string that replaces the matched sequence.

Since strings are immutable, the replace method returns a new string with the replaced characters.

In this example, the replace method is used to replace all instances of the letter l with the number 1 in the string hello.

"hello".replace(/l/g, "1");

Strings have a .match() method, which takes a regex argument. .match() will return an array of match results – containing either the first match, or all matches if the global flag is used.

const str = 'example string';
const regex = /example/;
const result = str.match(regex); // Returns ['example']

The match method returns an array with any matches found in the string.

Here is a complete breakdown of that information:

"1e3" is the matched value against the /\d+e\d+/i regex.
index: 0 is the index of the matched value in the string.
input: '1e3' is the original string that was matched.
groups: undefined are the matched groups, which are not used in this case. You will learn more about groups in a later project.

The match method returns null when no match is found. In this case, the isInvalidInput function should return null when the input is a valid number without any scientific notation.

null in JavaScript is a special primitive that represents the intentional absence of a value. In a boolean context, null is considered falsy which evaluates to false in a conditional statement.

JavaScript has a feature called template literals, which allow you to interpolate variables directly within a string. Template literals are denoted with backticks ``, as opposed to single or double quotes. Variables can be passed in to a template literal by surrounding the variable with ${} – the value of the variable will be inserted into the string.

For example:

const name = "Naomi";
const templateLiteral = `Hello, my name is ${name}~!`;
console.log(templateLiteral);
The console will show the string "Hello, my name is Naomi~!".

The querySelectorAll() method returns a NodeList of all the elements that match the selector. A NodeList is an array-like object, so you can access the elements using bracket notation.

The innerHTML property sets or returns the HTML content inside an element.

Here is a form element with a label and input element nested inside.

<form id="form">
  <label for="first-name">First name</label>
  <input id="first-name" type="text">
</form>
If you want to add another label and input element inside the form, then you can use the innerHTML property as shown below:

const formElement = document.getElementById("form");
const formContent = `
  <label for="last-name">Last name</label>
  <input id="last-name" type="text">
`;
formElement.innerHTML += formContent;

The following example uses the addEventListener method to add a click event to a button. When the button is clicked, the printName function is called.

<button class="btn">Print name</button>
Example Code
const button = document.querySelector('.btn');
function printName() {
  console.log("Jessica");
}
button.addEventListener('click', printName);
The addEventListener method takes two arguments. The first is the event to listen to. (Ex. 'click') The second is the callback function, or the function that runs when the event is triggered.

The insertAdjacentHtml method takes two arguments. The first argument is a string that specifies the position of the inserted element. The second argument is a string containing the HTML to be inserted.

The submit event is triggered when the form is submitted. The default action of the submit event is to reload the page. You need to prevent this default action using the preventDefault() method of your e parameter.

Math.abs() is a built-in JavaScript method that will return the absolute value of a number.

const num = -5;
Math.abs(num); // 5

Finally, you need to make the #output element visible so the user can see your text. Your output variable is an Element, which has a classList property. This property has a .remove() method, which accepts a string representing the class to remove from the element.

Example Code
const paragraphElement = document.getElementById('paragraph');
paragraphElement.classList.remove('hide');

Remember that document.querySelectorAll returns a NodeList, which is array-like but is not an array. However, the Array object has a .from() method that accepts an array-like and returns an array. This is helpful when you want access to more robust array methods, which you will learn about in a future project.

The following example takes a NodeList of li elements and converts it to an array of li elements:

<ul>
  <li>List 1</li>
  <li>List 2</li>
  <li>List 3</li>
</ul>
Example Code
const listItemsArray = Array.from(document.querySelectorAll('li'));

console.log(listItemsArray); //Output: (3) [li, li, li]

The difference between innerText and innerHTML is that innerText will not render HTML elements, but will display the tags and content as raw text.
chkdsk [<Volume>[[<Path>]<FileName>]] [/f] [/v] [/r] [/x] [/i] [/c] [/l[:<Size>]] [/b]  
Now you can start writing your JavaScript. Begin by creating a script element. This element is used to load JavaScript into your HTML file.

<script>
  // JavaScript code goes here
</script>

One of the most powerful tools is your developer console. Depending on your browser, this might be opened by pressing F12 or Ctrl+Shift+I. On Mac, you can press Option + ⌘ + C and select "Console". You can also click the "Console" button above the preview window to see our built-in console.

The developer console will include errors that are produced by your code, but you can also use it to see values of variables in your code, which is helpful for debugging.

JavaScript interacts with the HTML using the Document Object Model, or DOM. The DOM is a tree of objects that represents the HTML. You can access the HTML using the document object, which represents your entire HTML document.

One method for finding specific elements in your HTML is using the querySelector() method. The querySelector() method takes a CSS selector as an argument and returns the first element that matches that selector. For example, to find the <h1> element in your HTML, you would write:

let h1 = document.querySelector("h1");
Note that h1 is a string and matches the CSS selector you would use.

We have run into a slight problem. You are trying to query your page for a button element, but your script tag is in the head of your HTML. This means your code runs before the browser has finished reading the HTML, and your document.querySelector() will not see the button - because the browser hasn't processed it yet.

To fix this, move your script element out of the head element, and place it at the end of your body element (just before the closing <body> tag.)

button1 represents your first button element. These elements have a special property called onclick, which you can use to determine what happens when someone clicks that button.

You can access properties in JavaScript a couple of different ways. The first is with dot notation. Here is an example of using dot notation to set the onclick property of a button to a function reference.

button.onclick = myFunction;
In this example, button is the button element, and myFunction is a reference to a function. When the button is clicked, myFunction will be called.

The innerText property controls the text that appears in an HTML element. For example:

<p id="info">Demo content</p> 
Example Code
const info = document.querySelector("#info"); 
info.innerText = "Hello World"; 
The following example would change the text of the p element from Demo content to Hello World.

Objects are an important data type in JavaScript. The next few steps will be dedicated to learning about them so you will better understand how to apply them in your project.

Objects are non primitive data types that store key-value pairs. Non primitive data types are mutable data types that are not undefined, null, boolean, number, string, or symbol. Mutable means that the data can be changed after it is created.

Here is the basic syntax for an object:

{
  key: value
}

Objects are similar to arrays, except that instead of using indexes to access and modify their data, you access the data in objects through properties.

Properties consist of a key and a value. The key is the name of the property, and the value is the data stored in the property.

Here is an example of an object with a single property:

const obj = {
  name: "Quincy Larson"
};

If the property name (key) of an object has a space in it, you will need to use single or double quotes around the name.

Here is an example of an object with a property name that has a space:

const spaceObj = {
  "Space Name": "Kirk",
};
If you tried to write a key without the quotes, it would throw an error:

const spaceObj = {
  // Throws an error
  Space Name: "Kirk",
}; 

There are two ways to access the properties of an object: dot notation (.) and bracket notation ([]), similar to an array.

Dot notation is what you use when you know the name of the property you're trying to access ahead of time.

object.property;
Here is a sample of using dot notation (.) to read the name property of the developer object:

const developer = {
  name: "Jessica",
}

// Output: Jessica
console.log(developer.name); 

The second way to access the properties of an object is bracket notation ([]). If the property of the object you are trying to access has a space in its name, you will need to use bracket notation.

objectName["property name"];
Here is a sample of using bracket notation to read an object's property:

const spaceObj = {
  "Space Name": "Kirk",
};

spaceObj["Space Name"]; // "Kirk"

By default, the HTML element that shows the monster's stats has been hidden with CSS. When the player clicks the "Fight dragon" button, the monster's stats should be displayed. You can accomplish this by using the style and display properties on the monsterStats element.

The style property is used to access the inline style of an element and the display property is used to set the visibility of an element.

Here is an example of how to update the display for a paragraph element:

const paragraph = document.querySelector('p');
paragraph.style.display = 'block';

The Math object in JavaScript contains static properties and methods for mathematical constants and functions. One of those is Math.random(), which generates a random number from 0 (inclusive) to 1 (exclusive). Another is Math.floor(), which rounds a given number down to the nearest integer.

Using these, you can generate a random number within a range. For example, this generates a random number between 1 and 5: Math.floor(Math.random() * 5) + 1;.

The innerHTML property allows you to access or modify the content inside an HTML element using JavaScript.

Here is an example of updating the content for this paragraph element using the innerHTML property.

<p id="demo">This is a paragraph.</p>
document.querySelector("#demo").innerHTML = "Hello, innerHTML!";

The ternary operator is a conditional operator and can be used as a one-line if-else statement. The syntax is: condition ? expressionIfTrue : expressionIfFalse.

Here is an example of returning a value using an if-else statement and a refactored example using a ternary operator:

// if-else statement
if (score > 0) {
  return score
} else {
  return default_score
}

// ternary operator
return score > 0 ? score : default_score

The logical OR operator will use the first value if it is truthy – that is, anything apart from NaN, null, undefined, 0, -0, 0n, "", and false. Otherwise, it will use the second value.

For example: num < 10 || num > 20.

The .includes() method determines if an array contains an element and will return either true or false.

Here is an example of the .includes() syntax:

Example Code
const numbersArray = [1, 2, 3, 4, 5]
const number = 3

if (numbersArray.includes(number)) {
  console.log("The number is in the array.")
}
[HttpGet]
[Route("getUserById/{id}")]
public async Task<IActionResult> GetUserById(int id)
{
    try
    {
        IQueryable<User> query =  _appDbContext.Users.Include(u => u.User_Status).Include(u => u.User_Type);

        var results = await query.ToArrayAsync();

        dynamic users = results.Select(u => new
        {
            u.Id,
            u.Name,
            u.Surname,
            u.Email,
            u.Physical_Address,
            u.PhoneNumber,
            u.Date_of_Birth,
            UserStatus = u.User_Status.User_Status_Description,
            UserType = u.User_Type.User_Type_Name,
            u.Photo,
            u.ID_Number
        });

        return Ok(users);
    }
    catch (Exception ex)
    {
        // Log the exception for debugging
        Console.WriteLine(ex.Message);
        return BadRequest("An error occurred while fetching user details.");
    }
}
[HttpGet]
[Route("getUserById/{id}")]
public async Task<IActionResult> GetUserById(int id)
{
    try
    {
        var user = await _userManager.FindByIdAsync(id.ToString());

        if (user == null)
        {
            return NotFound("User not found.");
        }

        var userViewModel = new UserViewModel
        {
            Name = user.Name,
            Surname = user.Surname,
            Email = user.Email,
            Physical_Address = user.Physical_Address,
            PhoneNumber = user.PhoneNumber,
            Date_of_Birth = user.Date_of_Birth,
            User_Status_ID = user.User_Status_ID,
            User_Type_ID = user.User_Type_ID,
            Id_Number = user.ID_Number
        };

        // Fetch the base64 string photo from user.Photo
        string base64Photo = user.Photo;

        // Convert base64 string to byte array
        byte[] photoBytes = Convert.FromBase64String(base64Photo);

        // Convert byte array to IFormFile-like object
        var memoryStream = new MemoryStream(photoBytes);

        userViewModel.Photo = new FormFile(memoryStream, 0, photoBytes.Length, "Photo", "photo.jpg")
        {
            Headers = new HeaderDictionary(),
            ContentType = "image/jpeg" // Set the content type as appropriate
        };

        return Ok(userViewModel);
    }
    catch (Exception ex)
    {
        // Log the exception for debugging
        Console.WriteLine(ex.Message);
        return BadRequest("An error occurred while fetching user details.");
    }
}
NW_COCTmp.COCRecipientName                 = NW_COCDP::GetSteps(NW_CertificationOfCompletionHeader.CertificationOfCompletionID,PurchParameters::find().COCRecipient);

 

public static str GetSteps(str 50 _CertificationOfCompletionID , str 100 _Name)
    {
        NW_CertificationOfCompletionHeader  NW_CertificationOfCompletionHeader;

 

        WorkflowTrackingStatusTable workflowTrackingStatusTable, _workflowTrackingStatusTable;
        WorkflowTrackingTable WorkflowTrackingTable, _WorkflowTrackingTable;
        str UserName;

 

        select NW_CertificationOfCompletionHeader where NW_CertificationOfCompletionHeader.CertificationOfCompletionID == _CertificationOfCompletionID;

 

        SELECT * FROM workflowTrackingStatusTable order by workflowtrackingstatustable.CreatedDateTime desc
            where workflowTrackingStatusTable.CONTEXTRECID == NW_CertificationOfCompletionHeader.recid
&& workflowTrackingStatusTable.CONTEXTTABLEID == tableNum(NW_CertificationOfCompletionHeader)
           join workflowTrackingTable
           where workflowTrackingTable.WorkflowTrackingStatusTable == workflowTrackingStatusTable.RecId
&& WorkflowTrackingTable.TRACKINGTYPE == WorkflowTrackingType::Creation
&& WorkflowTrackingTable.TRACKINGCONTEXT == WorkflowTrackingContext::Step
&& WorkflowTrackingTable.Name == _Name;

 

 

        SELECT * FROM _workflowTrackingStatusTable where _workflowTrackingStatusTable.CONTEXTRECID == NW_CertificationOfCompletionHeader.recid
&& _workflowTrackingStatusTable.CONTEXTTABLEID == tableNum(NW_CertificationOfCompletionHeader)
           join _WorkflowTrackingTable order by _WorkflowTrackingTable.CreatedDateTime
           where _WorkflowTrackingTable.WorkflowTrackingStatusTable == _workflowTrackingStatusTable.RecId
&& _WorkflowTrackingTable.CreatedDateTime >= WorkflowTrackingTable.CreatedDateTime
&& _WorkflowTrackingTable.TRACKINGTYPE == WorkflowTrackingType::Approval
&& _WorkflowTrackingTable.TRACKINGCONTEXT == WorkflowTrackingContext::WorkItem;

 

 

        if(WorkflowTrackingTable)
        {
            UserName = _WorkflowTrackingTable.User;

 

        }

 

        return HcmWorker::find(HcmWorker::userId2Worker(UserName)).name() ;
        //NW_CertificationOfCompletionHeader  _NW_CertificationOfCompletionHeader;

 

 

        //select _NW_CertificationOfCompletionHeader where _NW_CertificationOfCompletionHeader.CertificationOfCompletionID == _CertificationOfCompletionID;

 

        //WorkflowTrackingStatusTable workflowTrackingStatusTable;

 

        //WorkflowTrackingTable WorkflowTrackingTable;

 

        //WorkflowApprovalName approvername;
        //utcdatetime approverDate;
        //WorkflowWorkItemTable WorkflowWorkItemTable;
        //WorkflowElementTable  WorkflowElementTable;

 

        //select * from WorkflowWorkItemTable
        //where WorkflowWorkItemTable.Status ==WorkflowWorkItemStatus::Completed
        //&& WorkflowWorkItemTable.RefRecId == _NW_CertificationOfCompletionHeader.recid
        //&& WorkflowWorkItemTable.RefTableId == _NW_CertificationOfCompletionHeader.TableId
        //    join WorkflowElementTable
        //    where WorkflowElementTable.ElementId == WorkflowWorkItemTable.ElementId
        //    && WorkflowElementTable.Name == _Name;

 

        //join workflowTrackingStatusTable  //order by workflowtrackingstatustable.ConfigurationVersionId desc
        // where WorkflowWorkItemTable.CorrelationId == workflowTrackingStatusTable.CorrelationId
        //  //  && (workflowtrackingstatustable.TrackingStatus == WorkflowTrackingStatus::Pending
        //  //  || workflowtrackingstatustable.TrackingStatus == WorkflowTrackingStatus::Completed)
        //    && workflowtrackingstatustable.ContextRecId == _NW_CertificationOfCompletionHeader.recid
        //&& workflowtrackingstatustable.ContextTableId == _NW_CertificationOfCompletionHeader.TableId
        //join WorkflowTrackingTable //order by workflowtrackingtable.CreatedDateTime desc
        //    where workflowtrackingtable.TrackingContext == workflowtrackingcontext::Step
        //    && workflowtrackingtable.TrackingType == workflowtrackingtype::Creation
        //    && workflowtrackingtable.WorkflowTrackingStatusTable == workflowtrackingstatustable .recid
        //    && workflowtrackingtable.Name == _Name;

 

    
        //if(WorkflowWorkItemTable)
        //{

 

        //    //  approverDate = DateTimeUtil::date(workflowtrackingtable.CreatedDateTime);
        //    approvername = WorkflowWorkItemTable.UserId;

 

        //}

 

        //return approvername;

 

    }
#include <iostream>
#include <string>
using namespace std;

string addInplaceOfSpaces (string &s) {
  string temp = "";
  for (int i = 0; i < s.length(); i ++) {
    if (s[i] == ' ') {
      temp.push_back('@');
      temp.push_back('2');
      temp.push_back('3');
    }
    else {
      temp.push_back(s[i]);
    }
  }
  return temp;
}

int main() {
  string s ="my name is vishnu deb jha" ;
  string v = addInplaceOfSpaces(s);
  cout << v << endl;
  return 0;
}
// output is my@23name@23is@23vishnu@23deb@23jha
add_filter( 'sp_wpspro_product_image', function ( $product_img_html ) {
    return apply_filters( 'woocommerce_single_product_image_thumbnail_html', $product_img_html );
}, 99, 1 );
char getMaxOccCharacter(string s) {
  int arr[26] = {0};
  for (int i = 0; i < s.length(); i++) {
    char ch = s[i];
    int number = 0;
    number = ch - 'a';
    arr[number]++;
  }
  int maxi = -1, ans = 0;
  for (int i = 0; i < 26; i++) {
    if (arr[i] > maxi) {
      maxi = arr[i];
      ans = i;
    }
  }
  return 'a' + ans;
}
#include <stdio.h>

int main(void) {
	// your code goes here
	int t;
	scanf("%d",&t);
	while(t--)
	{
	    int x;
	    scanf("%d",&x);
	    if(x+3<=10)
	    {
	        printf(" yes \n");
	    }
	    else
	    {
	        printf(" no \n");
	    }
	}
	return 0;
}
import { rdsConnection } from "@/lib/aws";
import type { Country, LineUp, Port, Position, Vessel } from "@/types";
import { emptyVessel } from "@/types";
import type { MysqlError } from "mysql";
import mysql from "mysql";
import { VesselDetails } from "@/types/vessel";

export async function getVesselFromIMO(imo: string) {
  return await new Promise<Vessel[]>((resolve, reject) => {
    rdsConnection.query(
      `SELECT vessel_id, dwt, imo, flag, mmsi, vessel_name, cargo_type, cargo_sub_type, year_of_build, manager FROM spotship_vessel WHERE imo LIKE ? LIMIT 20`,
      [`${imo}%`],
      (error: unknown, elements: Vessel[]) => {
        if (error) {
          return reject(error);
        }
        return resolve(elements);
      },
    );
  });
}

export async function getVesselFromMMSI(mmsi: string) {
  return await new Promise<Vessel[]>((resolve, reject) => {
    rdsConnection.query(
      `SELECT vessel_id, dwt, imo, flag, mmsi, vessel_name, cargo_type, cargo_sub_type, year_of_build, manager FROM spotship_vessel WHERE mmsi LIKE ? LIMIT 20`,
      [`${mmsi}%`],
      (error: unknown, elements: Vessel[]) => {
        if (error) {
          return reject(error);
        }
        return resolve(elements);
      },
    );
  });
}

export async function getVesselFromName(name: string) {
  return await new Promise<Vessel[]>((resolve, reject) => {
    rdsConnection.query(
      `SELECT vessel_id, dwt, imo, flag, mmsi, vessel_name, cargo_type, cargo_sub_type, year_of_build, manager FROM spotship_vessel WHERE vessel_name LIKE ? ORDER BY vessel_name LIMIT 250`,
      [`%${name.toUpperCase()}%`],
      (error: unknown, elements: Vessel[]) => {
        if (error) {
          return reject(error);
        }
        return resolve(elements);
      },
    );
  });
}

export async function getVesselFromId(vessel_id: string) {
  return await new Promise<Vessel[]>((resolve, reject) => {
    rdsConnection.query(
      `SELECT vessel_id, dwt, imo, flag, mmsi, vessel_name, cargo_type, cargo_sub_type, year_of_build FROM spotship_vessel WHERE vessel_id = ?`,
      [vessel_id],
      (error: unknown, elements: Vessel[]) => {
        if (error) {
          return reject(error);
        }
        return resolve(elements);
      },
    );
  });
}

export async function getPortFromName(name: string) {
  return await new Promise<Port[]>((resolve, reject) => {
    rdsConnection.query(
      `SELECT port.id, port.name, port.locode, country.name AS country, country.code as flag, port.longitude, port.latitude, port.number_of_berths, port.port_region, port.super_region, port.type FROM spotship_port AS port INNER JOIN spotship_country AS country ON port.country_id = country.id WHERE port.name LIKE ? ORDER BY port.name LIMIT 1000`,
      [`%${name.toUpperCase()}%`],
      (error: unknown, elements: Port[]) => {
        if (error) {
          return reject(error);
        }
        return resolve(elements);
      },
    );
  });
}

export async function getPortFromId(port_id: number) {
  return await new Promise<Port[]>((resolve, reject) => {
    rdsConnection.query(
      `SELECT port.name, port.locode, country.name AS country, country.code as flag, port.longitude, port.latitude, port.number_of_berths, port.port_region, port.super_region, port.type FROM spotship_port AS port INNER JOIN spotship_country AS country ON port.country_id = country.id WHERE port.id = ?`,
      [port_id],
      (error: unknown, elements: Port[]) => {
        if (error) {
          return reject(error);
        }
        return resolve(elements);
      },
    );
  });
}

export async function getCountryFromName(name: string) {
  return await new Promise<Country[]>((resolve, reject) => {
    rdsConnection.query(
      `SELECT id, name, code FROM spotship_country WHERE name LIKE ? ORDER BY name LIMIT 1000`,
      [`${name}%`],
      (error: unknown, elements: Country[]) => {
        if (error) {
          return reject(error);
        }
        return resolve(elements);
      },
    );
  });
}

export async function getRegionFromName(name: string) {
  return await new Promise<Array<{ name: string }>>((resolve, reject) => {
    rdsConnection.query(
      `SELECT DISTINCT port_region AS name FROM spotship_port WHERE port_region LIKE ? ORDER BY port_region LIMIT 1000`,
      [`%${name}%`],
      (error: unknown, elements: Array<{ name: string }>) => {
        if (error) {
          return reject(error);
        }
        return resolve(elements);
      },
    );
  });
}

export async function getSuperRegionFromName(name: string) {
  return await new Promise<Array<{ name: string }>>((resolve, reject) => {
    rdsConnection.query(
      `SELECT DISTINCT super_region AS name FROM spotship_port WHERE super_region LIKE ? ORDER BY super_region LIMIT 1000`,
      [`%${name}%`],
      (error: unknown, elements: Array<{ name: string }>) => {
        if (error) {
          return reject(error);
        }
        return resolve(elements);
      },
    );
  });
}

function translateDirtyClean(dirtyClean: "CPP" | "DPP" | "N/A" | null) {
  switch (dirtyClean) {
    case "CPP":
      return "WET - CLEAN";
    case "DPP":
      return "WET - DIRTY";
    case "N/A":
      return "WET";
    default:
      return null;
  }
}

function dirtyOrClean(dirtyClean: "CPP" | "DPP" | "N/A" | null) {
  switch (dirtyClean) {
    case "CPP":
      return "CLEAN";
    case "DPP":
      return "DIRTY";
    case "N/A":
      return "";
    default:
      return "";
  }
}

async function updateVesselDirtyClean(
  vessel_id: string,
  status: "CPP" | "DPP" | "N/A" | null,
) {
  return await new Promise((resolve, reject) => {
    rdsConnection.query(
      `UPDATE spotship_vessel SET dirty_clean = ? WHERE vessel_id = ?`,
      [dirtyOrClean(status), vessel_id],
      (error: unknown, elements: unknown) => {
        if (error) {
          console.error(
            "Error origin: Updating dirty/clean in Spotship Database | ",
            error,
          );
          return reject(error);
        }
        return resolve(elements);
      },
    );
  });
}

export function insertPositionValue(
  filename: string,
  broker: number,
  source: string,
  position: Position,
) {
  return `(
    ${mysql.escape(broker)},
    'DATA TEAM',
    ${mysql.escape(
      source.indexOf("<") === -1 || source.indexOf(">") === -1
        ? source
        : source.substring(source.indexOf("<") + 1, source.lastIndexOf(">")),
    )},
    ${mysql.escape(filename)},
    ${mysql.escape(position.vessel.vessel_id)},
    ${mysql.escape(position.open?.startDate ?? "")},
    ${mysql.escape(position.open?.endDate ?? "")},
    ${mysql.escape(position.port.id)},
    ${mysql.escape(position.status)},
    ${mysql.escape(position.cargo)},
    ${mysql.escape(position.notes)},
    ${mysql.escape(translateDirtyClean(position.dirtyClean))},
    'AVAILABLE',
    ${mysql.escape(new Date().toISOString())}
  ),`;
}

export async function bulkInsertPosition(
  brokers: Array<number>,
  positions: Array<Position>,
  filename: string,
  source: string,
) {
  if (positions.length == 0 || brokers.length == 0) {
    console.error(
      "Error origin: Inserting Position into Spotship Database | Broker list or positions list was empty",
    );
    return;
  }

  let query = `INSERT INTO spotship_vesselavailability
  (broker_id, source, origin, origin_id, vessel_id, open_date, close_date, open_location, status, last_3_cargoes, details, wet_dry, current_status, created_at)
  VALUES `;

  brokers.forEach((id) => {
    if (id > 0) {
      positions.forEach((position: Position) => {
        query += insertPositionValue(filename, id, source, position);
      });
    }
  });

  // Remove last comma
  query = query.replace(/,$/, "");

  return await new Promise((resolve, reject) => {
    rdsConnection.query(
      query,
      async (error: MysqlError | null, elements: unknown) => {
        if (error) {
          if (error.code === "ER_LOCK_DEADLOCK") {
            console.warn(
              "Warning origin: Inserting Position into Spotship Database - Retrying due to ER_LOCK_DEADLOCK | ",
              error,
            );
            // N.B. Recursion used for infinite retries.
            return bulkInsertPosition(brokers, positions, filename, source);
          }
          console.error(
            "Error origin: Inserting Position into Spotship Database | ",
            error,
          );
          return reject(error);
        }

        await Promise.all(
          positions.map(async (position) => {
            try {
              await updateVesselDirtyClean(
                position.vessel.vessel_id,
                position.dirtyClean,
              );
            } catch (e) {
              console.error(
                "Error origin: Updating vessel dirty/clean in Spotship Database | ",
                e,
              );
            }
          }),
        );
        return resolve(elements);
      },
    );
  });
}

export function insertLineupValue(
  filename: string,
  broker: number,
  source: string,
  lineup: LineUp,
) {
  let open = lineup.eta ?? new Date();
  if (lineup.etb !== null && open < lineup.etb) {
    open = lineup.etb;
  }
  if (lineup.etd !== null && open < lineup.etd) {
    open = lineup.etd;
  }

  return `(
    ${mysql.escape(broker)},
    'DATA TEAM',
    ${mysql.escape(
      source.indexOf("<") === -1 || source.indexOf(">") === -1
        ? source
        : source.substring(source.indexOf("<") + 1, source.lastIndexOf(">")),
    )},
    ${mysql.escape(filename)},
    ${mysql.escape(lineup.vessel.vessel_id)},
    ${mysql.escape(lineup.port.id)},
    ${mysql.escape(
      `${
        lineup.toleranceType === "Min/Max"
          ? `${lineup.quantity} - ${lineup.tolerance}`
          : `${lineup.quantity}`
      }${lineup.unit}${
        lineup.toleranceType === "%" || lineup.toleranceType === "Unit"
          ? ` ± ${lineup.tolerance}${lineup.toleranceType === "%" ? "%" : ""}`
          : ""
      } ${lineup.cargo}`,
    )},
    'AVAILABLE',
    ${mysql.escape(new Date().toISOString())},
    ${mysql.escape(lineup.eta?.toISOString())},
    ${mysql.escape(lineup.etb?.toISOString())},
    ${mysql.escape(lineup.etd?.toISOString())},
    ${mysql.escape(lineup.loading !== null ? (lineup.loading ? 1 : 0) : null)},
    ${mysql.escape(`${lineup.terminal !== null && lineup.terminal !== "" ? `TERMINAL: ${lineup.terminal}` : ""} ${lineup.pier !== null && lineup.pier !== "" ? `PIER: ${lineup.pier}` : ""} ${lineup.destination !== null && lineup.destination.name !== "" ? `DESTINATION: ${lineup.destination.name} ` : ""}`)},
    ${mysql.escape(open.toISOString())}
  ),`;
}

export async function bulkInsertLineup(
  brokers: Array<number>,
  lineups: Array<LineUp>,
  filename: string,
  source: string,
) {
  if (lineups.length == 0 || brokers.length == 0) {
    console.error(
      "Error origin: Inserting Line ups into Spotship Database | Broker list or line up list was empty",
    );
    return;
  }

  let query = `INSERT INTO spotship_vesselavailability
  (broker_id, source, origin, origin_id, vessel_id, open_location, last_3_cargoes, current_status, created_at, et_a, etb, etd, load_discharge, details, open_date)
  VALUES `;

  brokers.forEach((id) => {
    if (id > 0) {
      lineups.forEach((lineup: LineUp) => {
        query += insertLineupValue(filename, id, source, lineup);
      });
    }
  });

  // Remove last comma
  query = query.replace(/,$/, "");

  return await new Promise((resolve, reject) => {
    rdsConnection.query(
      query,
      async (error: MysqlError | null, elements: unknown) => {
        if (error) {
          if (error.code === "ER_LOCK_DEADLOCK") {
            console.warn(
              "Warning origin: Inserting Lineup into Spotship Database - Retrying due to ER_LOCK_DEADLOCK | ",
              error,
            );
            // N.B. Recursion used for infinite retries.
            return bulkInsertLineup(brokers, lineups, filename, source);
          }
          console.error(
            "Error origin: Inserting Line up into Spotship Database | ",
            error,
          );
          return reject(error);
        }
        return resolve(elements);
      },
    );
  });
}

// QUERY FOR VESSEL INFO - Raf
export async function queryVesselFromIMO(imo: string) {
  return await new Promise<Vessel[]>((resolve, reject) => {
    rdsConnection.query(
      `SELECT vessel_id, dwt, imo, flag, mmsi, vessel_name, cargo_type, cargo_sub_type, year_of_build, maximum_draft, manager FROM spotship_vessel WHERE imo LIKE ? LIMIT 20`,
      [`${imo}%`],
      (error: unknown, elements: Vessel[]) => {
        if (error) {
          return reject(error);
        }
        return resolve(elements);
      },
    );
  });
}

// QUERY FOR VESSEL DETAILS INFO - Raf
export async function queryVesselDetails(vessel_id: string) {
  return await new Promise<VesselDetails[]>((resolve, reject) => {
    rdsConnection.query(
      `SELECT vessel_id, geared, gear_details FROM spotship_vesseldetails WHERE vessel_id = ?`,
      [vessel_id],
      (error: unknown, elements: VesselDetails[]) => {
        if (error) {
          return reject(error);
        }
        return resolve(elements);
      },
    );
  });
}

// ADD VESSEL TO DB - Raf
export async function addVessel(vessel: Vessel) {
  return await new Promise<void>((resolve, reject) => {
    rdsConnection.query(
      `INSERT INTO spotship_vessel (vessel_id, dwt, imo, flag, mmsi, vessel_name, cargo_type, cargo_sub_type, year_of_build, maximum_draft, manager) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`,
      [
        vessel.vessel_id,
        vessel.dwt,
        vessel.imo,
        vessel.flag,
        vessel.mmsi,
        vessel.vessel_name,
        vessel.cargo_type,
        vessel.cargo_sub_type,
        vessel.year_of_build,
        vessel.maximum_draft,
        vessel.manager,
      ],
      (error: unknown) => {
        if (error) {
          return reject(error);
        }
        return resolve();
      },
    );
  });
}

// ADD VESSEL DETAILS TO DB - Raf
export async function addVesselDetails(details: VesselDetails) {
  return await new Promise<void>((resolve, reject) => {
    rdsConnection.query(
      `INSERT INTO spotship_vesseldetails (vessel_id, geared, gear_details) VALUES (?, ?, ?)`,
      [details.vessel_id, details.geared, details.gear_details],
      (error: unknown) => {
        if (error) {
          return reject(error);
        }
        return resolve();
      },
    );
  });
}

// UPDATE EXISTING VESSEL - Raf
export async function modernizeVessel(vessel: Vessel) {
  return await new Promise<void>((resolve, reject) => {
    rdsConnection.query(
      `UPDATE spotship_vessel SET dwt = ?, imo = ?, flag = ?, mmsi = ?, vessel_name = ?, cargo_type = ?, cargo_sub_type = ?, year_of_build = ?, beam = ?, overall_length = ?, maximum_draft = ?, manager = ? WHERE vessel_id = ?`,
      [
        vessel.dwt,
        vessel.imo,
        vessel.flag,
        vessel.mmsi,
        vessel.vessel_name,
        vessel.cargo_type,
        vessel.cargo_sub_type,
        vessel.year_of_build,
        vessel.beam,
        vessel.overall_length
        vessel.maximum_draft,
        vessel.manager,
        vessel.vessel_id,
      ],
      (error: unknown) => {
        if (error) {
          return reject(error);
        }
        return resolve();
      },
    );
  });
}

// UPDATE EXISTING VESSEL DETAILS - Raf
export async function modernizeVesselDetails(details: VesselDetails) {
  return await new Promise<void>((resolve, reject) => {
    rdsConnection.query(
      `UPDATE spotship_vesseldetails SET geared = ?, gear_details = ? WHERE vessel_id = ?`,
      [details.geared, details.gear_details, details.vessel_id],
      (error: unknown) => {
        if (error) {
          return reject(error); 
        }
        return resolve();
      },
    );
  });
}

export async function inssertVesselDetail(port: Port) {
  return await new Promise((resolve, reject) => {
    rdsConnection.query(
      `INSERT INTO spotship_vesseldetails (geared, gear_details) VALUES (?, ?)`,
      [emptyVessel.vessel_id, emptyVessel.dwt],
      (error: unknown, elements: unknown) => {
        if (error) {
          console.error(
            "Error origin: Inserting a vessel into Spotship Database | ",
            error,
          );
          return reject(error);
        }
        return resolve(elements);
      },
    );
  });
}

export async function insertPort(port: Port) {
  return await new Promise((resolve, reject) => {
    rdsConnection.query(
      `INSERT INTO spotship_port (name, country_id, latitude, longitude, locode, port_region, super_region, type) VALUES (?, ?, ?, ?, ?, ?, ?, ?)`,
      [
        port.name,
        port.country,
        port.latitude,
        port.longitude,
        port.locode,
        port.port_region,
        port.super_region,
        port.type,
      ],
      (error: unknown, elements: unknown) => {
        if (error) {
          console.error(
            "Error origin: Inserting a port into Spotship Database | ",
            error,
          );
          return reject(error);
        }
        return resolve(elements);
      },
    );
  });
}

export async function editVessel(vessel_id: Vessel, name: string) {
  return await new Promise((resolve, reject) => {
    rdsConnection.query(
      `UPDATE spotship_vessel SET vessel_name = ? WHERE vessel_id = ?`,
      [name, vessel_id],
      (error: unknown, elements: unknown) => {
        if (error) {
          console.error(
            "Error origin: Updating a vessel in Spotship Database | ",
            error,
          );
          return reject(error);
        }
        return resolve(elements);
      },
    );
  });
}
<div
    x-data=""
    x-init="
         Inputmask('currency', {
            numericInput: true,
            rightAlign: false,
            autoUnmask: true,
            onBeforeMask: function (value, opts) {
                if(null === value){ // fix charAt on null errors
                    value= '0.00'
                }
                return value;
            }
        }).mask($refs.input);
    "
>

    <input
        x-ref="input"
        x-on:change="$dispatch('input', $refs.input.value)"
        {{ $attributes->merge(['class' => 'text-center flex-1 block w-full py-2 px-4 border border-gr-brown-500 outline-none transition duration-150 ease-in-out sm:leading-5 text-center']) }}
        onfocus="this.select();"
    />
</div>
In programming, you will often need to work with lots of data. There are many data structures that can help you organize and manage your data. One of the most basic data structures is an array.

An array is a non-primitive data type that can hold a series of values. Non-primitive data types differ from primitive data types in that they can hold more complex data. Primitive data types like strings and numbers can only hold one value at a time.

Arrays are denoted using square brackets ([]). Here is an example of a variable with the value of an empty array:

let array = [];

When an array holds values, or elements, those values are separated by commas. Here is an array that holds two strings:

Example Code
let array = ["first", "second"];

You can access the values inside an array using the index of the value. An index is a number representing the position of the value in the array, starting from 0 for the first value.

You can access the value using bracket notation, such as array[0].

Arrays are special in that they are considered mutable. This means you can change the value at an index directly.

For example, this code would assign the number 25 to the second element in the array:

let array = [1, 2, 3];
array[1] = 25;
console.log(array); // prints [1, 25, 3]

You can make use of the .length property of an array - this returns the number of elements in the array. To get the last element of any array, you can use the following syntax:

array[array.length - 1]

array.length returns the number of elements in the array. By subtracting 1, you get the index of the last element in the array. 

A method in JavaScript is a function that's associated with certain values or objects. An example you've already encountered is the .log() method, which is part of the console object.

Arrays have their own methods, and the first you will explore is the .push() method. This allows you to "push" a value to the end of an array. Here is an example to add the number 12 to the end of an array:

array.push(12);

Another method essential for this project is the .pop() method. It removes the last element from an array and returns that element.

When a method returns a value, you can think of it as giving the value back to you, making it available for use in other parts of your code.

.push() returns the new length of the array, after adding the value you give it.

When you have to perform a task repeatedly until a condition is met, you will use a loop. There are many ways to write a loop.

You are going to start with a basic for loop. for loops use the following syntax:

for (iterator; condition; iteration) {
  logic;
}

The iterator is a variable you can declare specifically in your for loop to control how the loop iterates or goes through your logic.

It is a common convention to use i as your iterator variable in a loop. A for loop allows you to declare this in the parentheses (). For example, here is a for loop that declares an index variable and assigns it the value 100.

for (let index = 100; "second"; "third") {

}

The condition of a for loop tells the loop how many times it should iterate. When the condition becomes false, the loop will stop.

In JavaScript, a Boolean value can be either true or false. These are not strings - you will learn more about the difference later on.

Your iteration statement will tell your loop what to do with the iterator after each run.

When you reassign a variable, you can use the variable to reference the previous value before the reassignment. This allows you to do things like add three to an existing number. For example, bees = bees + 3; would increase the value of bees by three.

A for...of loop, which iterates over each item in an iterable object and temporarily assigns it to a variable.

The syntax for a for...of loop looks like:

for (const value of iterable) {

}

You will need to add a new line to each row. However, pressing the return key to insert a line break between quotes in JavaScript will result in a parsing error. Instead, you need to use the special escape sequence \n, which is interpreted as a new line when the string is logged. For example:

lineOne = lineOne + "\n" + lineTwo;

To achieve this, you will use the .repeat() method available to strings. This method accepts a number as an argument, specifying the number of times to repeat the target string. For example, using .repeat() to generate the string "Code! Code! Code!":

const activity = "Code! ";
activity.repeat(3);

A function is a block of code that can be reused throughout your application. Functions are declared with the following syntax:

function name(parameter) {

}

The function keyword tells JavaScript that the name variable is going to be a function. parameter is a variable that represents a value that is passed into the function when it is used. A function may have as many, or as few, parameters as you'd like.

In order to use a function, you need to call it. A function call tells your application to run the code from the function wherever you choose to call it. The syntax for a function call is the function name followed by parentheses. For example, this code defines and calls a test function.

function test() {

}
test();

All functions in JavaScript return a value, meaning they provide the defined result of calling them for you to use elsewhere.

By default, functions return undefined as their value.

In order to return something else, you need to use the return keyword. Here is an example of a function that returns the string "Functions are cool!":

Example Code
function demo() {
  return "Functions are cool!";
}

Hard-coding a value inside a function might not make it as reusable as you'd like.

Instead, you can define parameters for the function. Parameters are special variables that are given a value when you call the function, and can be used in your function to dynamically change the result of the function's code.

To add a parameter to your function, you need to add a variable name inside the parentheses. For example, this demo function has a name parameter:

function demo(name) {

}

A function does not have to return a hard-coded value. It can return the value stored in a variable. Parameters are special variables for a function, so they can also be returned.

When you pass a value to a function call, that value is referred to as an argument. Here is an example of calling a demo function and passing "Naomi" as the argument for the name parameter.

function demo(name) {
  return name;
}
demo("Naomi");

Variables in JavaScript are available in a specific scope. In other words, where a variable is declared determines where in your code it can be used.

The first scope is the global scope. Variables that are declared outside of any "block" like a function or for loop are in the global scope.

When a variable is in the global scope, a function can access it in its definition. Here is an example of a function using a global title variable:

const title = "Professor ";
function demo(name) {
  return title + name;
}
demo("Naomi")
This example would return "Professor Naomi".

Variables can also be declared inside a function. These variables are considered to be in the local scope, or block scope. A variable declared inside a function can only be used inside that function. If you try to access it outside of the function, you get a reference error.

Values returned out of a function are used by calling the function. You can use the function call directly as the value it returns, or capture the returned value in a variable. This way, you can use the value assigned to a locally scoped variable, outside the function it was created in.

function getName() {
  const name = "Camper cat";
  return name;
}

console.log(getName()); // "Camper cat"

const capturedReturnValue = getName();
console.log(capturedReturnValue); // "Camper cat"

console.log(name); // reference error

The values you provide to a function call are referred to as arguments, and you pass arguments to a function call. Here's a function call with "Hello" passed as an argument:

test("Hello");

You can pass full expressions as an argument. The function will receive the result of evaluating that expression. For example, these two function calls would yield the same result:

test(2 * 3 + 1);
test(7);

An if statement allows you to run a block of code only when a condition is met. They use the following syntax:

if (condition) {
  logic
}

A truthy value is a value that is considered true when evaluated as a boolean. Most of the values you encounter in JavaScript will be truthy.

A falsy value is the opposite - a value considered false when evaluated as a boolean. JavaScript has a defined list of falsy values. Some of them include false, 0, "", null, undefined, and NaN.

In addition to if statements, JavaScript also has else if statements. else if statements allow you to check multiple conditions in a single block of code.

Here is the syntax for an else if statement:

if (condition1) {
  // code to run if condition1 is true
} else if (condition2) {
  // code to run if condition2 is true
} else if (condition3) {
  // code to run if condition3 is true
} 
If the first condition is false, JavaScript will check the next condition in the chain. If the second condition is false, JavaScript will check the third condition, and so on.

Sometimes you will want to run different code when all of the if...else if conditions are false. You can do this by adding an else block.

An else block will only evaluate if the conditions in the if and else if blocks are not met.

Here the else block is added to the else if block.

if (condition) {
  // this code will run if condition is true
} else if (condition2) {
  // this code will run if the first condition is false
} else {
  // this code will run 
  // if the first and second conditions are false
}

A while loop will run over and over again until the condition specified is no longer true. It has the following syntax:

while (condition) {
  logic;
}

The equality operator can lead to some strange behavior in JavaScript. For example, "0" == 0 is true, even though one is a string and one is a number.

The strict equality operator === is used to check if two values are equal and share the same type. As a general rule, this is the equality operator you should always use. With the strict equality operator, "0" === 0 becomes false, because while they might have the same value of zero, they are not of the same type.

The strict inequality operator !== allows you to check if two values are not equal, or do not have the same type. The syntax is similar to the equality operator: value !== 4.

The .unshift() method of an array allows you to add a value to the beginning of the array, unlike .push() which adds the value at the end of the array. Here is an example:

const numbers = [1, 2, 3];
numbers.unshift(5);

Arrays also have a .shift() method. This will remove the first element of the array, unlike .pop() which removes the last element. Here is an example of the .shift() method:

const numbers = [1, 2, 3];
numbers.shift();
star

Sat Jun 29 2024 12:45:34 GMT+0000 (Coordinated Universal Time)

@insplay

star

Sat Jun 29 2024 12:44:08 GMT+0000 (Coordinated Universal Time)

@insplay

star

Sat Jun 29 2024 12:40:12 GMT+0000 (Coordinated Universal Time)

@insplay

star

Sat Jun 29 2024 08:52:48 GMT+0000 (Coordinated Universal Time) https://cli.vgv.dev/

@sami

star

Sat Jun 29 2024 08:52:33 GMT+0000 (Coordinated Universal Time) https://cli.vgv.dev/

@sami

star

Sat Jun 29 2024 08:52:23 GMT+0000 (Coordinated Universal Time) https://cli.vgv.dev/

@sami

star

Sat Jun 29 2024 08:51:44 GMT+0000 (Coordinated Universal Time) https://pub.dev/packages/very_good_cli

@sami

star

Sat Jun 29 2024 08:51:03 GMT+0000 (Coordinated Universal Time) https://cli.vgv.dev/

@sami

star

Sat Jun 29 2024 07:09:32 GMT+0000 (Coordinated Universal Time)

@Ranjith

star

Sat Jun 29 2024 07:03:22 GMT+0000 (Coordinated Universal Time)

@NoFox420 #javascript

star

Sat Jun 29 2024 07:01:01 GMT+0000 (Coordinated Universal Time)

@mrakchaudhary

star

Sat Jun 29 2024 05:29:09 GMT+0000 (Coordinated Universal Time) https://myassignmenthelp.co.uk/onlineexam

@alicahelen #onlineexam #education #programming #pythonexamhelp

star

Sat Jun 29 2024 04:52:36 GMT+0000 (Coordinated Universal Time) https://www.geeksforgeeks.org/convert-number-to-words/

@Sifat_H

star

Sat Jun 29 2024 04:51:16 GMT+0000 (Coordinated Universal Time) https://www.geeksforgeeks.org/php-program-to-convert-a-given-number-to-words/

@Sifat_H

star

Sat Jun 29 2024 02:48:20 GMT+0000 (Coordinated Universal Time)

@NoFox420 #javascript

star

Sat Jun 29 2024 02:06:13 GMT+0000 (Coordinated Universal Time)

@quanganh141220 #php #single #product

star

Fri Jun 28 2024 23:21:50 GMT+0000 (Coordinated Universal Time) https://developers.google.com/admob/android/privacy

@calazar23 #gradle

star

Fri Jun 28 2024 21:21:54 GMT+0000 (Coordinated Universal Time) https://runkit.com/mmoaf44

@calazar23 #undefined

star

Fri Jun 28 2024 21:16:20 GMT+0000 (Coordinated Universal Time) https://runkit.com/mmoaf44

@calazar23 #undefined

star

Fri Jun 28 2024 21:15:23 GMT+0000 (Coordinated Universal Time) https://runkit.com/mmoaf44/667f244977a01c000922ec90

@calazar23 #undefined

star

Fri Jun 28 2024 21:14:13 GMT+0000 (Coordinated Universal Time) https://runkit.com/mmoaf44/667f244977a01c000922ec90

@calazar23 #undefined

star

Fri Jun 28 2024 21:05:33 GMT+0000 (Coordinated Universal Time) https://runkit.com/mmoaf44/667f244977a01c000922ec90

@calazar23 #undefined

star

Fri Jun 28 2024 21:05:21 GMT+0000 (Coordinated Universal Time) https://runkit.com/mmoaf44/667f244977a01c000922ec90

@calazar23 #undefined

star

Fri Jun 28 2024 21:03:27 GMT+0000 (Coordinated Universal Time) https://runkit.com/mmoaf44/667f244977a01c000922ec90

@calazar23 #undefined

star

Fri Jun 28 2024 21:03:22 GMT+0000 (Coordinated Universal Time) https://runkit.com/mmoaf44/667f244977a01c000922ec90

@calazar23 #undefined

star

Fri Jun 28 2024 21:03:19 GMT+0000 (Coordinated Universal Time) https://runkit.com/mmoaf44/667f244977a01c000922ec90

@calazar23 #undefined

star

Fri Jun 28 2024 20:56:14 GMT+0000 (Coordinated Universal Time) https://www.npmjs.com/package/@rollup/plugin-auto-install

@calazar23

star

Fri Jun 28 2024 20:56:06 GMT+0000 (Coordinated Universal Time) https://www.npmjs.com/package/@rollup/plugin-auto-install

@calazar23

star

Fri Jun 28 2024 14:14:05 GMT+0000 (Coordinated Universal Time) https://appticz.com/crypto-com-clone-script

@aditi_sharma_

star

Fri Jun 28 2024 10:20:57 GMT+0000 (Coordinated Universal Time)

@iamkatmakhafola

star

Fri Jun 28 2024 08:03:06 GMT+0000 (Coordinated Universal Time) https://www.alphacodez.com/cryptocurrency-exchange-script

@jacksonjackk #html #angular #css #javascript #java #sql #mysql

star

Fri Jun 28 2024 08:00:36 GMT+0000 (Coordinated Universal Time) https://www.alphacodez.com/cryptocurrency-exchange-script

@jacksonjackk #html #angular #css #javascript #java #sql #mysql

star

Fri Jun 28 2024 06:07:11 GMT+0000 (Coordinated Universal Time) https://youtu.be/1CdolnvxLs0

@vishnu_jha #c++ #dsa #2darray #spiralprint

star

Fri Jun 28 2024 05:38:13 GMT+0000 (Coordinated Universal Time) eyJkYXRhc2V0X3F1ZXJ5Ijp7InR5cGUiOiJuYXRpdmUiLCJuYXRpdmUiOnsiY29sbGVjdGlvbiI6InVzZXJDaGFsbGVuZ2VNYXBwaW5nIiwicXVlcnkiOiJbXHJcbiAgICB7XHJcbiAgICAgICAgXCIkbWF0Y2hcIjoge1xyXG4gICAgICAgICAgICBcImNoYWxsZW5nZUlkXCI6IE9iamVjdElkKFwiNjY3NDQwNDQxMzk1ODU0M2I1OTRmZTZmXCIpXHJcbiAgICAgICAgfVxyXG4gICAgfSxcclxuICAgIHtcclxuICAgICAgICBcIiRwcm9qZWN0XCI6IHtcclxuICAgICAgICAgICAgXCJlbWFpbFwiOiBcIiRyZWdpc3RyYXRpb25EZXRhaWxzLmVtYWlsXCIsXHJcbiAgICAgICAgICAgIFwicG9pbnRzXCI6IFwiJG92ZXJBbGxJbXBhY3QucG9pbnRcIixcclxuICAgICAgICAgICAgXCJXZWlnaHRJbXBhY3RcIjogXCIkb3ZlckFsbEltcGFjdC5vdmVyQWxsV2VpZ2h0SW1wYWN0XCIsXHJcbiAgICAgICAgICAgIFwiZXZlbnRQb2ludHNcIjogXCIkZXZlbnRQb2ludFwiLFxyXG4gICAgICAgICAgICBcIndlZWtseVdlaWdodExvZ1wiOiB7XHJcbiAgICAgICAgICAgICAgICBcIiRvYmplY3RUb0FycmF5XCI6IFwiJHdlZWtseVdlaWdodExvZ1wiXHJcbiAgICAgICAgICAgIH1cclxuICAgICAgICB9XHJcbiAgICB9LFxyXG4gICAge1xyXG4gICAgICAgIFwiJHVud2luZFwiOiBcIiR3ZWVrbHlXZWlnaHRMb2dcIlxyXG4gICAgfSxcclxuICAgIHtcclxuICAgICAgICBcIiRhZGRGaWVsZHNcIjoge1xyXG4gICAgICAgICAgICBcIndlZWtseVdlaWdodExvZy5rRGF0ZVwiOiB7XHJcbiAgICAgICAgICAgICAgICBcIiR0b0RhdGVcIjogXCIkd2Vla2x5V2VpZ2h0TG9nLmtcIlxyXG4gICAgICAgICAgICB9XHJcbiAgICAgICAgfVxyXG4gICAgfSxcclxuICAgIHtcclxuICAgICAgICBcIiRzb3J0XCI6IHtcclxuICAgICAgICAgICAgXCJ3ZWVrbHlXZWlnaHRMb2cua0RhdGVcIjogLTFcclxuICAgICAgICB9XHJcbiAgICB9XHJcbl1cclxuIiwidGVtcGxhdGUtdGFncyI6e319LCJkYXRhYmFzZSI6Mn0sImRpc3BsYXkiOiJ0YWJsZSIsInZpc3VhbGl6YXRpb25fc2V0dGluZ3MiOnt9fQ

@CodeWithSachin #aggregation #mongodb #$objecttoarray #$addfiels

star

Fri Jun 28 2024 05:34:15 GMT+0000 (Coordinated Universal Time) http://34.74.16.180:3000/question#eyJkYXRhc2V0X3F1ZXJ5Ijp7ImRhdGFiYXNlIjo2NSwibmF0aXZlIjp7ImNvbGxlY3Rpb24iOiJwYXJ0aWNpcGFudERpZXRNZWFsUGxhbkRldGFpbHMiLCJxdWVyeSI6IltcclxuICAgIHtcclxuICAgICAgICBcIiRtYXRjaFwiOiB7XHJcbiAgICAgICAgICAgIFwibWVhbFBsYW5cIjoge1xyXG4gICAgICAgICAgICAgICAgXCIkZWxlbU1hdGNoXCI6IHtcclxuICAgICAgICAgICAgICAgICAgICBcInBvcnRpb25NZWFzdXJlXCI6IFwiVGVhIFNwb29uXCIsXHJcbiAgICAgICAgICAgICAgICAgICAgXCJkaXNoVmFyaWF0aW9uXCI6IFwiUGFuZWVyIFBhcmF0aGFcIlxyXG4gICAgICAgICAgICAgICAgfVxyXG4gICAgICAgICAgICB9XHJcbiAgICAgICAgfVxyXG4gICAgfSxcclxuICAgIHtcclxuICAgICAgICRjb3VudDpcInRvYXRhbFwiXHJcbiAgICB9XHJcbl1cclxuIiwidGVtcGxhdGUtdGFncyI6e319LCJ0eXBlIjoibmF0aXZlIn0sImRpc3BsYXkiOiJ0YWJsZSIsInZpc3VhbGl6YXRpb25fc2V0dGluZ3MiOnt9fQ==

@CodeWithSachin #aggregation #mongodb #elemmatch #elem #match #$elemmatch

star

Fri Jun 28 2024 05:16:11 GMT+0000 (Coordinated Universal Time) https://youtu.be/1CdolnvxLs0

@vishnu_jha #c++ #dsa #2darray #waveprint

star

Fri Jun 28 2024 01:54:40 GMT+0000 (Coordinated Universal Time)

@NoFox420 #javascript

star

Fri Jun 28 2024 01:18:49 GMT+0000 (Coordinated Universal Time) https://learn.microsoft.com/en-us/previous-versions/windows/it-pro/windows-server-2012-r2-and-2012/cc730714(v

@Mad_Hatter

star

Thu Jun 27 2024 22:26:09 GMT+0000 (Coordinated Universal Time)

@NoFox420 #javascript

star

Thu Jun 27 2024 18:03:42 GMT+0000 (Coordinated Universal Time)

@iamkatmakhafola

star

Thu Jun 27 2024 13:32:23 GMT+0000 (Coordinated Universal Time)

@MinaTimo

star

Thu Jun 27 2024 11:32:01 GMT+0000 (Coordinated Universal Time) https://youtu.be/Wdjr6uoZ0e0

@vishnu_jha #c++ #dsa #string

star

Thu Jun 27 2024 11:23:15 GMT+0000 (Coordinated Universal Time) https://nikaserver.store/global/wp-admin/admin.php?page

@Pulak

star

Thu Jun 27 2024 11:08:26 GMT+0000 (Coordinated Universal Time) https://youtu.be/Wdjr6uoZ0e0

@vishnu_jha #c++ #dsa #string

star

Thu Jun 27 2024 09:41:00 GMT+0000 (Coordinated Universal Time)

@karticksriram #c

star

Thu Jun 27 2024 08:13:37 GMT+0000 (Coordinated Universal Time)

@rafal_rydz

star

Thu Jun 27 2024 07:32:14 GMT+0000 (Coordinated Universal Time) https://www.dappfort.com/cryptocurrency-exchange-script/

@novamichelin #react.js #cryptocurrency #bitcoin #javascript

star

Thu Jun 27 2024 06:34:02 GMT+0000 (Coordinated Universal Time) https://forum.laravel-livewire.com/t/livewire-and-alpine-and-a-masking-plugin/2912/3

@xsirlalo

star

Thu Jun 27 2024 05:44:50 GMT+0000 (Coordinated Universal Time)

@NoFox420 #javascript

Save snippets that work with our extensions

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