Snippets Collections
bool linearsearch (int *arr, int size, int key) {
  if (size == 0)
    return false;
  if(arr[0]==key)
    return true;
  else 
    return linearsearch(arr+1, size-1, key);
}
bool isArraySorted (int arr[],int size) {
  if (size == 0 || size == 1) 
    return true;
  if (arr[0]>arr[1]) 
    return false;
  else {
    bool remainingPart = isArraySorted(arr+1,size-1); 
    return remainingPart;
  }
  
}
class Solution {
public:
    int fib(int n) {
        if (n==0)
        return 0;
        if (n==1)
        return 1;
        return fib(n-1)+fib(n-2);
        
    }
};
#include <iostream>
using namespace std;

void sayDigit (int n,string arr[]) {
  if (n==0) 
    return;
  if (n>0) {
    int digit = n%10;
    n = n/10;
    sayDigit(n,arr);
    cout << arr[digit] << " ";
  }
}

int main () {
  string arr[10] = {"zero","one","two","three","four","five","six","seven","eight","nine"};
  int n;
  cin >> n;
  sayDigit(n,arr);
  return 0;
}
In an earlier project you learned about truthy and falsy values, which are values that evaluate to true or false. In JavaScript, some common falsy values you'll see are null, undefined, the number 0, and empty strings.

Rather than check if a value is equal to a falsy value, you can use the logical NOT operator (!) to check if the value itself is falsy. For example:

const num = 0;

console.log(num === 0); // true
console.log(!num); // true

A good way to check and normalize numbers in JavaScript is to use the built-in parseInt() function, which converts a string into an integer or whole number. parseInt() takes at least one argument, a string to be converted into an integer, and returns either an integer or NaN which stands for Not a Number. For example:

parseInt(2.2); // 2
parseInt("2e+3"); // 2
parseInt("e") // NaN

Next, you need to check if the value returned by the parseInt() function is a number or not.

To do that, you can use the isNaN() function. This function takes in a string or number as an argument, and returns true if it evaluates to NaN. For example:

isNaN("test"); // true
isNaN(2); // false
isNaN("3.5"); // false

The setTimeout function takes two arguments: a callback function and a number representing the time in milliseconds to wait before executing the callback function.

For example, if you wanted to log "Hello, world!" to the console after 3 seconds, you would write:

setTimeout(() => {
  console.log("Hello, world!");
}, 3000);

If you test your code, you'll notice that your console logs are not in the expected order. Instead of logging "free", pausing for a second before logging "Code", and finally logging "Camp", you'll see this:

Example Code
free
Camp
Code
This is because the setTimeout() function is asynchronous, meaning that it doesn't stop the execution of the rest of your code. All the code in the showAnimation() function runs line by line, but because setTimeout() is asynchronous, free and Camp are logged to the console immediately, and then Code is logged to the console after a one second delay.

While asynchronous, or async, code can be difficult to understand at first, it has many advantages. One of the most important is that it allows you to write non-blocking code.

For example, imagine you're baking a cake, and you put the cake in the oven and set a timer. You don't have to sit in front of the oven waiting the entire time – you can wash dishes, read a book, or do anything else while you wait for the timer to go off.

Async code works in a similar way. You can start an async operation and other parts of your code will still work while that operation is running.
build
.gitignore
doc
manuals
README.md
material
set-qt-project.jpg
set-qt-version.png
resources
.gitignore
README-zh.md
build-openark-zh.md
build-openark.md
build-qt5-static-library.md
code-style-guide.md
release
src
tools
.gitattributes
CONTRIBUTORS
LICENSE
README.md
 LocalStorage is a web storage feature of JavaScript that lets you persist data by storing the data as a key:value pair.
 
In earlier projects, you learned how to add and remove classes from an element with el.classList.add() and el.classList.remove(). Another method to use with the classList property is the toggle method.

The toggle method will add the class if it is not present on the element, and remove the class if it is present on the element.

element.classList.toggle("class-to-toggle");

The HTML dialog element has a showModal() method that can be used to display a modal dialog box on a web page.

dialogElement.showModal();

The HTML dialog element has a close() method that can be used to close a modal dialog box on a web page.

dialogElement.close();

The findIndex() array method finds and returns the index of the first element in an array that meets the criteria specified by a provided testing function. If no such element is found, the method returns -1.

Here's an example:

const numbers = [3, 1, 5, 6];
const firstNumLargerThanThree = numbers.findIndex((num) => num > 3);

console.log(firstNumLargerThanThree); // prints index 2

To make the id more unique, add another hyphen and use Date.now().

Date.now() returns the number of milliseconds elapsed since January 1, 1970 00:00:00 UTC.

console.log(Date.now()); // 1628586800000

Instead of clearing the input fields one by one, it's a good practice to create a function that handles clearing those fields. You can then call this function whenever you need to clear the input fields again.

splice() is an array method that modifies arrays by removing, replacing, or adding elements at a specified index, while also returning the removed elements. It can take up to three arguments: the first one is the mandatory index at which to start, the second is the number of items to remove, and the third is an optional replacement element. Here's an example:

const fruits = ["mango", "date", "cherry", "banana", "apple"];

// Remove date and cherry from the array starting at index 1
const removedFruits = fruits.splice(1, 2);

console.log(fruits); // [ 'mango', 'banana', 'apple' ]
console.log(removedFruits); // [ 'date', 'cherry' ]

localStorage offers methods for saving, retrieving, and deleting items. The items you save can be of any JavaScript data type.

For instance, the setItem() method is used to save an item, and the getItem() method retrieves the item. To delete a specific item, you can utilize the removeItem() method, or if you want to delete all items in the storage, you can use clear().

Here's how you can save an item:

localStorage.setItem("key", value); // value could be string, number, or any other data type

If you check the "Application" tab of your browser console, you'll notice a series of [object Object]. This is because everything you save in localStorage needs to be in string format.

To resolve the issue, wrap the data you're saving in the JSON.stringify() method. 

The syntax for reading the localStorage item is as follows:

const cat = localStorage.getItem("myCat");

The syntax for removing the localStorage item is as follows:

localStorage.removeItem("myCat");

The syntax for removing all the localStorage items is as follows:

localStorage.clear();
We are going to use a method called Object.freeze(obj) which will freeze this object and prevent any changes being made to it.

In the last two steps, you have been accessing properties from the myFavoriteFootballTeam object using dot notation and assigning them to new const variables. But in JavaScript, there is an easier way to accomplish the same goal.

The object destructuring syntax allows you to unpack values from arrays and objects:

const developerObj = {
  name: "Jessica Wilkins",
  isDeveloper: true
};

// Object destructuring
const { name, isDeveloper } = developerObj;

Function parameters can be initialized with default values. If a function is called without an argument, then the default value will be used:

const greeting = (name = "Anonymous") => {
  return "Hello " + name;
} 

console.log(greeting("John")); // Hello John
console.log(greeting()); // Hello Anonymous
//// Forgot password
//[HttpPost("ForgotPassword")]
//public async Task<IActionResult> ForgotPassword(ForgotPasswordViewModel model)
//{
//    try
//    {
//        if (string.IsNullOrEmpty(model.Email))
//        {
//            return BadRequest("Email is required.");
//        }

//        var user = await _userManager.FindByEmailAsync(model.Email);
//        if (user == null)
//        {
//            return Ok("Do not exist.");
//        }

//        var token = await _userManager.GeneratePasswordResetTokenAsync(user);
//        var resetLink = Url.Action("ResetPassword", "User",
//                                   new { token, email = user.Email },
//                                   protocol: HttpContext.Request.Scheme);

//        var mailtoLink = $"mailto:{model.Email}?subject=Password%20Reset&body=Reset%20your%20password%20by%20clicking%20the%20following%20link:%20{WebUtility.UrlEncode(resetLink)}";

//        await SendResetPasswordEmail(model.Email, resetLink); // Send reset password email

//        return Ok("Please check your email for password reset instructions.");
//    }
//    catch (Exception ex)
//    {
//        _logger.LogError(ex, "Error sending reset password email.");
//        return StatusCode(StatusCodes.Status500InternalServerError, "Error sending reset password email.");
//    }
//}

//[HttpPost]
//[Route("ForgotPassword")]
//public IActionResult ForgotPassword(ForgotPasswordViewModel model)
//{
//    try
//    {

//        if (string.IsNullOrEmpty(model.Email))
//        {
//            return BadRequest("Email is required.");
//        }

//        var resetLink = $"mailto:{WebUtility.UrlEncode(model.Email)}?subject=Reset%20Password&body=Click%20the%20following%20link%20to%20reset%20your%20password:%20[RESET_LINK_HERE]";

//        // Redirect the user to the mailto link
//        return Redirect(resetLink);
//    }
//    catch (Exception)
//    {
//        return BadRequest("Failed");
//    }
//}


// Reset password
//[HttpPost("ResetPassword")]
//public async Task<IActionResult> ResetPassword(ResetPasswordViewModel model)
//{
//    if (!ModelState.IsValid)
//    {
//        return BadRequest("Invalid data.");
//    }

//    var user = await _userManager.FindByEmailAsync(model.Email);
//    if (user == null)
//    {
//        return NotFound("User not found.");
//    }

//    var result = await _userManager.ResetPasswordAsync(user, model.Token, model.Password);
//    if (result.Succeeded)
//    {
//        return Ok("Password has been reset successfully.");
//    }

//    return BadRequest("Error while resetting the password.");
//}

//private async Task SendResetPasswordEmail(string email, string resetLink)
//{
//    try
//    {
//        var smtpClient = new SmtpClient(_configuration["Smtp:Host"])
//        {
//            Port = int.Parse(_configuration["Smtp:Port"]),
//            Credentials = new NetworkCredential(_configuration["Smtp:Username"], _configuration["Smtp:Password"]),
//            EnableSsl = bool.Parse(_configuration["Smtp:EnableSsl"]),
//        };

//        var mailMessage = new MailMessage
//        {
//            From = new MailAddress(_configuration["Smtp:From"]),
//            Subject = "Reset Password",
//            Body = $"<h4>Reset your password by <a href='{resetLink}'>clicking here</a></h4>",
//            IsBodyHtml = true,
//        };
//        mailMessage.To.Add(email);

//        await smtpClient.SendMailAsync(mailMessage);
//    }
//    catch (SmtpException ex)
//    {
//        _logger.LogError(ex, "Error sending reset password email.");
//        throw;
//    }
//}
//Before Domain
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

//After domain
SG.a1b2C3d4E5F6g7H8i9J0kL1m2N3O4P5Q6R7s8T9u0V1W2X3Y4Z5a6B7c8D9E0fG1H2i3J4K5L6

//latest
test api key 2.0
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
​const p1={
  name:"Raphael",
  age:21,
  isMaried:false,
  say:()=>{
    console.log(`I'm ${p1.name} I'm ${p1.age} years old`);
    if(p1.isMaried === false){
      console.log(`I'm Celobator`);
    }else{
      console.log(`I'm maried`);
    }
  }
}
p1.say()
const Width = ({ children }) => children(500);
Route::middleware([
    'auth:sanctum',
    config('jetstream.auth_session'),
    'verified',
])->group(function () {
    Route::redirect('/dashboard', '/admin');
});

Route::get('/', Dashboard::class)
    ->name('dashboard');

Route::get('/posts/{post:slug}', Show::class)
    ->name('posts.show');
{
    "api_key": "...",
    "language": "et_EE",
    "limit": 1
}
{
    "id": null,
    "jsonrpc": "2.0",
    "result": {
        "data": [
            {
                "create_date": "2019-10-10 14:16:52",
                "description": "Komplektis on ~40 osa ja konstruktori kokkupanek on lihtne tänu samm-sammult järgitavale juhendile",
                "id": 1,
                "last_change_date": "2019-10-10 14:18:11",
                "name": "Komplektis on ~40 osa ja konstruktori kokkupanek on lihtne tänu samm-sammult järgitavale juhendile",
                "priority": 1,
                "product_ids_m2m": []
            }
        ],
        "status": "success"
    }
}
{
    "api_key": "...",
    "language": "et_EE",
    "product_ids": [1],
}
{
    "id": null,
    "jsonrpc": "2.0",
    "result": {
        "data": {
            "1": []
        },
        "status": "success"
    }
}
{
    "api_key": "...",
    "language": "et_EE",
    "product_ids": [1],
}
{
    "id": null,
    "jsonrpc": "2.0",
    "result": {
        "status": "success",
        "data": {
            "1": {
                "main_image_base64": "/9j/4AAQSkZJRgABAQAAA...",
                "additional_images": []
            }
        },
    },
} 
{
    "api_key": "...",
    "ids": [1],
    "language": "et_EE"
}
{
    "id": null,
    "jsonrpc": "2.0",
    "result": {
        "data": [
            {
                "associated_category": false,
                "code": false,
                "create_date": "2019-10-09 08:52:25",
                "id": 1,
                "last_change_date": "2019-10-09 08:52:25",
                "name": "Arduino",
                "product_ids_m2m": []
            }
        ],
        "status": "success"
    }
}
 {
    "api_key": "...",
    "language": "et_EE",
    "limit": 1,
    "brand_ids": [35],
}
{
    "id": null,
    "jsonrpc": "2.0",
    "result": {
        "status": "success",
        "data": [{
            "width": 0.0,
            "video": false,
            "origin_country": "CN",
            "last_change_date": "2020-01-03 10:00:10",
            "age_from": 3.0,
            "quantity_available": 1.0,
            "age_to": 0.0,
            "keywords": false,
            "dimensions": false,
            "height": 0.0,
            "wholesale_price": 47.94,
            "length": 0.0,
            "recommended_retail_price": 69.9,
            "name": "Õuepintslid (tekstuuripintslid)",
            "description_sale": "Nende uuenduslike pintslitega saab luua suurele pinnale mitmekesiseid mustreid, tekstuure ja märke tõmbamise, vajutamise, kaapimise ja keerutamise teel. Neljast varrest ja eri otstest koosnev komplekt sobib kasutamiseks värvi, vee (lombid) ja liivaga. Valmistatud plastist. Komplektis 4 tk. L 22 x P 55 cm.\n ",
            "create_date": "2019-07-04",
            "category_ids": [],
            "description_sale_long": false,
            "additional_picture_urls": ["https://www.insplay.eu/web/image/product.image/43195/image_raw"]
            "main_picture_url": "https://www.insplay.eu/web/image/product.product/35/image_raw"
            "net_weight": 1.24,
            "more_info_url": "www.tts-international.com",
            "id": 4022,
            "brand_id": [
                35, 
                "TTS"
            ],
            "tariff_no": "95030095",
            "under_3_forbidden": true,
            "product_code": "AR00797B",
            "ean13": false,
            "related_products_ids_m2m": [],
            "old_nav_category": "DE2F3A4E-877B-4C14-93C1-FB9F957F2748",
            "out_of_production": false,
        }]
    },
}
{
    "api_key": "...",
    "language": "et_EE",
    "limit": 1,
}
{
    "id": null,
    "jsonrpc": "2.0",
    "result": {
        "data": [
            {
                "code": false,
                "create_date": "2019-10-29 15:01:52",
                "id": 2950,
                "is_published": false,
                "last_change_date": "2020-01-03 10:00:17",
                "name": "Robootika ja elektroonika",
                "parent_category_id": false,
                "priority": 10000
            }
        ],
        "status": "success"
    }
}
 {
    "api_key": "...",
    "language": "et_EE",
    "limit": 1,
    "search_name": "TTS",
}
{
    "id": null,
    "jsonrpc": "2.0",
    "result": {
        "data": [
            {
                "create_date": "2019-08-26 08:18:06",
                "description": false,
                "id": 35,
                "last_change_date": "2019-12-06 08:26:03",
                "logo_base64": "/9j/4AAQSkZJRgABAQAAA...",
                "name": "TTS"
            }
        ],
        "status": "success"
    }
}
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);
star

Sun Jun 30 2024 08:47:07 GMT+0000 (Coordinated Universal Time)

@vishnu_jha #c++ #dsa #recursion #array #linearsearch

star

Sun Jun 30 2024 08:15:40 GMT+0000 (Coordinated Universal Time)

@vishnu_jha #c++ #dsa #recursion #array

star

Sun Jun 30 2024 06:50:19 GMT+0000 (Coordinated Universal Time)

@vishnu_jha #c++ #dsa #fibonacci #recursion

star

Sun Jun 30 2024 06:48:41 GMT+0000 (Coordinated Universal Time)

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

star

Sun Jun 30 2024 06:22:51 GMT+0000 (Coordinated Universal Time) https://www.freecodecamp.org/news/python-code-examples-sample-script-coding-tutorial-for-beginners/

@Aarav_2008

star

Sun Jun 30 2024 06:22:47 GMT+0000 (Coordinated Universal Time) https://www.freecodecamp.org/news/python-code-examples-sample-script-coding-tutorial-for-beginners/

@Aarav_2008

star

Sun Jun 30 2024 06:22:38 GMT+0000 (Coordinated Universal Time) https://www.freecodecamp.org/news/python-code-examples-sample-script-coding-tutorial-for-beginners/

@Aarav_2008

star

Sun Jun 30 2024 06:22:32 GMT+0000 (Coordinated Universal Time) https://www.freecodecamp.org/news/python-code-examples-sample-script-coding-tutorial-for-beginners/

@Aarav_2008

star

Sun Jun 30 2024 06:22:31 GMT+0000 (Coordinated Universal Time) https://www.freecodecamp.org/news/python-code-examples-sample-script-coding-tutorial-for-beginners/

@Aarav_2008 #python

star

Sun Jun 30 2024 05:26:31 GMT+0000 (Coordinated Universal Time)

@NoFox420 #javascript

star

Sun Jun 30 2024 05:06:51 GMT+0000 (Coordinated Universal Time) https://plzrun.tistory.com/entry/clone된-로컬-저장소에서-삭제된-파일-복구하는-방법

@khyinto

star

Sun Jun 30 2024 05:06:49 GMT+0000 (Coordinated Universal Time) https://plzrun.tistory.com/entry/clone된-로컬-저장소에서-삭제된-파일-복구하는-방법

@khyinto

star

Sun Jun 30 2024 05:06:48 GMT+0000 (Coordinated Universal Time) https://plzrun.tistory.com/entry/clone된-로컬-저장소에서-삭제된-파일-복구하는-방법

@khyinto

star

Sun Jun 30 2024 02:41:54 GMT+0000 (Coordinated Universal Time) https://github.com/BlackINT3/OpenArk

@Dewaldt

star

Sun Jun 30 2024 00:47:34 GMT+0000 (Coordinated Universal Time)

@NoFox420 #javascript

star

Sun Jun 30 2024 00:44:03 GMT+0000 (Coordinated Universal Time)

@NoFox420 #javascript

star

Sat Jun 29 2024 18:35:15 GMT+0000 (Coordinated Universal Time)

@iamkatmakhafola

star

Sat Jun 29 2024 16:09:04 GMT+0000 (Coordinated Universal Time) https://codepen.io/pen/

@raphael #undefined

star

Sat Jun 29 2024 15:59:42 GMT+0000 (Coordinated Universal Time) https://reactpatterns.com/

@reedjones #react.js #javascript

star

Sat Jun 29 2024 13:52:30 GMT+0000 (Coordinated Universal Time)

@pablopetr

star

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

@insplay

star

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

@insplay

star

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

@insplay

star

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

@insplay

star

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

@insplay

star

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

@insplay

star

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

@insplay

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

Save snippets that work with our extensions

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