Snippets Collections
Sucess Banner:
<div class="slds-box slds-box_small slds-theme_success">
  
Failure Banner:
<div class="slds-box slds-box_small slds-theme_error">

Warning Banner:
<div class="slds-box slds-box_small slds-theme_warning">

Information Banner:
<div class="slds-box slds-box_small slds-theme_shade">

Success Notification 
<div class="slds-scoped-notification slds-theme_success" role="status">

Failure  Notification
<div class="slds-scoped-notification slds-theme_error" role="status">
  
Warning Notification 
<div class="slds-scoped-notification slds-theme_warning" role="status">

SELECT 
    CASE 
        WHEN nombre = 'FEDERICO DE LEON' 
        THEN 'Jefe de Transformacion y Personas'
        ELSE PUENOM
    END AS PUENOM,
    AVG(SUELDO) AS Promedio_Sueldo_Anual,
    AVG(PRODUCTIVIDAD) AS Promedio_Productividad,
    AVG([COMISIONES VARIABLES]) AS Promedio_Comisiones_Variables_Anual,
    AVG(GRATIFICACION) AS Promedio_Gratificacion
FROM (
    SELECT 
        RTRIM(primer_nombre) + ' ' + RTRIM(primer_apellido) AS nombre,
        PUENOM,
        [PREMIOS] AS PRODUCTIVIDAD,
        [COMISIONES VARIABLES] AS [COMISIONES VARIABLES],
        [SUELDO] AS SUELDO,
        [GRATIFICACION]
    FROM (
        SELECT 
            vista_completa.primer_nombre,
            vista_completa.primer_apellido,
            PUESTOS.PUENOM,
            vista_completa.DEPARTAMENTO_NOMBRE,
            VISTA_GENEXCEL.FECHA_INGRESO,
            vista_genexcel.mes_y_anio,
            vista_genexcel.importe,
            vista_completa.fecha_de_egreso,
            CASE 
                WHEN vista_genexcel.CONCEPTO IN (45, 40, 46) THEN 'COMISIONES VARIABLES'
                ELSE vista_genexcel.concepto_nombre
            END AS concepto_nombre
        FROM 
            sueldosprod.dbo.fundef FUNDEF,
            sueldosprod.dbo.puestos PUESTOS,
            sueldosprod.dbo.vista_genexcel VISTA_GENEXCEL
            INNER JOIN sueldosprod.dbo.vista_completa VISTA_COMPLETA
                ON vista_genexcel.funcionario = vista_completa.ci
        WHERE  
            ((( vista_genexcel.mes_y_anio >= {ts '2024-08-01 00:00:00'} ) and ( vista_genexcel.mes_y_anio < {ts '2024-09-01 00:00:00'} )) or ( vista_genexcel.mes_y_anio >= {ts '2024-01-01 00:00:00'} and VISTA_GENEXCEL.CONCEPTO=2000))
            AND fundef.deffuncod = vista_completa.funcionario_codigo
            AND puestos.empcod = fundef.empcod
            AND puestos.puecod = fundef.puecod
            AND vista_genexcel.CONCEPTO IN (1, 44, 20, 45, 40, 46, 2000)
    ) AS SourceTable
    PIVOT (
        SUM(importe)
        FOR concepto_nombre IN ([PREMIOS], [COMISIONES VARIABLES], [SUELDO],[GRATIFICACION])
    ) AS PivotTable
    WHERE fecha_de_egreso IS NULL 
) AS ResultTable
where PUENOM != 'SIN DEFINIR'
GROUP BY 
    CASE 
        WHEN nombre = 'FEDERICO DE LEON' 
        THEN 'Jefe de Transformacion y Personas'
        ELSE PUENOM
    END
<?php
/**
 * Front to the WordPress application. This file doesn't do anything, but loads
 * wp-blog-header.php which does and tells WordPress to load the theme.
 *
 * @package WordPress
 */

/**
 * Tells WordPress to load the WordPress theme and output it.
 *
 * @var bool
 */
define( 'WP_USE_THEMES', true );

/** Loads the WordPress Environment and Template */
require __DIR__ . '/wp-blog-header.php';
//@version=5
strategy("MA30 Long Strategy ", overlay=true)
 
// Set the trading date range
startDate = timestamp(2020, 01, 01, 00, 00)
endDate = timestamp(2024, 12, 31, 23, 59)
 
// Calculate the 30-period moving average
ma30 = ta.sma(close, 30)
ma2= ta.sma(close, 10)
 
// Calculate the standard deviation of the last 30 periods
stdDev = ta.stdev(close, 30)
 
// Maximum position size as 10% of the available capital
positionSize = strategy.equity * 1 / close
 
// Define the exit level (1.5 standard deviations below the MA30)
stopLossPercentage = 0.08
stopPriceShort = close * (1 + stopLossPercentage)
exitLevel =  ma2 - (1.5* stdDev) 
 
// Define the strategy logic for trading
if (time >= startDate and time <= endDate)  // Only trade within the specified date range
    // Open a long position when the stock price crosses above the MA30
    if (ta.crossover(close, ma30))
        // Open a long position using 10% of the fund
        strategy.entry("Long", strategy.long, qty = positionSize)
        
    // Close the position when the stock price drops below 1.5 standard deviations from the MA30
    if (close < ma30 )
        // Close the long position
        strategy.close("Long")
 
longlen = input.int(30, "Long MA Length", minval=1)
long = ta.sma(close, longlen)
plot(long, color = color.rgb(249, 18, 18), title="Long MA")
import pendulum

current_date = pendulum.now().date()
uploaded_date = pendulum.date(2018, 8, 1)

diff_days = current_date.diff(uploaded_date).in_days()

print(current_date.subtract(days = diff_days).diff_for_humans()) # 6 years ago
import pendulum

try:
    print(pendulum.parse('{:0>2}-{:0>2}-{:0>2}'.format(2024, 9, 21)))
except Exception as e:
    print(e)
model/userbackend:

class Userbackend extends ActiveRecord implements IdentityInterface
{
    const STATUS_DELETED = 0;
    const STATUS_ACTIVE = 10;
    const ROLE_ADMIN = 25; //RolMaximo
    const ROLE_ENTE = 15; //Rol#1
    const ROLE_SUP_ENTE = 20; //Rol#2
    const ROLE_PRESIDENTE_ENTE = 26; //Rol#3
    const ROLE_VICEMINISTRO_SECTOR = 30; //Rol#4
    const ROLE_DESPACHO_MINISTRO = 35; //Rol#5

 public function getRole()
    {
        if ($this->role == self::ROLE_ADMIN) { //MAXIMO
            $r = 'ADMINISTRADOR';
        } elseif ($this->role == self::ROLE_ENTE) {//Rol#1
            $r = 'ENTE';
        } elseif ($this->role == self::ROLE_SUP_ENTE) { //Rol#2
            $r = 'SUPERVIDOR ENTE';
        } elseif ($this->role == self::ROLE_PRESIDENTE_ENTE) {//Rol#3
            $r = 'PRESIDENTE ENTE';

        } elseif ($this->role == self::ROLE_VICEMINISTRO_SECTOR){//Rol#4
            $r = 'VICEMINISTRO SECTOR';

        } elseif ($this->role == self::ROLE_DESPACHO_MINISTRO) {//Rol#5
            $r = 'DESPACHO MINISTRO';

        } else {
            $r = '';
        }
        return $r;
    }

nota: las siguientes lineas van debajo de la siguiente funcion:

public function getDatosUsuario()
    {
        return $this->nomper . " " . $this->apeper . " (" . $this->username . ")";
    }

// desde aqui

public static function isUserAdmin($username)
    {
        if (static::findOne(['username' => $username, 'role' => self::ROLE_ADMIN])) {//maximo
            return true;
        } else {
            return false;
        }
    }

    
    public static function isUserEnte($username)
    {
        if (static::findOne(['username' => $username, 'role' => self::ROLE_ENTE])) {//Rol#1
            return true;
        } else {
            return false;
        }
    }

    public static function isUserSup_Ente($username)
    {
        if (static::findOne(['username' => $username, 'role' => self::ROLE_SUP_ENTE])) {//Rol#2
            return true;
        } else {
            return false;
        }
    }

    public static function isUserPres_Ente($username)
    {
        if (static::findOne(['username' => $username, 'role' => self::ROLE_PRESIDENTE_ENTE])) {//Rol#3
            return true;
        } else {
            return false;
        }
    }


    public static function isUserVice_Sector($username)
    {
        if (static::findOne(['username' => $username, 'role' => self::ROLE_VICEMINISTRO_SECTOR])) {//Rol#4
            return true;
        } else {
            return false;
        }
    }

    public static function isUserDesp_Ministro($username)
    {
        if (static::findOne(['username' => $username, 'role' => self::ROLE_DESPACHO_MINISTRO])) {//Rol#5
            return true;
        } else {
            return false;
        }
    }

from pynput.keyboard import Listener

def on_press(key):
    print(str(key))


with Listener(on_press = on_press) as l:
    l.join()
#include <iostream>
#include <bits/stdc++.h>
 using namespace std;


void findTimeToBuyTicket(vector<int> tickets ,int k){
   
    int timetaken=0;
    while(tickets[k]!=0){
       
      for (int i =0;i<tickets.size();i++){
         if(tickets[i] ==0){
          continue;
         }
        tickets[i]--;
        timetaken++;
        if(i==k){
            break;
        }
    }
    }
    cout<<"Time taken of kth person is: " <<timetaken<<endl;
}
 

 int main() {
 //Write your C++ code here
 vector<int> tickets ={5,1,1,1};
 findTimeToBuyTicket(tickets,2);
 return 0;
 }
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Calculator</title>
    <style>
        body {
            font-family: Arial, sans-serif;
            margin: 20px;
        }
        input, button {
            margin: 5px;
            padding: 10px;
            font-size: 16px;
        }
        #result {
            margin-top: 20px;
            font-weight: bold;
        }
    </style>
</head>
<body>

    <h3>Simple Calculator</h3>
    <input type="number" id="value1" placeholder="Enter first number">
    <input type="number" id="value2" placeholder="Enter second number">
    
    <div>
        <button name="add" onclick="add()">ADDITION</button>
        <button name="sub" onclick="sub()">SUBTRACT</button>
        <button name="mul" onclick="mul()">MULTIPLY</button>
        <button name="div" onclick="div()">DIVISION</button>
    </div>

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

    <script>
        function add() {
            const value1 = parseFloat(document.getElementById('value1').value);
            const value2 = parseFloat(document.getElementById('value2').value);
            const result = value1 + value2;
            document.getElementById('result').innerText = `Addition of ${value1} and ${value2} is ${result}`;
        }

        function sub() {
            const value1 = parseFloat(document.getElementById('value1').value);
            const value2 = parseFloat(document.getElementById('value2').value);
            const result = value1 - value2;
            document.getElementById('result').innerText = `Subtraction of ${value1} and ${value2} is ${result}`;
        }

        function mul() {
            const value1 = parseFloat(document.getElementById('value1').value);
            const value2 = parseFloat(document.getElementById('value2').value);
            const result = value1 * value2;
            document.getElementById('result').innerText = `Multiplication of ${value1} and ${value2} is ${result}`;
        }

        function div() {
            const value1 = parseFloat(document.getElementById('value1').value);
            const value2 = parseFloat(document.getElementById('value2').value);
            if (value2 === 0) {
                document.getElementById('result').innerText = 'Error: Division by zero';
            } else {
                const result = value1 / value2;
                document.getElementById('result').innerText = `Division of ${value1} and ${value2} is ${result}`;
            }
        }
    </script>

</body>
</html>
#include <iostream>
#include <bits/stdc++.h>
 using namespace std;


void findStudentsUnableToEatLunch(queue<int> food, queue<int>students){
    int foodNotMatched =0;
    while(!food.empty()){

    if(students.front() == food.front()){
        food.pop();
        students.pop();
    }else{
        foodNotMatched++;
        if(foodNotMatched == students.size()){
            break;
        }else{
            students.push(students.front());
            students.pop();
        }
    }
      
    
    
}
cout<<"The element remaning is: " << students.size()<<endl;
}
 

 int main() {
 //Write your C++ code here
 queue<int> food;
 food.push(1);
 food.push(0);
 food.push(0);
 food.push(0);
 food.push(1);
 food.push(1);
 queue<int> students;
 students.push(1);
 students.push(1);
 students.push(1);
 students.push(0);
 students.push(0);
 students.push(1);
 findStudentsUnableToEatLunch(food,students);
 return 0;
 }
<a href="facebook.com">hhh</a>
Understanding Solana Meme Coin Development

In the fast-paced world of cryptocurrencies, meme coins have become a unique trend, combining fun with digital innovation. Solana meme coins highlight this trend through their use of the Solana blockchain. Known for its high speed and low transaction costs, Solana offers an ideal platform for these meme coins. Solana meme coins blend the playful spirit of meme culture with the advanced technology of Solana, making them stand out in the crypto market. This introduction will explore what makes Solana meme coins special, their benefits, and how they are shaping the future of digital assets.
Innovative Technology
The advanced technology of the Solana blockchain, renowned for its quick transaction times and inexpensive fees, is utilized by Solana meme currencies. Because meme currencies frequently involve large volume, low-value exchanges, Solana's distinct Proof of History (PoH) agreement process in conjunction with Proof of Stake (PoS) guarantees quick and safe transactions, which makes it the perfect platform for meme currencies that seek to garner community involvement as well as commercial attention.
The Rise of Solana Meme Coins
Solana meme coins are gaining popularity because they blend internet culture with advanced blockchain tech. Thanks to Solana’s fast and affordable network, these tokens attract both crypto fans and the general public. Solana’s ability to process many transactions quickly makes it perfect for meme coins, which often see rapid trading and high price swings. This trend shows how playful, community-focused projects can thrive with strong technology, capturing the spirit of the crypto world and engaging a wide range of online communities.
Community Engagement
Community involvement is key to the success of Solana meme coins. These coins thrive on the enthusiasm and support of their online communities, which help drive their popularity and value. Active communities engage in discussions, share memes, and promote the coin across social media platforms, creating a buzz around the project. Events, giveaways, and collaborative activities further strengthen community bonds and encourage more people to get involved. By fostering a strong, engaged community, Solana meme coins can build a loyal user base and sustain interest, making community support a key factor in their growth and success.
Future Prospects for Solana Meme Coins:
The future looks bright for Solana meme coins as they continue to grow in popularity. With Solana’s fast and low-cost transactions, these meme coins can handle increasing activity and trading volume. As more people join the Solana ecosystem, meme coins could see greater adoption and integration into various applications. The community’s enthusiasm and creativity will likely drive new projects and innovations. Additionally, as the crypto market evolves, Solana meme coins may benefit from increased visibility and support, potentially leading to new opportunities and expanded use cases. Overall, their future appears promising with ongoing development and engagement.

Solana Updates and Upgrades
Solana consistently updates and upgrades its blockchain to boost performance and enhance security. Recent advancements include optimizations for transaction speed and scalability, ensuring the network handles growing demand efficiently. Upgrades also focus on reducing fees and enhancing developer tools, which support the growth of decentralized applications and tokens. These ongoing improvements strengthen Solana’s position as a leading platform, benefiting projects like meme coins by providing a robust and reliable infrastructure.
 Conclusion
Beleaf Technologies has demonstrated remarkable growth and innovation in Solana meme coin development. The company has established itself as a leader by consistently leveraging cutting-edge technology and fostering a culture of creativity and excellence. Their commitment to delivering high-quality solutions and adapting to the ever-evolving technological landscape positions them well for continued success.
Visit — https://www.beleaftechnologies.com/solana-meme-coin
Contact Details:
Phone +91 8148147362

Are you ready to dive into the awesome world of Solana meme coins? These super cool tokens are all about having a blast and connecting with others. Not only that, but they're also making a big impact on the future of cryptocurrency and adding some extra fun to the Solana network.
Visit us:https://www.beleaftechnologies.com/solana-meme-coin
#SolanaMemeCoin #SolanaShenanigans #SolanaLols #SOLMeme #SolanaLaughs #SOLFun
 #MemeCoinOnSOL #SolanaToTheMoon #SOLGiggles #SolanaVibes

Visit — https://www.beleaftechnologies.com/solana-meme-coin
Contact Details:
Phone +91 8148147362
R Studio has emerged as one of the most powerful tools for data analysis, statistical computing, and graphical representation. Students in various fields such as data science, statistics, and computer science rely heavily on it for their academic projects. However, mastering R Studio is no easy task. It requires a deep understanding of programming concepts, statistical theories, and the ability to work with complex data sets. This is where R Studio assignment help becomes essential for students striving to excel in their coursework.

One of the major reasons why students seek assistance with R Studio assignments is the complexity of the software itself. It is a versatile tool that offers extensive libraries and functions for data manipulation and visualization. However, students often find it challenging to implement these tools effectively without proper guidance. This can lead to frustration, especially when faced with tight deadlines. Seeking r studio assignment help can save time, reduce stress, and ensure that assignments are completed accurately and on time. Professional assistance allows students to focus on learning and understanding the core concepts rather than getting bogged down by technical difficulties.

Moreover, R Studio assignments often involve advanced statistical analysis, which can be daunting for students who are not well-versed in these concepts. Statistical modeling, hypothesis testing, regression analysis, and data visualization are common components of these assignments. For students unfamiliar with these techniques, completing the tasks becomes overwhelming. In such situations, seeking expert r studio assignment help is a practical solution. With professional guidance, students can gain a clearer understanding of statistical concepts and learn how to apply them effectively in R Studio.

In addition to the complexity of the assignments, another reason students opt for help is the need for high-quality submissions. Academic assignments are often graded based on accuracy, clarity, and presentation. Submitting an assignment with errors or poorly presented data can result in low grades, even if the student understands the concepts. By turning to experts, students can ensure their assignments meet academic standards. Professional services like myassignment help offer tailored solutions that not only assist with coding and statistical analysis but also ensure that the final submission is well-structured and free of errors.

Lastly, learning how to navigate and utilize R Studio effectively is a skill that extends beyond academia. As industries increasingly rely on data-driven decision-making, proficiency in R Studio has become a valuable asset in the job market. Students who seek help with their assignments are not only ensuring their academic success but are also building a strong foundation for their future careers. R Studio assignment help provides students with the opportunity to develop these critical skills while managing their academic workload efficiently.

In conclusion, the complexity of R Studio, coupled with the demands of academic assignments, makes professional assistance a valuable resource for students. Whether it’s to save time, ensure accuracy, or enhance understanding, seeking r studio assignment help is an essential step toward academic and career success. For students looking for comprehensive support, platforms like myassignment help offer expert guidance, enabling them to tackle their assignments with confidence

Visit : https://myassignmenthelp.expert/r-studio-assignment-help.html
connectedCallback() {
        const inputAligncenter = document.createElement('style');
        inputAligncenter.innerText = `c-fdvgc_simulation-financial-create-quote-qroup {position: relative;} .uiModal--horizontalForm .modal-container:has(c-fdvgc_simulation-financial-create-quote-qroup) { width: 99%; max-width: 99%;} .runtime_platform_actionsQuickActionWrapper .quick-actions-panel:has(c-fdvgc_simulation-financial-create-quote-qroup) { overflow-y: clip;}`;
        document.body.appendChild(inputAligncenter);
    }

int converter(int decimalno)
{
    int binaryno = 0;
    
    for(int base = 1; decimalno > 0; decimalno /= 2)
    {
        binaryno += (decimalno % 2) * base;
        base *= 10;
    }
    
    return binaryno;
}
set.seed(28092024) 
n <- 3 
sample_norm <- rnorm(3,0,sqrt(5)) 
unb_estim <- var(sample_norm) 
max_estim <- var(sample_norm) * ((n-1)/n) 
mse_estim <- var(sample_norm) * ((n-1)/(n+1)) 
popul_var <- 5



estimates <- c(max_estim , unb_estim , mse_estim ) 
differences <- estimates - popul_var 
result <- data.frame( Estimator = c("MLE", "Unbiased", "MinMSE"), Estimate = estimates, Difference = differences ) 
print(result)
barplot(result$Difference, names.arg = result$Estimator, main = "Difference of Estimator values fromTrue Population Variance", ylab = "Difference", col = c("red", "green", "blue"), ylim = c(min(result$Difference) - 1, max(result$Difference) + 1))



calculate_estimators <- function(n, S, mean, popul_var) { 
unbiased_vals <- numeric(S) 
mle_vals <- numeric(S) 
mse_vals <- numeric(S) 
for (i in 1:S) { 
sample <- rnorm(n, mean, sqrt(popul_var)) 
unbiased <- var(sample) 
mle <- unbiased * ((n - 1) / n) 
minmse <- unbiased * ((n - 1) / (n + 1)) 
unbiased_vals[i] <- unbiased 
mle_vals[i] <- mle 
mse_vals[i] <- minmse } 
return(list( unbiased_var = unbiased_vals, mle_var = mle_vals, mse_var = mse_vals )) } 



stats_calc <- function(estimate_vals, popul_var) { 
avg_val <- mean(estimate_vals) 
bias <- avg_val - popul_var 
variance <- var(estimate_vals) 
mse <- mean((estimate_vals - popul_var)^2) 
return(c(Average = avg_val, Bias = bias, Variance = variance, MSE = mse)) } 
exp_n3 = calculate_estimators(3,10000,0,sqrt(5))
exp_n20 = calculate_estimators(20,10000,0,sqrt(5))
exp_n200 = calculate_estimators(200,10000,0,sqrt(5))



results_n3 <- data.frame( Estimator = c("Unbiased", "MLE", "MinMSE"), Average = c(n3_unbiased_stats["Average"], n3_mle_stats["Average"], n3_minmse_stats["Average"]), Bias = c(n3_unbiased_stats["Bias"], n3_mle_stats["Bias"], n3_minmse_stats["Bias"]), Variance = c(n3_unbiased_stats["Variance"], n3_mle_stats["Variance"], n3_minmse_stats["Variance"]), MSE = c(n3_unbiased_stats["MSE"], n3_mle_stats["MSE"], n3_minmse_stats["MSE"]) )

results_n20 <- data.frame( Estimator = c("Unbiased", "MLE", "MinMSE"), Average = c(n20_unbiased_stats["Average"], n20_mle_stats["Average"], n20_minmse_stats["Average"]), Bias = c(n20_unbiased_stats["Bias"], n20_mle_stats["Bias"], n20_minmse_stats["Bias"]), Variance = c(n20_unbiased_stats["Variance"], n20_mle_stats["Variance"], n20_minmse_stats["Variance"]), MSE = c(n20_unbiased_stats["MSE"], n20_mle_stats["MSE"], n20_minmse_stats["MSE"]) )


results_n200 <- data.frame( Estimator = c("Unbiased", "MLE", "MinMSE"), Average = c(n200_unbiased_stats["Average"], n200_mle_stats["Average"], n200_minmse_stats["Average"]), Bias = c(n200_unbiased_stats["Bias"], n200_mle_stats["Bias"], n200_minmse_stats["Bias"]), Variance = c(n200_unbiased_stats["Variance"], n200_mle_stats["Variance"], n200_minmse_stats["Variance"]), MSE = c(n200_unbiased_stats["MSE"], n200_mle_stats["MSE"], n200_minmse_stats["MSE"]) )





<?php
// تأكد من تثبيت مكتبة apple-signin-php باستخدام Composer
require_once 'vendor/autoload.php';

use AppleSignIn\ASDecoder;

// إعدادات قاعدة البيانات
$servername = "localhost";
$username = "nullsafety_app";
$password = "gQ0T(DHze!5L";
$dbname = "nullsafety_app";

// إعدادات Apple Sign In
$LOGIN_APPLE_CLIENT_ID = "io.fitness.club";
$LOGIN_APPLE_SECRET = "eyJraWQiOiJMQ1hESDJSTDJSIiwiYWxnIjoiRVMyNTYifQ.eyJpc3MiOiI2TFRESjJITldZIiwiaWF0IjoxNjk3MTQ2MDU2LCJleHAiOjE3MTI2OTgwNTYsImF1ZCI6Imh0dHBzOi8vYXBwbGVpZC5hcHBsZS5jb20iLCJzdWIiOiJpby5maXRuZXNzLmNsdWIifQ.D4YPbDBiRv76ToNUa9Lll1F82uohsgIUzIN4x-NBNahfZuC_A8LTNzFuaBDCBp4m5ohPa9eTc2xoK4NRJjWJWA";

// إنشاء اتصال
$conn = new mysqli($servername, $username, $password, $dbname);

// التحقق من الاتصال
if ($conn->connect_error) {
    die("فشل الاتصال: " . $conn->connect_error);
}

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    // استلام البيانات من Apple
    $id_token = $_POST['id_token'];
    
    try {
        // فك تشفير وتحقق من الـ token
        $appleSignInPayload = ASDecoder::getAppleSignInPayload($id_token);
        
        // استخراج معلومات المستخدم
        $email = $appleSignInPayload->getEmail();
        $user_id = $appleSignInPayload->getUser();
        // الاسم غير متوفر دائمًا، لذا نحتاج للتحقق
        $name = isset($_POST['user']) ? json_decode($_POST['user'])->name : null;
        
        // التحقق مما إذا كان المستخدم موجودًا بالفعل
        $stmt = $conn->prepare("SELECT id FROM users WHERE apple_id = ?");
        $stmt->bind_param("s", $user_id);
        $stmt->execute();
        $result = $stmt->get_result();
        
        if ($result->num_rows > 0) {
            // المستخدم موجود بالفعل، قم بتحديث المعلومات إذا لزم الأمر
            $stmt = $conn->prepare("UPDATE users SET email = ?, name = ? WHERE apple_id = ?");
            $stmt->bind_param("sss", $email, $name, $user_id);
        } else {
            // مستخدم جديد، قم بإدراجه في قاعدة البيانات
            $stmt = $conn->prepare("INSERT INTO users (apple_id, email, name) VALUES (?, ?, ?)");
            $stmt->bind_param("sss", $user_id, $email, $name);
        }
        
        if ($stmt->execute()) {
            echo "تم تسجيل الدخول وحفظ البيانات بنجاح!";
        } else {
            echo "حدث خطأ أثناء حفظ البيانات: " . $stmt->error;
        }
        
    } catch (Exception $e) {
        echo "حدث خطأ: " . $e->getMessage();
    }
}

$conn->close();
?>

<!DOCTYPE html>
<html>
<head>
    <title>تسجيل الدخول باستخدام Apple</title>
</head>
<body>
    <div id="appleid-signin" data-color="black" data-border="true" data-type="sign in"></div>
    <script type="text/javascript" src="https://appleid.cdn-apple.com/appleauth/static/jsapi/appleid/1/en_US/appleid.auth.js"></script>
    <script type="text/javascript">
        AppleID.auth.init({
            clientId : '<?php echo $LOGIN_APPLE_CLIENT_ID; ?>',
            scope : 'name email',
            redirectURI : 'https://developer.null-safety.com/',
            state : 'YOUR_STATE_VALUE'
        });
    </script>
</body>
</html>
SELECT DurableId, FlowDefinitionView.Label, VersionNumber, Status FROM FlowVersionView WHERE FlowDefinitionView.Label LIKE '%PLACE PART OF THE FLOW NAME HERE%' AND Status != 'Active'



/* NOTE: When IMPORTING (Delete Action) - Mark API Type as "Tooling API", limit the batch to 10 and 1 thread (SF Limitation), and change DurableId to ID */
var ProductTypes = new Product_Type[]
{
  // Types for "Tops" (Category_ID = 1)
  new Product_Type { Type_ID = 1, Type_Name = "Shirts", Category_ID = 1 },  // T-shirts, long sleeves, crop tops
    new Product_Type { Type_ID = 2, Type_Name = "Tank Tops", Category_ID = 1 }, // All tank tops
      new Product_Type { Type_ID = 3, Type_Name = "Hoodies", Category_ID = 1 },   // Sleeveless and regular hoodies
        new Product_Type { Type_ID = 4, Type_Name = "Sweats", Category_ID = 1 },    // Sweatshirts and similar

          // Types for "Bottoms" (Category_ID = 2)
          new Product_Type { Type_ID = 5, Type_Name = "Shorts", Category_ID = 2 },    // All types of shorts
            new Product_Type { Type_ID = 6, Type_Name = "Joggers", Category_ID = 2 },   // Joggers and sweatpants
              new Product_Type { Type_ID = 7, Type_Name = "Leggings", Category_ID = 2 },  // All leggings
                new Product_Type { Type_ID = 8, Type_Name = "Compression Tights", Category_ID = 2 }, // Compression tights

                  // Types for "Gear" (Category_ID = 3)
                  new Product_Type { Type_ID = 9, Type_Name = "Gloves", Category_ID = 3 },    // Weightlifting gloves, workout gloves
                    new Product_Type { Type_ID = 10, Type_Name = "Socks", Category_ID = 3 },    // Athletic socks
                      new Product_Type { Type_ID = 11, Type_Name = "Accessories", Category_ID = 3 } // Wrist wraps, resistance bands, gym bags, etc.
};

builder.Entity<Product_Type>().HasData(ProductTypes);
import Axios from 'axios';
import CONFIG from '../../../config/config';
import moment from 'moment';

const url = {
  getPortfolioSurveysConsultants:
    CONFIG.BASE_URL + 'double-materiality/getPortfolioSurveysConsultants',
  getSurveys: CONFIG.BASE_URL + 'double-materiality/getSurveys',
};
/*
 Desc: Api to create double materiality
 Params: Data:- will be save on collection based on consultantId
*/ const localUrl =
  'http://localhost:17538/api/v1/';

const createDoubleMaterialitySurvey = async data => {
  let url = CONFIG.BASE_URL + 'createSurveyResult';
  const response = await Axios.post(url, data, {
    headers: {
      'x-api-key': CONFIG.X_API_KEY,
    },
    mode: 'no-cors',
  });
  return response;
};

/*
 Desc: Api to update double materiality
 Params: Data:- will be save on collection based on consultantId
 consultantId:- to identity collection
 currentSurveyId:- id to update doc in collection
 surveyId:- id to update doc in collection
*/
const updateDoubleMaterialitySurvey = async (data, consultantId, currentSurveyId, surveyId) => {
  let url =
    CONFIG.BASE_URL +
      'double-materiality/portfolio-surveys-consultants' +
      '?currentSurveyId=' +
      currentSurveyId ??
    '' + '&surveyId=' + surveyId ??
    '' + '&consultantId=' + consultantId;
  const response = await Axios.put(url, data, {
    headers: {
      'x-api-key': CONFIG.X_API_KEY,
    },
    mode: 'no-cors',
  });
  return response;
};

/*
 Desc: Api to get double materiality details
 Params: 
 consultantId:- to identity collection
 surveyId:- id to update doc in collection
*/
const getbysurveyid = async (surveyId,consultantId) => {
  const response = await Axios.get(`${CONFIG.BASE_URL}getbysurveyid?surveyId=${surveyId}&consultantId=${consultantId || ''}`, {
    headers: {
      'x-api-key': CONFIG.X_API_KEY,
    },
    mode: 'no-cors'
})
if(response?.data?.data['survey-results']) {
  delete response?.data?.data['survey-results'];
}
if(response?.data?.data['workshops']) {
  delete response?.data?.data['workshops'];
}
if(response?.data?.data['financial-workshops']) {
  delete response?.data?.data['financial-workshops'];
}

  return { response, data: () => response?.data?.data || {}, id: response?.data?.data?.id ?? '' };
};

/*
 Desc: Api to get surveyresults details
 Params: 
 consultantId:- to identity collection
 surveyId:- fetch data based on surveyId
*/
const getsurveyresultsbysurveyId = (surveyId,consultantId) => {
  return Axios.get(`${CONFIG.BASE_URL}getsurveyresultsbysurveyId?surveyId=${surveyId}&consultantId=${consultantId || ''}`, {
    headers: {
      'x-api-key': CONFIG.X_API_KEY,
    },
    mode: 'no-cors'
  })
}

/*
 Desc: Api to get workshops details
 Params: 
 consultantId:- to identity collection
surveyId:- fetch data based on surveyId
*/
const getworkshopsbysurveyId = (surveyId,consultantId) => {
  return Axios.get(`${CONFIG.BASE_URL}getworkshopsbysurveyId?surveyId=${surveyId}&consultantId=${consultantId || ''}`, {
    headers: {
      'x-api-key': CONFIG.X_API_KEY,
    },
    mode: 'no-cors'
  })
}

/*
 Desc: Api to get financialworkshops details
 Params: 
 consultantId:- to identity collection
surveyId:- fetch data based on surveyId
*/
const getfinancialworkshopsbysurveyid = (surveyId,consultantId) => {
  return Axios.get(`${CONFIG.BASE_URL}getfinancialworkshopsbysurveyid?surveyId=${surveyId}&consultantId=${consultantId || ''}`, {
    headers: {
      'x-api-key': CONFIG.X_API_KEY,
    },
    mode: 'no-cors'
  })
}

/*
 Desc: function to get subcollection details
 Params: 
 consultantId:- to identity collection
 surveyId:- fetch data based on surveyId
 collectionName: indicate collection name
*/
const getSurveyResultForSubcollection = async (surveyId, consultantId, collectionName) => {
  try {
    if(collectionName == 'survey-results') {
      const response = await getsurveyresultsbysurveyId(surveyId,consultantId);
      const [surveyResult = []] =  response?.data?.data;

      let value = parseSnapShortData(response,collectionName);
      return value;
    }
    if(collectionName == 'workshops') {
      const response = await getworkshopsbysurveyId(surveyId,consultantId);
      const [surveyResult = []] =  response?.data?.data;

      let value = parseSnapShortData(response,collectionName);
      debugger
      return value;
    }
    if(collectionName == 'financial-workshops') {
      const response = await getfinancialworkshopsbysurveyid(surveyId,consultantId);
      const [surveyResult = []] =  response?.data?.data;

      let value = parseSnapShortData(response,collectionName);
      return value;
    }
    if (collectionName == 'dashboard-worksheet-audit-logs') {
      let url = 'getsurveyDashboardWorksheetAuditLogs';
      if (consultantId) {
        url = 'getportfolioSurveyDashboardWorksheetAuditLogs';
      }
      const response = await Axios.get(
        `${CONFIG.AUDIT_LOG_URL}${url}?surveyId=${surveyId}&consultantId=${consultantId || ''}`,
        {
          headers: {
            'x-api-key': CONFIG.X_API_KEY,
          },
          mode: 'no-cors',
        },
      );
      // const [surveyResult = []] =  response?.data?.data;
      let value = parseLogSnapShortData(response, collectionName);
      return value;
    }
    if (collectionName == 'methodology-logs') {
      let url = 'getSurveyMethodologyLogs';
      if (consultantId) {
        url = 'getportfolioSurveyMethodologyLogs';
      }
      const response = await Axios.get(
        `${CONFIG.AUDIT_LOG_URL}${url}?surveyId=${surveyId}&consultantId=${consultantId || ''}`,
        {
          headers: {
            'x-api-key': CONFIG.X_API_KEY,
          },
          mode: 'no-cors',
        },
      );
      // const [surveyResult = []] =  response?.data?.data;

      let value = parseLogSnapShortData(response, collectionName);
      return value;
    }
    if (collectionName == 'methodology-task-logs') {
      let url = 'getsurveyMethodologyTaskAuditLogModel';
      if (consultantId) {
        url = 'getportfolioSurveyMethodologyTaskAuditLogModel';
      }

      const response = await Axios.get(
        `${CONFIG.AUDIT_LOG_URL}${url}?surveyId=${surveyId}&consultantId=${consultantId || ''}`,
        {
          headers: {
            'x-api-key': CONFIG.X_API_KEY,
          },
          mode: 'no-cors',
        },
      );
      // const [surveyResult = []] =  response?.data?.data;
      let value = parseLogSnapShortData(response, collectionName);
      return value;
    }
    if (collectionName == 'action-report-task-logs') {
      let url = 'getsurveyActionReportLogs';
      if (consultantId) {
        url = 'getportfolioSurveyActionReportLogs';
      }

      const response = await Axios.get(
        `${CONFIG.AUDIT_LOG_URL}${url}?surveyId=${surveyId}&consultantId=${consultantId || ''}`,
        {
          headers: {
            'x-api-key': CONFIG.X_API_KEY,
          },
          mode: 'no-cors',
        },
      );
      // const [surveyResult = []] =  response?.data?.data;
      let value = parseLogSnapShortData(response, collectionName);
      return value;
    }
    if (collectionName == 'audit-log') {
      let url = 'getbysurveyId';
      if (consultantId) {
        url = 'getbyportfolioSurveyConsultantId';
      }

      const response = await Axios.get(
        `${CONFIG.AUDIT_LOG_URL}${url}?surveyId=${surveyId}&consultantId=${consultantId || ''}`,
        {
          headers: {
            'x-api-key': CONFIG.X_API_KEY,
          },
          mode: 'no-cors',
        },
      );
      // const [surveyResult = []] =  response?.data?.data;
      let value = parseLogSnapShortData(response, collectionName);
      return value;
    }
  } catch (error) {
    console.log(error, 'error');
  }
};

const getsubmittedSurveyResult = async (surveyId,consultantId) => {
  const response = await Axios.get(`${CONFIG.BASE_URL}getsubmittedSurveyResult?surveyId=${surveyId}&consultantId=${consultantId || ''}`, {
    headers: {
      'x-api-key': CONFIG.X_API_KEY,
    },
    mode: 'no-cors'
  })
  let value = [];
  if (response?.data?.data?.length && response?.data?.data[0]['survey-results']?.length) {
    value = response?.data?.data[0]['survey-results'].map((v, i) => {
      return {
        data: () => v,
        id: v.id || i,
      };
    });
  }
 
  return value;
}

/*
 Desc: function to parse the response and return in expected formate
 Params: 
 response: Response from collection
*/
const parseSnapShortData = response => {
  const surveyResult = response?.data?.data ?? [];
  let value = [];
  if (surveyResult?.length) {
    value = surveyResult.map((v, i) => {
      return {
        data: () => v || {},
        id: v.id || v?._id?.toString() || i,
      };
    });
  }
  return value;
};

const parseLogSnapShortData = (response, collectionName) => {
  const surveyResult = response?.data?.data ?? [];
  let value = [];
  if (surveyResult?.length) {
    value = surveyResult.map((v, i) => {
      return {
        data: () => v || {},
        id: v.id || v?._id?.toString() || i,
      };
    });
  }
  return value;
};

/*
 Desc: Api to update double materiality
 Params: 
 consultantId:- to identity collection
 surveyId:- fetch data based on surveyId
*/
const updateSurveyById =  (consultantId,surveyId,currentSurveyId) => {
  let url = CONFIG.BASE_URL+'double-materiality/portfolio-surveys-consultants'+'?surveyId='+surveyId ?? '';
  url += '&consultantId='+consultantId ?? '';
  url += '&currentSurveyId='+currentSurveyId ?? '';

  const update = async (data, url) => {
    const response = await Axios.put(url, data, {
      headers: {
        'x-api-key': CONFIG.X_API_KEY,
      },
      mode: 'no-cors',
    });
    return response;
  };

  return { update: data => update(data, url), consultantId, surveyId, currentSurveyId };
};

const addToMethodologyLogs = (consultantId, surveyId, currentSurveyId) => {
  let url = CONFIG.AUDIT_LOG_URL + 'setSurveyMethodologyLogs';
  if (consultantId) {
    url = CONFIG.AUDIT_LOG_URL + 'setportfolioSurveyMethodologyLogs';
  }
  
  const add  = async (data,url) => {
    const id =  surveyId ? surveyId :  currentSurveyId;
    console.log(url)
    data = {
      data,
      surveyId: id,
      currentSurveyId,
    };

    const response = await Axios.post(url, data, {
      headers: {
        'x-api-key': CONFIG.X_API_KEY,
      },
      mode: 'no-cors',
    });
    return response;
  }
  
  return {add : (data) => add(data,url) , consultantId, surveyId,currentSurveyId};
}


const setWorkshops = async (consultantId,data) => {
  let url = CONFIG.BASE_URL+'double-materiality/set-workshops?';
    url += '&consultantId='+consultantId ?? '';
    const response = await Axios.post(url,data, {
      headers: {
        'x-api-key': CONFIG.X_API_KEY,
      },
      mode: 'no-cors',
    });
    return response;
}

const updateWorkshops = async (consultantId,id,data) => {
  let url = CONFIG.BASE_URL+'double-materiality/update-workshops?';
    url += '&consultantId='+consultantId ?? '';
    url += '&id='+id ?? '';
    const response = await Axios.put(url,data, {
      headers: {
        'x-api-key': CONFIG.X_API_KEY,
      },
      mode: 'no-cors',
    });
    return response;
}

const setFinancialWorkshops = async (consultantId,data) => {
  let url = CONFIG.BASE_URL+'double-materiality/set-financial-workshops?';
    url += '&consultantId='+consultantId ?? '';
    const response = await Axios.post(url,data, {
      headers: {
        'x-api-key': CONFIG.X_API_KEY,
      },
      mode: 'no-cors',
    });
    return response;
}

const updateFinancialWorkshops = async (consultantId,id,data) => {
  let url = CONFIG.BASE_URL+'double-materiality/update-financial-workshops?';
    url += '&consultantId='+consultantId ?? '';
    url += '&id='+id ?? '';
    const response = await Axios.put(url,data, {
      headers: {
        'x-api-key': CONFIG.X_API_KEY,
      },
      mode: 'no-cors',
    });
    return response;
}


/**
 * Desc: Api to get survey result by id
 * Params: 
    surveyResultId:- to fetch data based on the survey result
 */
const getSurveyResultById = async surveyResId => {
  const response = await Axios.get(
    `${CONFIG.BASE_URL}getsurveyresultsbyId?surveyResultId=${surveyResId}`,
    {
      headers: {
        'x-api-key': CONFIG.X_API_KEY,
      },
      mode: 'no-cors',
    },
  );
  return { response, data: () => response?.data?.data || {}, id: response?.data?.data?.id ?? '' };
};

/**
 * Desc: Api to update survey result
 * Params: 
    consultantId: to identify the collection
    data: to be added in survey-results
 */
const setSurveyResult = async (consultantId, data) => {
  let url = CONFIG.BASE_URL + 'double-materiality/set-survey-results?';
  url += '&consultantId=' + consultantId ?? '';
  const response = await Axios.post(url, data, {
    headers: {
      'x-api-key': CONFIG.X_API_KEY,
    },
    mode: 'no-cors',
  });
  return response;
};

/**
 * Desc: Api to update survey result
 * Params: 
    consultantId: to identify the collection
    id: id of the survey-result to be updated
    data: to be updated against the survey-result selected
 */
const updateSurveyResultData = async (consultantId, id, data) => {
  let url = CONFIG.BASE_URL + 'double-materiality/update-survey-results?';
  url += 'consultantId=' + consultantId ?? '';
  url += '&id=' + id ?? '';
  const response = await Axios.put(url, data, {
    headers: {
      'x-api-key': CONFIG.X_API_KEY,
    },
    mode: 'no-cors',
  });
  return response;
};

const addToSurveyResults = (surveyId, currentSurveyId) => {
  const url = CONFIG.BASE_URL + 'insertIntoSurveyResults';
  const add = async (payload, url) => {
    const id = surveyId ? surveyId : currentSurveyId;

    const data = {
      data: payload,
      surveyId: id,
    };

    const response = await Axios.post(url, data, {
      headers: {
        'x-api-key': CONFIG.X_API_KEY,
      },
      mode: 'no-cors',
    });
    return response;
  };

  return { add: payload => add(payload, url), surveyId, currentSurveyId };
};

const addToAuditLogs = (consultantId, surveyId, currentSurveyId) => {
  let url = CONFIG.AUDIT_LOG_URL + 'addauditstosurveys';
  if (consultantId) {
    url = CONFIG.AUDIT_LOG_URL + 'addauditstoportfoilosurveysconsultants';
  }
 
  const add = async (data, url) => {
    const id = surveyId ? surveyId : currentSurveyId;
    console.log(url);
    data = {
      data,
      surveyId: id,
      currentSurveyId,
    };
 
    const response = await Axios.post(url, data, {
      headers: {
        'x-api-key': CONFIG.X_API_KEY,
      },
      mode: 'no-cors',
    });
    return response;
  };
 
  return { add: data => add(data, url), consultantId, surveyId, currentSurveyId };
};

/**
 * Adds a new comment to an answered topic.
 * @param {Object} params - an object containing surveyId and consultantId.
 * @param {Object} body - data to be sent in the request body.
 * @returns {Object} - an object containing response, data and status.
 * @throws {Error} - if unable to fetch the workshop.
 */

const addAnsweredTopicComment = async (params, body) => {
  const { surveyId, consultantId } = params;
  let URL = `${localUrl}addAnsweredTopic?surveyId=${surveyId}&consultantId=${consultantId || ""}`;

  try {
    const response = await Axios.post(URL, body, {
      headers: {
        'x-api-key': CONFIG.X_API_KEY,
      },
      mode: 'no-cors',
    });

    return {
      response: response?.data?.data || {},
      data: () => response?.data?.data,
      status: response?.status,
    };
  } catch (error) {
    console.log(error);
    throw new Error('Failed to fetch workshop');
  }
};

const editAnsweredTopicComment = async (params, body) => {
  const { surveyId, consultantId, workshopId } = params;
  console.log("workshopId", workshopId)
  let URL = `${localUrl}updateAnsweredTopic?surveyId=${surveyId}&consultantId=${consultantId || ""}&workshopId=${workshopId || ""}`;
  console.log("URL", URL)
  try {
    const response = await Axios.put(URL, body, {
      headers: {
        'x-api-key': CONFIG.X_API_KEY,
      },
      mode: 'no-cors',
    });

    return {
      response: response?.data?.data || {},
      data: () => response?.data?.data,
      status: response?.status,
    };
  } catch (error) {
    console.log(error);
    throw new Error('Failed to fetch workshop');
  }
};

/**
 * Updates a workshop property based on given endpoint, params and data.
 * @param {Object} params - an object containing surveyId, consultantId, workshopId, type and property.
 * @param {Object} data - data to be sent in the request body.
 * @returns {Object} - an object containing response and a function to get the data.
 * @throws {Error} - if unable to fetch the workshop.
 */
const updateWorkshopProperty = async (params, body) => {
  const { surveyId, consultantId, workshopId, type, property } = params;
  console.log('workshopId', workshopId);
  let URL = `${localUrl}double-materiality/update-workshop-property?surveyId=${surveyId}&consultantId=${consultantId ||
    ''}&workshopId=${workshopId || ''}&type=${type}`;

  if (property) URL += `&property=${property}`;

  console.log('URL', URL);

  try {
    const response = await Axios.post(URL, body, {
      headers: {
        'x-api-key': CONFIG.X_API_KEY,
      },
      mode: 'no-cors',
    });

    return {
      response: response?.data?.data || {},
      data: () => response?.data?.data,
      status: response?.status,
    };
  } catch (error) {
    console.log(error);
    throw new Error('Failed to fetch workshop');
  }
};

/*
 * Updates consultants or survey Model property based on given endpoint, params and data.
 * @param {Object} params - an object containing surveyId, consultantId and property.
 * @param {Object} data - data to be sent in the request body.
 * @returns {Object} - an object containing response and a function to get the data.
 * @throws {Error} - if unable to fetch the workshop.
 */
const updateConsultantsOrSurveyProperty = async (params, body) => {
  const { surveyId, consultantId, property } = params;
  let URL = `${localUrl}double-materiality/updateConsultantsOrSurvey?surveyId=${surveyId}&consultantId=${consultantId ||
    ''}`;

  if (property) URL += `&property=${property}`;

  try {
    const response = await Axios.post(URL, body, {
      headers: {
        'x-api-key': CONFIG.X_API_KEY,
      },
      mode: 'no-cors',
    });

    return {
      response: response?.data?.data || {},
      data: () => response?.data?.data,
      status: response?.status,
    };
  } catch (error) {
    console.log(error);
    throw new Error('Failed to fetch workshop');
  }
}


/**
 * Creates a new document with the action report task audit log details based on the data provided.
 * @param {String} consultantId - consultantId to identify the collection
 * @param {String} surveyId - surveyId to fetch data based on
 * @param {String} currentSurveyId - currentSurveyId to fetch data based on if surveyId is not provided
 * @returns {Object} - an object containing add function and consultantId, surveyId, currentSurveyId
 * @throws {Error} - if unable to created the document.
 */
const addToActionReportTaskAuditLogs = (consultantId, surveyId, currentSurveyId) => {
  let url = CONFIG.AUDIT_LOG_URL + 'setSurveyActionReportLogs';
  if (consultantId) {
    url = CONFIG.AUDIT_LOG_URL + 'setportfolioSurveyActionReportLogs';
  }

  const add = async (data, url) => {
    const id = surveyId ? surveyId : currentSurveyId;
    data = {
      data,
      surveyId: id,
      currentSurveyId
    }

    const response = await Axios.post(url, data, {
      headers: {
        'x-api-key': CONFIG.X_API_KEY,
      },
      mode: 'no-cors',
    });
    return response;
  }

  return { add: (data) => add(data, url), consultantId, surveyId, currentSurveyId };
}

/**
 * Creates a new document with the double materiality audit log details based on the data provided.
 * @param {data} params - contains surveyId, consultantId, field and updated by details
 * @returns {Object} - an object with status
 * @throws {Error} - if unable to created the document.
 */
const addToDoubleMaterialityAuditLog = (consultantId, surveyId) => {
  let url = CONFIG.AUDIT_LOG_URL + 'setDoubleMaterialityAuditLogs';

  const add = async (data, url) => {
    const response = await Axios.post(url, data, {
      headers: {
        'x-api-key': CONFIG.X_API_KEY,
      },
      mode: 'no-cors',
    });
    return response;
  }

  return { add: (data) => add(data, url), consultantId, surveyId };
}

/**
 * Fetches the double materiality audit logs by its surveyId.
 * @param {surveyId} params - contains the surveyId of which the details are to be fetched.
 * @returns {Object} - an object containing audit log details.
 * @throws {Error} - if unable to fetch the details.
 */
const getDoubleMaterialityAuditLogs = async (surveyId) => {
  const response = await Axios.get(`${CONFIG.AUDIT_LOG_URL}getDoubleMaterialityAuditLogs?surveyId=${surveyId}`, {
    headers: {
      'x-api-key': CONFIG.X_API_KEY,
    },
    mode: 'no-cors'
  })
  let value = [];
  if (response?.data?.data?.length && response?.data?.data[0]['survey-results']?.length) {
    value = response?.data?.data[0]['survey-results'].map((v, i) => {
      return {
        data: () => v,
        id: v.id || i
      }
    })
  }

  return value;
}


export {
    parseSnapShortData,
    getsurveyresultsbysurveyId,
    getworkshopsbysurveyId,
    getfinancialworkshopsbysurveyid,
    getsubmittedSurveyResult,
    getSurveyResultForSubcollection,
    addToMethodologyLogs,
    updateSurveyById,
    getbysurveyid,
    createDoubleMaterialitySurvey,
    updateDoubleMaterialitySurvey,
    setWorkshops,
    updateWorkshops,
    setFinancialWorkshops,
    updateFinancialWorkshops,
    getSurveyResultById,
    setSurveyResult,
    updateSurveyResultData,
    addToAuditLogs,
    addToSurveyResults,
};
handleSubmitReasonForMaxOrAverage = e => {
    const { surveyId, currentSurveyId, consultantId, reasonForMaxOrAverage } = this.state;
    this.setState({ loading: true });
    this.setState({ maxOrAverageSelectionWarningModal: false });

    const body = {
      reasonForMaxOrAverage: reasonForMaxOrAverage
    }

    updateConsultantsOrSurveyProperty({
      surveyId,
      consultantId,
      property: "reasonForMaxOrAverage"
    }, body).then((res) => {
      console.log("updated the reason for max and average", res)
      this.setState({ loading: false });
    }).catch((err) => {
      console.log("error while updating", err)
      this.setState({ loading: false });
    })

    // const surveysRef = firebase
    //   .firestore()
    //   .collection(this.state.consultantId ? 'portfolio-surveys-consultants' : 'surveys');

    // surveysRef
    //   .doc(this.state.surveyId ? this.state.surveyId : this.state.currentSurveyId)
    //   .update({
    //     reasonForMaxOrAverage: this.state.reasonForMaxOrAverage,
    //   })
    //   .then(() => {
    //     this.setState({ loading: false });
    //   })
    //   .catch(error => {
    //     console.log('error updating parent topics');
    //   });
  };

  handleSaveBooleanValue = (type, value) => {
    console.log("handleSaveBooleanValue", type, value)
    this.setState({ [type]: value });

    const payload = {
      [type]: value,
    }

    updateConsultantsOrSurveyProperty(
      {
        surveyId: this.state.surveyId,
        consultantId: this.state.consultantId,
        property: type,
      },
      payload,
    ).then(() => { })
      .catch(error => {
        console.log('error updating');
      });

    // const surveysRef = firebase
    //   .firestore()
    //   .collection(this.state.consultantId ? 'portfolio-surveys-consultants' : 'surveys');

    // surveysRef
    //   .doc(this.state.surveyId ? this.state.surveyId : this.state.currentSurveyId)
    //   .update({
    //     [type]: value,
    //   })
    //   .then(() => { })
    //   .catch(error => {
    //     console.log('error updating');
    //   });
  };
  handleChangeScoringSetting = newScoringSetting => {
    const { surveyId, currentSurveyId, consultantId, scoringSetting } = this.state;

    // const matrixWorkshopsRef = firebase
    //   .firestore()
    //   .collection(consultantId ? 'portfolio-surveys-consultants' : 'surveys')
    //   .doc(surveyId ? surveyId : currentSurveyId);

    if (scoringSetting !== newScoringSetting) {
      this.setState({
        scoringSetting: newScoringSetting,
      });

      const body = {
        scoringSettings: newScoringSetting,
      };

      updateConsultantsOrSurveyProperty({
        surveyId,
        consultantId,
        property: "scoringSettings"
      }, body).then((res) => {
        console.log(`Updated scoring setting`, res);
      }).catch((err) => {
        console.log("Error updating scoring setting", err)
      })

      // matrixWorkshopsRef
      //   .update({
      //     scoringSetting: newScoringSetting,
      //   })
      //   .then(() => {
      //     console.log(`Updated scoring setting`);
      //   })
      //   .catch(error => {
      //     console.log('Updated scoring setting');
      //   });
    }
  };
#elevated command prompt, all accounts
wmic UserAccount set PasswordExpires=False

#elevated command prompt, particular accounts
wmic UserAccount where Name="user name" set PasswordExpires=False
#Substitute user name in the command above with the actual user name of the local account.
 appendImportedData_Impact = async book => {
    console.log("appendImportedData_Impact function called")
    try {
      const _selectedAnsweredEntry = this.state.selectedworkshop.answeredEntries;

      if (!_selectedAnsweredEntry) {
        this.state.selectedworkshop.answeredEntries = [];
        this.setState({
          selectedworkshop: { ...this.state.selectedworkshop, answeredEntries: [] },
        });
      }

      const selectedAnsweredEntry = this.state.selectedworkshop.answeredEntries;

      let _worksheet = this.state.selectedworkshop.worksheet
        .filter((item, index, self) => index === self.findIndex(t => t.id === item.id))
        .sort((a, b) => {
          if (a.framework == 'CSRD') {
            let _a =
              CSRDAllTopics?.find(
                item2 => item2['mainId'] == a['mainId'] && item2['topic'] == a['topic'],
              )?.sortIndex || 0;
            let _b =
              CSRDAllTopics?.find(
                item2 => item2['mainId'] == b['mainId'] && item2['topic'] == b['topic'],
              )?.sortIndex || 0;

            return _a < _b ? -1 : _a > _b ? 1 : 0;
          }

          if (a.framework == 'GRI') {
            let _a = a.id;
            let _b = b.id;

            return _a < _b ? -1 : _a > _b ? 1 : 0;
          }

          if (a.topic < b.topic) return -1;
          if (a.topic > b.topic) return 1;
        })
        .sort((a, b) => {
          if (this.renderESG(a.dimension) == 'Environmental') return -1;
          if (this.renderESG(b.dimension) == 'Environmental') return 1;
          if (this.renderESG(a.dimension) == 'Social') return -1;
          if (this.renderESG(b.dimension) == 'Social') return 1;
          if (this.renderESG(a.dimension) == 'Governance') return -1;
          if (this.renderESG(b.dimension) == 'Governance') return 1;

          if (this.renderESG(a.dimension) < this.renderESG(b.dimension)) return -1;
          if (this.renderESG(a.dimension) > this.renderESG(b.dimension)) return 1;
        })
        .sort((a, b) => {
          if (this.renderESG(a.dimension) == 'Environmental') return -1;
          if (this.renderESG(b.dimension) == 'Environmental') return 1;
          if (this.renderESG(a.dimension) == 'Social') return -1;
          if (this.renderESG(b.dimension) == 'Social') return 1;
          if (this.renderESG(a.dimension) == 'Governance') return -1;
          if (this.renderESG(b.dimension) == 'Governance') return 1;

          if (this.renderESG(a.dimension) < this.renderESG(b.dimension)) return -1;
          if (this.renderESG(a.dimension) > this.renderESG(b.dimension)) return 1;
        })
        .filter((item, index) => {
          return item.entryType !== 'comment' && item.entryType !== 'added-entry';
        });

      let allAnsweredEntries = [];
      _worksheet.forEach(item => {
        const answerData = this.state.answeredTopics.find(data => data.id === item.id);
        let answer = '';
        if (answerData) {
          answer = answerData;
        }

        const topicResult = this.state.surveyResultsIROComments.filter(
          item2 => item2.id == item.id,
        );

        let allComments = this.getAllCommentsFromShortSurvey_Impact(
          topicResult,
          Array.from(this.state.financialConsolidatedReports || []),
          Array.from(this.state.addedCommentTopics || []),
        );

        if (allComments.length > 0) {
          allComments
            .filter((v, i, a) => a.findIndex(t => t.id === v.id) === i)
            .filter(item => (item.assessmentType ? item.assessmentType == 'Impact' : item))
            .forEach((commData, commIndex) => {
              let item = commData;

              const workshopWithEntry = Array.from(this.state.workshops || [])
                .concat(Array.from(this.state.financialworkshops || []))
                .find(ws => {
                  return Array.from(ws.worksheet || []).find(data => data.id === commData.id);
                });

              if (workshopWithEntry) {
                const prevItem = Array.from(workshopWithEntry.worksheet || []).find(
                  data => data.id === commData.id,
                );

                if (prevItem) {
                  item = prevItem;
                }
              }

              const answerData = this.state.answeredTopics.find(data => data.id === item.id);
              let answer = '';
              if (answerData) {
                answer = answerData;
              }

              const entryId = `${this.state.surveyId}__${this.state.selectedworkshop.id}__${item.id}`;
              let entry = {
                topic: item.topic,
                id: entryId,
                surveyId: this.state.surveyId,
                workshopId: this.state.selectedworkshop.id,
                oldid: item.id,
              };

              if (
                item?.entryType == 'comment' &&
                (!answer?.['Verification'] ||
                  answer?.['Verification']?.value == 'No' ||
                  answer?.['Verification']?.value == '')
              ) {
                return null;
              }

              allAnsweredEntries.push(entry);
            });
        }
      });

      if (book && book.SheetNames) {
        book.SheetNames.forEach((parentitem, parentindex) => {
          const data = xlsx2.utils.sheet_to_json(book.Sheets[parentitem]);

          data.forEach(item => {
            const itemFind = selectedAnsweredEntry?.find(item2 => item2.topic == item['Topic']);

            if (item?.['Comment or Added Entry'] == 'Yes') {
              if (itemFind) {
                if (parentindex == 0) {
                  itemFind[`Consolidated Level`] = item[`Consolidated Level`] || '';

                  if (item[`Entity-Specific`]) {
                    itemFind[`Entity-Specific`] =
                      item[`Entity-Specific`]
                        ?.split(', ')
                        ?.map(item2 => ({ value: item2, label: item2 })) || null;
                  }
                  if (item[`Country-Specific`]) {
                    itemFind[`Country-Specific`] =
                      item[`Country-Specific`]
                        ?.split(', ')
                        ?.map(item2 => ({ value: item2, label: item2 })) || null;
                  }
                  if (item[`Sector-Specific`]) {
                    itemFind[`Sector-Specific`] =
                      item[`Sector-Specific`]
                        ?.split(', ')
                        ?.map(item2 => ({ value: item2, label: item2 })) || null;
                  }
                } else if (parentindex == 1) {
                  if (item[`Stakeholder Type`]) {
                    itemFind[`Stakeholder Type`] =
                      item[`Stakeholder Type`]
                        ?.split(', ')
                        ?.map(item2 => ({ value: item2, label: item2 })) || null;
                  }
                  if (item[`Location in the Value Chain`]) {
                    itemFind[`Location in the Value Chain`] =
                      item[`Location in the Value Chain`]
                        ?.split(', ')
                        ?.map(item2 => ({ value: item2, label: item2 })) || null;
                  }
                } else if (parentindex == 2) {
                  itemFind[`Type of Impact`] = item[`Type of Impact`] || '';
                  itemFind[`Actual or Potential`] = item[`Actual or Potential`] || '';
                  itemFind[`Timeframe`] = item[`Timeframe`] || '';
                  itemFind[`People or Environmental`] = item[`People or Environmental`] || '';
                  itemFind[`Likelihood`] = item[`Likelihood`] || '';
                  itemFind[`Remediability`] = item[`Remediability`] || '';
                  itemFind[`Scale`] = item[`Scale`] || '';
                  itemFind[`Scope`] = item[`Scope`] || '';
                  itemFind[`Scoring Comments`] = item[`Comments`] || '';
                  itemFind[`Scoring Task Description`] = item[`Task Description`] || '';
                } else if (parentindex == 3) {
                  itemFind[`VAR - Maximum Value at Risk`] = item[`Maximum Value at Risk`] || '';
                  itemFind[`VAR - Revenue`] = item[`Revenue`] || '';
                  itemFind[`VAR - Expenditure`] = item[`Expenditure`] || '';
                  itemFind[`VAR - Assets`] = item[`Assets`] || '';
                  itemFind[`VAR - Liabilities`] = item[`Liabilities`] || '';
                  itemFind[`VAR - Capital`] = item[`Capital`] || '';
                  itemFind[`VAR - Financing`] = item[`Financing`] || '';
                  itemFind[`VAR Task Description`] = item[`Task Description`] || '';
                }
              } else {
                let itemFind = {};
                let answeredEntryFind = allAnsweredEntries.find(
                  item2 => item2['topic'] == item['Topic'],
                );
                if (answeredEntryFind) {
                  itemFind = {
                    ...itemFind,
                    ...answeredEntryFind,
                  };
                }

                if (parentindex == 0) {
                  itemFind[`Consolidated Level`] = item[`Consolidated Level`] || '';

                  if (item[`Entity-Specific`]) {
                    itemFind[`Entity-Specific`] =
                      item[`Entity-Specific`]
                        ?.split(', ')
                        ?.map(item2 => ({ value: item2, label: item2 })) || null;
                  }
                  if (item[`Country-Specific`]) {
                    itemFind[`Country-Specific`] =
                      item[`Country-Specific`]
                        ?.split(', ')
                        ?.map(item2 => ({ value: item2, label: item2 })) || null;
                  }
                  if (item[`Sector-Specific`]) {
                    itemFind[`Sector-Specific`] =
                      item[`Sector-Specific`]
                        ?.split(', ')
                        ?.map(item2 => ({ value: item2, label: item2 })) || null;
                  }
                } else if (parentindex == 1) {
                  if (item[`Stakeholder Type`]) {
                    itemFind[`Stakeholder Type`] =
                      item[`Stakeholder Type`]
                        ?.split(', ')
                        ?.map(item2 => ({ value: item2, label: item2 })) || null;
                  }
                  if (item[`Location in the Value Chain`]) {
                    itemFind[`Location in the Value Chain`] =
                      item[`Location in the Value Chain`]
                        ?.split(', ')
                        ?.map(item2 => ({ value: item2, label: item2 })) || null;
                  }
                } else if (parentindex == 2) {
                  itemFind[`Type of Impact`] = item[`Type of Impact`] || '';
                  itemFind[`Actual or Potential`] = item[`Actual or Potential`] || '';
                  itemFind[`Timeframe`] = item[`Timeframe`] || '';
                  itemFind[`People or Environmental`] = item[`People or Environmental`] || '';
                  itemFind[`Likelihood`] = item[`Likelihood`] || '';
                  itemFind[`Remediability`] = item[`Remediability`] || '';
                  itemFind[`Scale`] = item[`Scale`] || '';
                  itemFind[`Scope`] = item[`Scope`] || '';
                  itemFind[`Scoring Comments`] = item[`Comments`] || '';
                  itemFind[`Scoring Task Description`] = item[`Task Description`] || '';
                } else if (parentindex == 3) {
                  itemFind[`VAR - Maximum Value at Risk`] = item[`Maximum Value at Risk`] || '';
                  itemFind[`VAR - Revenue`] = item[`Revenue`] || '';
                  itemFind[`VAR - Expenditure`] = item[`Expenditure`] || '';
                  itemFind[`VAR - Assets`] = item[`Assets`] || '';
                  itemFind[`VAR - Liabilities`] = item[`Liabilities`] || '';
                  itemFind[`VAR - Capital`] = item[`Capital`] || '';
                  itemFind[`VAR - Financing`] = item[`Financing`] || '';
                  itemFind[`VAR Task Description`] = item[`Task Description`] || '';
                }

                selectedAnsweredEntry.push(itemFind);
              }
            }
          });
        });
      }

      const { surveyId, currentSurveyId, consultantId, selectedworkshop } = this.state;
      // const matrixWorkshopsRef = firebase
      //   .firestore()
      //   .collection(consultantId ? 'portfolio-surveys-consultants' : 'surveys')
      //   .doc(surveyId ? surveyId : currentSurveyId)
      //   .collection('workshops')
      //   .doc(selectedworkshop.id);

      const updatedWorkshop = {
        ...selectedworkshop,
        answeredEntries: [...selectedworkshop.answeredEntries, ...selectedAnsweredEntry].filter(
          (item, index, self) => index === self.findIndex(t => t.id === item.id),
        ),
      };

      console.log('updatedWorkshop', updatedWorkshop);

      this.setState({
        selectedworkshop: updatedWorkshop,
        loading: false,
      });

      const payload = [...selectedworkshop.answeredEntries, ...selectedAnsweredEntry].filter(
        (item, index, self) => index === self.findIndex(t => t.id === item.id),
      )


      updateWorkshopProperty({
        surveyId,
        consultantId,
        workshopId: selectedworkshop.id,
        type: "impact",
        property: "answeredEntries"
      }, payload).then((res) => {
        console.log("submitted to api", res)
      }).catch(error => {
        console.log('error saving answered entries');
      });

      // matrixWorkshopsRef
      //   .update({
      //     answeredEntries: [...selectedworkshop.answeredEntries, ...selectedAnsweredEntry].filter(
      //       (item, index, self) => index === self.findIndex(t => t.id === item.id),
      //     ),
      //   })
      //   .then(() => {
      //     console.log(`saved answered entries`);
      //   })
      //   .catch(error => {
      //     console.log('error saving answered entries');
      //   });

      // Reset the input
      const fileinput = document.getElementById('file-input-topics');

      if (fileinput) {
        fileinput.value = null;
      }
    } catch (ex) {
      console.log(ex.message);
      this.setState({ loading: false });

      // Reset the input
      const fileinput = document.getElementById('file-input-topics');

      if (fileinput) {
        fileinput.value = null;
      }
      return;
    }
  };
appendImportedData_Financial = async book => {
    try {
      const _selectedAnsweredEntry = this.state.selectedfinancialworkshop.answeredEntries;

      if (!_selectedAnsweredEntry) {
        this.state.selectedfinancialworkshop.answeredEntries = [];
        this.setState({
          selectedfinancialworkshop: {
            ...this.state.selectedfinancialworkshop,
            answeredEntries: [],
          },
        });
      }

      const selectedAnsweredEntry = this.state.selectedfinancialworkshop.answeredEntries;

      let _worksheet = this.state.selectedfinancialworkshop.worksheet
        .sort((a, b) => {
          if (a.framework == 'CSRD') {
            let _a =
              CSRDAllTopics?.find(
                item2 => item2['mainId'] == a['mainId'] && item2['topic'] == a['topic'],
              )?.sortIndex || 0;
            let _b =
              CSRDAllTopics?.find(
                item2 => item2['mainId'] == b['mainId'] && item2['topic'] == b['topic'],
              )?.sortIndex || 0;

            return _a < _b ? -1 : _a > _b ? 1 : 0;
          }

          if (a.framework == 'GRI') {
            let _a = a.id;
            let _b = b.id;

            return _a < _b ? -1 : _a > _b ? 1 : 0;
          }

          if (a.topic < b.topic) return -1;
          if (a.topic > b.topic) return 1;
        })
        .sort((a, b) => {
          if (this.renderESG(a.dimension) == 'Environmental') return -1;
          if (this.renderESG(b.dimension) == 'Environmental') return 1;
          if (this.renderESG(a.dimension) == 'Social') return -1;
          if (this.renderESG(b.dimension) == 'Social') return 1;
          if (this.renderESG(a.dimension) == 'Governance') return -1;
          if (this.renderESG(b.dimension) == 'Governance') return 1;

          if (this.renderESG(a.dimension) < this.renderESG(b.dimension)) return -1;
          if (this.renderESG(a.dimension) > this.renderESG(b.dimension)) return 1;
        })
        .sort((a, b) => {
          if (this.renderESG(a.dimension) == 'Environmental') return -1;
          if (this.renderESG(b.dimension) == 'Environmental') return 1;
          if (this.renderESG(a.dimension) == 'Social') return -1;
          if (this.renderESG(b.dimension) == 'Social') return 1;
          if (this.renderESG(a.dimension) == 'Governance') return -1;
          if (this.renderESG(b.dimension) == 'Governance') return 1;

          if (this.renderESG(a.dimension) < this.renderESG(b.dimension)) return -1;
          if (this.renderESG(a.dimension) > this.renderESG(b.dimension)) return 1;
        })
        .filter((item, index) => {
          return item.entryType !== 'comment' && item.entryType !== 'added-entry';
        });

      let allAnsweredEntries = [];
      _worksheet.forEach(item => {
        let verifiedTopic = '';
        if (item.value) {
          if (Array.isArray(item.value)) {
            verifiedTopic = item.value.map(item => item.label).join(', ');
          } else {
            verifiedTopic = item.value;
          }
        }

        const answerData = this.state.answeredTopics.find(data => data.id === item.id);
        let answer = '';
        if (answerData) {
          answer = answerData;
        }

        const riskValue = answer['Risk']?.value || '';
        const oppValue = answer['Opportunities']?.value || '';

        let riskValueColor = '#fff';
        let oppValueColor = '#fff';

        if (riskValue === 'Yes') {
          riskValueColor = '#D1060A';
        } else if (riskValue === 'No') {
          riskValueColor = '#2EB917';
        }

        if (oppValue === 'Yes') {
          oppValueColor = '#2EB917';
        }

        const topicResult = this.state.surveyResultsIROComments.filter(
          item2 => item2.id == item.id,
        );

        let allComments = this.getAllCommentsFromShortSurvey_Financial(
          topicResult,
          Array.from(this.state.financialConsolidatedReports || []),
          Array.from(this.state.addedCommentTopics || []),
        );

        if (allComments.length > 0) {
          allComments
            .filter((v, i, a) => a.findIndex(t => t.id === v.id) === i)
            .filter(item => (item.assessmentType ? item.assessmentType == 'Financial' : item))
            .forEach((commData, commIndex) => {
              let addedEntryTopicName = '';
              let item = commData;

              const workshopWithEntry = Array.from(this.state.workshops || [])
                .concat(Array.from(this.state.financialworkshops || []))
                .find(ws => {
                  return Array.from(ws.worksheet || []).find(data => data.id === commData.id);
                });

              if (workshopWithEntry) {
                const prevItem2 = Array.from(workshopWithEntry.worksheet || []).find(
                  data => data.id === commData.id,
                );

                if (prevItem2) {
                  addedEntryTopicName = prevItem2;
                }
              }

              const prevItem = Array.from(
                this.state.selectedfinancialworkshop.worksheet || [],
              ).find(data => data.id === commData.id);

              if (prevItem) {
                item = prevItem;
              }

              let verifiedTopic = '';
              if (item.value) {
                if (Array.isArray(item.value)) {
                  verifiedTopic = item.value.map(item => item.label).join(', ');
                } else {
                  verifiedTopic = item.value;
                }
              }

              const answerData = this.state.answeredTopics.find(data => data.id === item.id);
              let answer = '';
              if (answerData) {
                answer = answerData;
              }

              const entryId = `${this.state.surveyId}__${this.state.selectedfinancialworkshop.id}__${item.id}`;
              let entry = {
                topic: item.topic,
                id: entryId,
                surveyId: this.state.surveyId,
                workshopId: this.state.selectedfinancialworkshop.id,
                oldid: item.id,
              };
              const answeredEntryData = this.state.selectedfinancialworkshop?.answeredEntries?.find(
                entry => entry.id === entryId,
              );

              if (answeredEntryData) {
                entry = {
                  ...entry,
                  ...answeredEntryData,
                };
              }

              if (
                item?.entryType == 'comment' &&
                (!answer?.['Verification'] ||
                  answer?.['Verification']?.value == 'No' ||
                  answer?.['Verification']?.value == '')
              ) {
                return null;
              }

              allAnsweredEntries.push(entry);
            });
        }
      });

      if (book && book.SheetNames) {
        book.SheetNames.forEach((parentitem, parentindex) => {
          const data = xlsx2.utils.sheet_to_json(book.Sheets[parentitem]);

          data.forEach(item => {
            const itemFind = selectedAnsweredEntry?.find(item2 => item2.topic == item['Topic']);

            if (item?.['Comment or Added Entry'] == 'Yes') {
              if (itemFind) {
                if (parentindex == 0) {
                  itemFind[`Type of Impact`] = item[`Type of Impact`] || '';
                  itemFind[`Consolidated Level`] = item[`Consolidated Level`] || '';

                  if (item[`Entity-Specific`]) {
                    itemFind[`Entity-Specific`] =
                      item[`Entity-Specific`]
                        ?.split(', ')
                        ?.map(item2 => ({ value: item2, label: item2 })) || null;
                  }
                  if (item[`Country-Specific`]) {
                    itemFind[`Country-Specific`] =
                      item[`Country-Specific`]
                        ?.split(', ')
                        ?.map(item2 => ({ value: item2, label: item2 })) || null;
                  }
                  if (item[`Sector-Specific`]) {
                    itemFind[`Sector-Specific`] =
                      item[`Sector-Specific`]
                        ?.split(', ')
                        ?.map(item2 => ({ value: item2, label: item2 })) || null;
                  }
                } else if (parentindex == 1) {
                  if (item[`Stakeholder Type`]) {
                    itemFind[`Stakeholder Type`] =
                      item[`Stakeholder Type`]
                        ?.split(', ')
                        ?.map(item2 => ({ value: item2, label: item2 })) || null;
                  }
                  if (item[`Location in the Value Chain`]) {
                    itemFind[`Location in the Value Chain`] =
                      item[`Location in the Value Chain`]
                        ?.split(', ')
                        ?.map(item2 => ({ value: item2, label: item2 })) || null;
                  }
                  if (item[`Significant Assets`]) {
                    itemFind[`Significant Assets`] =
                      item[`Significant Assets`]
                        ?.split(', ')
                        ?.map(item2 => ({ value: item2, label: item2 })) || null;
                  }
                  itemFind[`Significant Locations`] = item[`Significant Locations`] || '';
                } else if (parentindex == 2) {
                  itemFind[`Type of Impact`] = item[`Type of Impact`] || '';
                  itemFind[`Actual or Potential`] = item[`Actual or Potential`] || '';
                  itemFind[`Timeframe`] = item[`Timeframe`] || '';
                  itemFind[`Likelihood`] = item[`Likelihood`] || '';
                  itemFind[`Magnitude`] = item[`Magnitude`] || '';
                  itemFind[`Scoring Comments`] = item[`Comments`] || '';
                  itemFind[`Scoring Task Description`] = item[`Task Description`] || '';
                } else if (parentindex == 3) {
                  itemFind[`VAR - Maximum Value at Risk`] = item[`Maximum Value at Risk`] || '';
                  itemFind[`VAR - Opportunity Value`] = item[`Opportunity Value`] || '';
                  itemFind[`VAR - Revenue`] = item[`Revenue`] || '';
                  itemFind[`VAR - Expenditure`] = item[`Expenditure`] || '';
                  itemFind[`VAR - Assets`] = item[`Assets`] || '';
                  itemFind[`VAR - Liabilities`] = item[`Liabilities`] || '';
                  itemFind[`VAR - Capital`] = item[`Capital`] || '';
                  itemFind[`VAR - Financing`] = item[`Financing`] || '';
                  itemFind[`VAR Task Description`] = item[`Task Description`] || '';
                }
              } else {
                let itemFind = {};
                let answeredEntryFind = allAnsweredEntries.find(
                  item2 => item2['topic'] == item['Topic'],
                );
                if (answeredEntryFind) {
                  itemFind = {
                    ...itemFind,
                    ...answeredEntryFind,
                  };
                }

                if (parentindex == 0) {
                  itemFind[`Type of Impact`] = item[`Type of Impact`] || '';
                  itemFind[`Consolidated Level`] = item[`Consolidated Level`] || '';

                  if (item[`Entity-Specific`]) {
                    itemFind[`Entity-Specific`] =
                      item[`Entity-Specific`]
                        ?.split(', ')
                        ?.map(item2 => ({ value: item2, label: item2 })) || null;
                  }
                  if (item[`Country-Specific`]) {
                    itemFind[`Country-Specific`] =
                      item[`Country-Specific`]
                        ?.split(', ')
                        ?.map(item2 => ({ value: item2, label: item2 })) || null;
                  }
                  if (item[`Sector-Specific`]) {
                    itemFind[`Sector-Specific`] =
                      item[`Sector-Specific`]
                        ?.split(', ')
                        ?.map(item2 => ({ value: item2, label: item2 })) || null;
                  }
                } else if (parentindex == 1) {
                  if (item[`Stakeholder Type`]) {
                    itemFind[`Stakeholder Type`] =
                      item[`Stakeholder Type`]
                        ?.split(', ')
                        ?.map(item2 => ({ value: item2, label: item2 })) || null;
                  }
                  if (item[`Location in the Value Chain`]) {
                    itemFind[`Location in the Value Chain`] =
                      item[`Location in the Value Chain`]
                        ?.split(', ')
                        ?.map(item2 => ({ value: item2, label: item2 })) || null;
                  }
                  if (item[`Significant Assets`]) {
                    itemFind[`Significant Assets`] =
                      item[`Significant Assets`]
                        ?.split(', ')
                        ?.map(item2 => ({ value: item2, label: item2 })) || null;
                  }
                  itemFind[`Significant Locations`] = item[`Significant Locations`] || '';
                } else if (parentindex == 2) {
                  itemFind[`Type of Impact`] = item[`Type of Impact`] || '';
                  itemFind[`Actual or Potential`] = item[`Actual or Potential`] || '';
                  itemFind[`Timeframe`] = item[`Timeframe`] || '';
                  itemFind[`Likelihood`] = item[`Likelihood`] || '';
                  itemFind[`Magnitude`] = item[`Magnitude`] || '';
                  itemFind[`Scoring Comments`] = item[`Comments`] || '';
                  itemFind[`Scoring Task Description`] = item[`Task Description`] || '';
                } else if (parentindex == 3) {
                  itemFind[`VAR - Maximum Value at Risk`] = item[`Maximum Value at Risk`] || '';
                  itemFind[`VAR - Opportunity Value`] = item[`Opportunity Value`] || '';
                  itemFind[`VAR - Revenue`] = item[`Revenue`] || '';
                  itemFind[`VAR - Expenditure`] = item[`Expenditure`] || '';
                  itemFind[`VAR - Assets`] = item[`Assets`] || '';
                  itemFind[`VAR - Liabilities`] = item[`Liabilities`] || '';
                  itemFind[`VAR - Capital`] = item[`Capital`] || '';
                  itemFind[`VAR - Financing`] = item[`Financing`] || '';
                  itemFind[`VAR Task Description`] = item[`Task Description`] || '';
                }

                selectedAnsweredEntry.push(itemFind);
              }
            }
          });
        });
      }

      const { surveyId, currentSurveyId, consultantId, selectedfinancialworkshop } = this.state;
      // const matrixWorkshopsRef = firebase
      //   .firestore()
      //   .collection(consultantId ? 'portfolio-surveys-consultants' : 'surveys')
      //   .doc(surveyId ? surveyId : currentSurveyId)
      //   .collection('financial-workshops')
      //   .doc(selectedfinancialworkshop.id);

      const updatedWorkshop = {
        ...selectedfinancialworkshop,
        answeredEntries: [
          ...selectedfinancialworkshop.answeredEntries,
          ...selectedAnsweredEntry,
        ].filter((item, index, self) => index === self.findIndex(t => t.id === item.id)),
      };

      this.setState({
        selectedfinancialworkshop: updatedWorkshop,
        loading: false,
      });

      const payload = [
        ...selectedfinancialworkshop.answeredEntries,
        ...selectedAnsweredEntry,
      ].filter((item, index, self) => index === self.findIndex(t => t.id === item.id));

      updateWorkshopProperty({
        surveyId,
        consultantId,
        workshopId: selectedfinancialworkshop.id,
        type: "financial",
        property: "answeredEntries"
      }, payload).then((res) => {
        console.log("submitted to api", res)
      }).catch(error => {
        console.log('error saving answered entries');
      });

      // matrixWorkshopsRef
      //   .update({
      //     answeredEntries: [
      //       ...selectedfinancialworkshop.answeredEntries,
      //       ...selectedAnsweredEntry,
      //     ].filter((item, index, self) => index === self.findIndex(t => t.id === item.id)),
      //   })
      //   .then(() => {
      //     console.log(`saved answered entries`);
      //   })
      //   .catch(error => {
      //     console.log('error saving answered entries');
      //   });

      // Reset the input
      const fileinput = document.getElementById('file-input-topics');

      if (fileinput) {
        fileinput.value = null;
      }
    } catch (ex) {
      console.log(ex.message);
      this.setState({ loading: false });

      // Reset the input
      const fileinput = document.getElementById('file-input-topics');

      if (fileinput) {
        fileinput.value = null;
      }
      return;
    }
  };
saveFinancialWorkshopAnswerEntry = () => {
    const { surveyId, currentSurveyId, consultantId, selectedfinancialworkshop } = this.state;
    // const matrixWorkshopsRef = firebase
    //   .firestore()
    //   .collection(consultantId ? 'portfolio-surveys-consultants' : 'surveys')
    //   .doc(surveyId ? surveyId : currentSurveyId)
    //   .collection('financial-workshops')
    //   .doc(selectedfinancialworkshop.id);

    const updatedWorkshop = {
      ...selectedfinancialworkshop,
      answeredEntries: [...selectedfinancialworkshop.answeredEntries],
    };

    const newWorkshops = Array.from(this.state.financialworkshops || []);
    const workshopIndex = newWorkshops.findIndex(item => item.id === updatedWorkshop.id);

    if (workshopIndex > -1) {
      newWorkshops[workshopIndex] = updatedWorkshop;

      this.setState({
        financialworkshops: newWorkshops,
        selectedfinancialworkshop: updatedWorkshop,
      });
    } else {
      this.setState({
        selectedfinancialworkshop: updatedWorkshop,
      });
    }

    saveToWorkshopAnswerEntry({
      surveyId,
      consultantId,
      workshopId: selectedfinancialworkshop.id,
      type: "financial",
    }, [...selectedfinancialworkshop.answeredEntries]).then((res) => {
      console.log("added to workshop entry", res)
    }).catch(error => {
      console.log('error saving entry');
    });

    // matrixWorkshopsRef
    //   .update({
    //     answeredEntries: [...selectedfinancialworkshop.answeredEntries],
    //   })
    //   .then(() => {
    //     console.log(`saved entry`);
    //   })
    //   .catch(error => {
    //     console.log('error saving entry');
    //   });
  };
handleFinancialWorkshopAnswerEntryChange = (e, item, key) => {
    const { selectedfinancialworkshop } = this.state;
    const itemFind = selectedfinancialworkshop?.answeredEntries?.find(
      item2 => item['id'] == item2['id'],
    );

    if (itemFind) {
      if (key) {
        itemFind[key] = e;

        this.setState({
          selectedfinancialworkshop: {
            ...selectedfinancialworkshop,
            answeredEntries: [...selectedfinancialworkshop.answeredEntries],
          },
        });

        return;
      }

      if (e.target.name == 'Consolidated Level') {
        if (e.target.value == 'Yes') {
          itemFind['Entity-Specific'] = null;
          itemFind['Country-Specific'] = null;
          itemFind['Sector-Specific'] = null;
        }
      }

      itemFind[e.target.name] = e.target.value;

      this.setState({
        selectedfinancialworkshop: {
          ...selectedfinancialworkshop,
          answeredEntries: [...selectedfinancialworkshop.answeredEntries],
        },
      });
    } else {
      const itemFind = {
        ...item,
      };
      let newAnsweredEntries = [];

      if (selectedfinancialworkshop.answeredEntries) {
        newAnsweredEntries = [...selectedfinancialworkshop.answeredEntries];
      }

      if (key) {
        itemFind[key] = e;

        newAnsweredEntries.push(itemFind);
        selectedfinancialworkshop.answeredEntries = newAnsweredEntries;

        this.setState({
          selectedfinancialworkshop: {
            ...selectedfinancialworkshop,
            answeredEntries: [...newAnsweredEntries],
          },
        });

        return;
      }

      if (e.target.name == 'Consolidated Level') {
        if (e.target.value == 'Yes') {
          itemFind['Entity-Specific'] = null;
          itemFind['Country-Specific'] = null;
          itemFind['Sector-Specific'] = null;
        }
      }

      itemFind[e.target.name] = e.target.value;

      newAnsweredEntries.push(itemFind);
      selectedfinancialworkshop.answeredEntries = newAnsweredEntries;

      this.setState({
        selectedfinancialworkshop: {
          ...selectedfinancialworkshop,
          answeredEntries: [...newAnsweredEntries],
        },
      });
    }
  };
 saveWorkshopAnswerEntry = () => {
    const { surveyId, currentSurveyId, consultantId, selectedworkshop } = this.state;

    console.log("selectedworkshop in saveWorkshopAnswerEntry", selectedworkshop)
    // const matrixWorkshopsRef = firebase
    //   .firestore()
    //   .collection(consultantId ? 'portfolio-surveys-consultants' : 'surveys')
    //   .doc(surveyId ? surveyId : currentSurveyId)
    //   .collection('workshops')
    //   .doc(selectedworkshop.id);

    const updatedWorkshop = {
      ...selectedworkshop,
      answeredEntries: [...selectedworkshop.answeredEntries],
    };

    const newWorkshops = Array.from(this.state.workshops || []);
    const workshopIndex = newWorkshops.findIndex(item => item.id === updatedWorkshop.id);

    if (workshopIndex > -1) {
      newWorkshops[workshopIndex] = updatedWorkshop;

      this.setState({
        workshops: newWorkshops,
        selectedworkshop: updatedWorkshop,
      });
    } else {
      this.setState({
        selectedworkshop: updatedWorkshop,
      });
    }

    saveToWorkshopAnswerEntry({
      surveyId,
      consultantId,
      workshopId: selectedworkshop.id,
      type: "impact",
    }, [...selectedworkshop.answeredEntries]).then((res) => {
      console.log("added to workshop entry", res)
    }).catch(error => {
      console.log('error saving entry');
    });

    // Create POST api to answeredEntries in Porfolio-survey-consultatnts/survey Models or WorkshopsModel?
    // matrixWorkshopsRef
    //   .update({
    //     answeredEntries: [...selectedworkshop.answeredEntries],
    //   })
    //   .then(() => {
    //     console.log(`saved entry`);
    //   })
    //   .catch(error => {
    //     console.log('error saving entry');
    //   });
  };
handleWorkshopWorksheetChange = (e, item, key) => {
    console.log("handleWorkshopWorksheetChange", item, e, key);
    const { selectedworkshop, surveyId, consultantId, answeredTopics } = this.state;
    console.log("selectedworkshop", selectedworkshop);
    const itemFind = selectedworkshop.worksheet.find(item2 =>
      item['id'] ? item['id'] == item2['id'] : item['code'] == item2['code'],
    );

    // console.log('e', e);
    // console.log('item', item);
    // console.log('key', key);
    console.log('itemFind', itemFind);

    if (itemFind) {
      console.log("edit condition entered");
      if (key) {
        itemFind[key] = e;

        this.setState({
          selectedworkshop: { ...selectedworkshop, worksheet: [...selectedworkshop.worksheet] },
        });

        // console.log('item', item);
        // console.log('itemFind', itemFind);
        // console.log('selectedworkshop.worksheet', selectedworkshop.worksheet);

        return;
      }

      if (e.target.name == 'Consolidated Level') {
        if (e.target.value == 'Yes') {
          itemFind['Entity-Specific'] = null;
          itemFind['Country-Specific'] = null;
          itemFind['Sector-Specific'] = null;
        }
      }

      itemFind[e.target.name] = e.target.value;

      this.setState({
        selectedworkshop: { ...selectedworkshop, worksheet: [...selectedworkshop.worksheet] },
      });

      const newAnswered = Array.from(this.state.answeredTopics || []);
      const answerData = newAnswered.find(ans => ans.id === item.id);
      console.log("answerData in edit condition", answerData)
      if (answerData) {
        answerData[e.target.name] = e.target.value;
        console.log('3');
        this.setState({
          answeredTopics: newAnswered,
        });
        const workshopId = selectedworkshop.id;

        editAnsweredTopicComment(
          {
            surveyId,
            consultantId,
            workshopId,
          },
          itemFind,
        )
          .then(response => {
            console.log('Added new comment', response);
          })
          .catch(error => {
            console.log('error adding new row');
          });

        // const matrixWorkshopsRef = firebase
        //   .firestore()
        //   .collection(this.state.consultantId ? 'portfolio-surveys-consultants' : 'surveys')
        //   .doc(this.state.surveyId ? this.state.surveyId : this.state.currentSurveyId);

        // matrixWorkshopsRef
        //   .update({
        //     answeredTopics: newAnswered,
        //   })
        //   .then(() => {
        //     console.log(`Added new row`);
        //   })
        //   .catch(error => {
        //     console.log('error adding new row');
        //   });
      }
    }
    // Add new entry
    else {
      console.log("Add new entry");
      const itemFind = {
        ...item,
      };

      const newWorksheet = [...selectedworkshop.worksheet];

      if (key) {
        itemFind[key] = e;

        newWorksheet.push(itemFind);
        selectedworkshop.worksheet = newWorksheet;

        this.setState({
          selectedworkshop: { ...selectedworkshop, worksheet: [...newWorksheet] },
        });

        return;
      }

      if (e.target.name == 'Consolidated Level') {
        if (e.target.value == 'Yes') {
          itemFind['Entity-Specific'] = null;
          itemFind['Country-Specific'] = null;
          itemFind['Sector-Specific'] = null;
        }
      }

      itemFind[e.target.name] = e.target.value;

      newWorksheet.push(itemFind);
      selectedworkshop.worksheet = newWorksheet;

      this.setState({
        selectedworkshop: { ...selectedworkshop, worksheet: [...newWorksheet] },
      });

      console.log("answeredTopics in state", answeredTopics)
      const newAnswered = Array.from(answeredTopics || []);
      console.log("newAnswered", newAnswered)
      const answerData = newAnswered.find(ans => ans.id === item.id);
      console.log("answerData", answerData)
      console.log("itemFind", itemFind)
      if (answerData) {
        answerData[e.target.name] = e.target.value; doubt
        console.log('5');
        this.setState({
          answeredTopics: newAnswered,
        });

        addAnsweredTopicComment({
          surveyId,
          consultantId,
        }, itemFind)
          .then(response => {
            console.log('Added new comment', response);
          })
          .catch(error => {
            console.log('error adding new row');
          });

        // const matrixWorkshopsRef = firebase
        //   .firestore()
        //   .collection(this.state.consultantId ? 'portfolio-surveys-consultants' : 'surveys')
        //   .doc(this.state.surveyId ? this.state.surveyId : this.state.currentSurveyId);

        // matrixWorkshopsRef
        //   .update({
        //     answeredTopics: newAnswered,
        //   })
        //   .then(() => {
        //     console.log(`Added new row`);
        //   })
        //   .catch(error => {
        //     console.log('error adding new row');
        //   });
      }
    }
  };
confirmdeleteworkshop = async () => {
    const { surveyId, currentSurveyId, consultantId, workshops, workshopdata } = this.state;

    this.setState({
      showdeleteworkshopmodal: false,
      loading: true,
    });

    try {
      // Delete workshop if already present
      if (workshopdata && workshopdata.id) {
        // await firebase
        //   .firestore()
        //   .collection(consultantId ? 'portfolio-surveys-consultants' : 'surveys')
        //   .doc(surveyId ? surveyId : currentSurveyId)
        //   .collection('workshops')
        //   .doc(workshopdata.id)
        //   .delete()
        //   .then(() => {
        //     this.handleAddAuditLog(
        //       'delete',
        //       this.state.assessmentType,
        //       'Assessment',
        //       `${this.state.user.name} deleted the worksheet of ${workshopdata['Name of Person']} (${workshopdata.id})`,
        //       'worksheet',
        //     );
        //   });

        // Delete existing workshop
        const response = await removeWorkshop("workshop", {
          surveyId: surveyId,
          consultantId: consultantId,
          workshopId: workshopdata.id,
        });

        this.handleAddAuditLog(
          'delete',
          this.state.assessmentType,
          'Assessment',
          `${this.state.user.name} deleted the worksheet of ${workshopdata['Name of Person']} (${workshopdata.id})`,
          'worksheet',
        );

        const deleteIndex = workshops.findIndex(item => item.id == workshopdata.id);
        workshops.splice(deleteIndex, 1);
        this.setState({
          loading: false,
          workshopdata: {},
          workshops: [...workshops],
        });
      }
    } catch (ex) {
      console.log(ex.message);
      this.setState({
        loading: false,
        workshopdata: {},
      });
    }
  };
confirmdeletefinancialworkshop = async () => {
    const {
      surveyId,
      currentSurveyId,
      consultantId,
      financialworkshops,
      financialworkshopdata,
    } = this.state;

    this.setState({
      showdeletefinancialworkshopmodal: false,
      loading: true,
    });

    try {
      if (financialworkshopdata && financialworkshopdata.id) {
        // await firebase
        //   .firestore()
        //   .collection(consultantId ? 'portfolio-surveys-consultants' : 'surveys')
        //   .doc(surveyId ? surveyId : currentSurveyId)
        //   .collection('financial-workshops')
        //   .doc(financialworkshopdata.id)
        //   .delete()
        //   .then(() => {
        //     this.handleAddAuditLog('delete', this.state.assessmentType, 'Assessment', `${this.state.user.name} deleted the worksheet of ${financialworkshopdata['Name of Person']} (${financialworkshopdata.id})`, 'worksheet');
        //   })

        const response = await removeWorkshop("financial", {
          surveyId: surveyId,
          consultantId: consultantId,
          workshopId: financialworkshopdata.id
        });

        if (response.status === 200) {
          this.handleAddAuditLog(
            'delete',
            this.state.assessmentType,
            'Assessment',
            `${this.state.user.name} deleted the worksheet of ${financialworkshopdata['Name of Person']} (${financialworkshopdata.id})`,
            'worksheet',
          );

        }


        const deleteIndex = financialworkshops.findIndex(
          item => item.id == financialworkshopdata.id,
        );
        financialworkshops.splice(deleteIndex, 1);
        this.setState({
          loading: false,
          financialworkshopdata: {},
          financialworkshops: [...financialworkshops],
        });
      }
    } catch (ex) {
      console.log(ex.message);
      this.setState({
        loading: false,
        financialworkshopdata: {},
      });
    }
  };
handleSubmitFinancialWorkshop = async e => {
    const {
      financialworkshops,
      financialworkshopdata,
      surveyId,
      currentSurveyId,
      consultantId,
    } = this.state;
    // const matrixFinancialWorkshopsRef = firebase
    //   .firestore()
    //   .collection(consultantId ? 'portfolio-surveys-consultants' : 'surveys')
    //   .doc(surveyId ? surveyId : currentSurveyId)
    //   .collection('financial-workshops');

    e.preventDefault();

    this.setState({
      loading: true,
      financialWorkshopTabIndex: 0,
    });

    const formatDate = (date) => {
      if (!date) return null;
      const d = date.seconds ? new Date(date.seconds * 1000 + date.nanoseconds / 1000000) : new Date(date);
      const month = ('0' + (d.getMonth() + 1)).slice(-2);
      const day = ('0' + d.getDate()).slice(-2);
      const year = d.getFullYear();
      return `${month}/${day}/${year}`;
    };

    try {
      // Edit condition (if id exists)
      if (financialworkshopdata.id) {
        // const docRef = matrixFinancialWorkshopsRef.doc(financialworkshopdata.id);
        // const docSnapshot = await docRef.get();
        // const oldData = docSnapshot.data();

        const workshopData = await getWorkshopById("financial-workshops", {
          surveyId: surveyId,
          consultantId: consultantId,
          id: financialworkshopdata.id,
        });

        const oldData = workshopData.data();
        const _date = financialworkshopdata['Date of Workshop or Interview'];
        const payload = {
          ...financialworkshopdata,
          answeredEntries: financialworkshopdata?.answeredEntries ? financialworkshopdata?.answeredEntries : [],
          ['Date of Workshop or Interview']:
            _date && _date.seconds
              ? new Date(_date.seconds * 1000 + _date.nanoseconds / 1000000)
              : _date,
          date: new Date(),
        };

        // await matrixFinancialWorkshopsRef.doc(financialworkshopdata.id).update(payload)
        // )

        await updateFinancialWorkshops(consultantId, financialworkshopdata.id, payload)

        const changes = [];
        // const oldDateFormatted = formatDate(oldData['Date of Workshop or Interview']);
        // const newDateFormatted = formatDate(financialworkshopdata['Date of Workshop or Interview']);
        const oldDateFormatted = oldData['Date of Workshop or Interview'];
        const newDateFormatted = financialworkshopdata['Date of Workshop or Interview'];

        if (financialworkshopdata['Name of Person'] !== oldData['Name of Person']) {
          changes.push(`Name of Person changed from ${oldData['Name of Person']} to ${financialworkshopdata['Name of Person']}`);
        }
        if (financialworkshopdata['Stakeholder Type'] !== oldData['Stakeholder Type']) {
          changes.push(`Stakeholder Type changed from ${oldData['Stakeholder Type']} to ${financialworkshopdata['Stakeholder Type']}`);
        }
        if (financialworkshopdata['Type'] !== oldData['Type']) {
          changes.push(`Type changed from ${oldData['Type']} to ${financialworkshopdata['Type']}`);
        }


        if (financialworkshopdata['Interviewer Name'] !== oldData['Interviewer Name']) {
          changes.push(`Interviewer Name changed from ${oldData['Interviewer Name']} to ${financialworkshopdata['Interviewer Name']}`);
        }

        if (newDateFormatted !== oldDateFormatted) {
          changes.push(`Date of Workshop or Interview changed from ${oldDateFormatted} to ${newDateFormatted}`);
        }

        if (financialworkshopdata['Comments'] !== oldData['Comments']) {
          const oldcomment = oldData['Comments'] || 'Blank';
          changes.push(`Comments changed from ${oldcomment} to ${financialworkshopdata['Comments']}`);
        }
        if (financialworkshopdata['Recommendations'] !== oldData['Recommendations']) {
          const oldrec = oldData['Recommendations'] || 'Blank';
          changes.push(`Recommendations changed from ${oldrec} to ${financialworkshopdata['Recommendations']}`);
        }

        this.handleAddAuditLog(
          'update',
          this.state.assessmentType,
          'Assessment',
          `${this.state.user.name} Updated worksheet of ${financialworkshopdata['Name of Person']} (${financialworkshopdata.id}) : ${changes} `,
          'worksheet',
        );

        const index = financialworkshops.findIndex(item => item.id == financialworkshopdata.id);

        financialworkshops[index] = payload;
        this.setState({
          loading: false,
          financialworkshopdata: {},
          financialworkshops: [...financialworkshops],
          selectedfinancialworkshop: payload,
          showfinancialworkshopmodal: false,
        });

        return;

      }


      // Add new financial Workshop
      const payload = {
        ...financialworkshopdata,
        ['Date of Workshop or Interview']:
          financialworkshopdata['Date of Workshop or Interview'] || new Date(),
        companyId: this.state.companyId,
        surveyId: surveyId,
        worksheet: [],
        date: new Date(),
      };

      // const { id } = await matrixFinancialWorkshopsRef.add(payload);

      const response = await setFinancialWorkshops(consultantId, payload)

      const answeredTopics = this.sortAnsweredTopics(this.state.answeredTopics || []);
      const payloadfinal = {
        ...payload,
        id: response.data.data.id,
        worksheet:
          payload.worksheet && payload.worksheet.length > 0
            ? payload.worksheet
            : answeredTopics.map(itm => ({ ...itm, 'Scoring Comments': '' })),
      };

      this.handleAddAuditLog(
        'add',
        this.state.assessmentType,
        'Assessment',
        `${this.state.user.name} added worksheet for ${payloadfinal['Name of Person']} (${payloadfinal.id})`,
        'worksheet',
      );

      financialworkshops.push(payloadfinal);

      this.setState({
        loading: false,
        financialworkshopdata: {},
        financialworkshops: [...financialworkshops],
        showfinancialworkshopmodal: false,
        selectedfinancialworkshop: payloadfinal,
        financialWorkshopViewIndex: 1,
        answeredTopics: answeredTopics.map(itm => ({ ...itm, 'Scoring Comments': '' })),
      });
    } catch (ex) {
      console.log(ex.message);
      this.setState({
        loading: false,
        financialworkshopdata: {},
        showfinancialworkshopmodal: false,
      });
    }
  };
#include <bits/stdc++.h>
using namespace std;

int main(){
    ios_base::sync_with_stdio(0);
    cin.tie(NULL);
    int a;
    cin >> a;
    string n;
    cin >> n;
    int A = 0;
    int B = 0;
    for(int i =0; i < n.size(); i++){
        if(n[i] == 'a'){
            A = A + 1;
        }
        
        if(n[i] == 'b'){
            B = B + 1;
        }
    }
    cout << A << " " << B << " ";
    cout << n.size() / 2 - min(A,B);
    return 0;
}
#include <bits/stdc++.h>
using namespace std;

int main(){
    ios_base::sync_with_stdio(0);
    cin.tie(NULL);
    int l;
    int r;
    int x;
    cin >> l >> r >> x;
    int ans = 1;
    int count = 0;
    while(ans <= r){
        if(ans >= r && ans <= r){
            cout << ans << " ";
            count = count + 1;
        }
        ans *= x;
    }
    if(count == 0){
        cout << "-1";
    }
    return 0;
}
import java.util.Arrays;
import java.util.Scanner;

class Job {
    int id;
    int deadline;
    int profit;

    Job(int id, int deadline, int profit) {
        this.id = id;
        this.deadline = deadline;
        this.profit = profit;
    }
}

public class JobScheduling {
    
    public static void scheduleJobs(Job[] jobs) {
        // Sort jobs based on profit in descending order
        Arrays.sort(jobs, (a, b) -> b.profit - a.profit);
        
        // Find the maximum deadline
        int maxDeadline = 0;
        for (Job job : jobs) {
            if (job.deadline > maxDeadline) {
                maxDeadline = job.deadline;
            }
        }
        
        // Create a slot array based on maximum deadline
        boolean[] slot = new boolean[maxDeadline];
        int[] result = new int[maxDeadline];

        for (Job job : jobs) {
            // Find a free slot for this job
            for (int j = Math.min(maxDeadline - 1, job.deadline - 1); j >= 0; j--) {
                if (!slot[j]) {
                    slot[j] = true;
                    result[j] = job.id; 
                    break;
                }
            }
        }

        // Output the scheduled jobs
        System.out.println("Scheduled Jobs:");
        for (int jobId : result) {
            if (jobId != 0) {
                System.out.print(jobId + " ");
            }
        }
        System.out.println();
    }

    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        System.out.println("Enter number of jobs: ");
        int n = sc.nextInt();

        Job[] jobs = new Job[n];
        System.out.println("Enter jobs (id, deadline, profit):");
        for (int i = 0; i < n; i++) {
            int id = sc.nextInt();
            int deadline = sc.nextInt();    
            int profit = sc.nextInt();
            jobs[i] = new Job(id, deadline, profit);
        }

        scheduleJobs(jobs);
        sc.close();
    }
}
 handleSubmitWorkshop = async e => {
    const { workshops, workshopdata, surveyId, currentSurveyId, consultantId } = this.state;
    // const matrixWorkshopsRef = firebase
    //   .firestore()
    //   .collection(consultantId ? 'portfolio-surveys-consultants' : 'surveys')
    //   .doc(surveyId ? surveyId : currentSurveyId)
    //   .collection('workshops'); // -->

    e.preventDefault();

    this.setState({
      loading: true,
      workshopTabIndex: 0,
    });
    const formatDate = (date) => {
      if (!date) return null;
      const d = date.seconds ? new Date(date.seconds * 1000 + date.nanoseconds / 1000000) : new Date(date);
      const month = ('0' + (d.getMonth() + 1)).slice(-2);
      const day = ('0' + d.getDate()).slice(-2);
      const year = d.getFullYear();
      return `${month}/${day}/${year}`;
    };

    try {
      // Edit condition (check if id present in the current workshop displayed in the UI)
      if (workshopdata.id) {
        // const docRef = matrixWorkshopsRef.doc(workshopdata.id); // -->
        // const docSnapshot = await docRef.get(); // -->
        // const oldData = docSnapshot.data(); // --> 
        // console.log("old data from firebase", oldData);

        const workshopData = await getWorkshopById("workshops", {
          surveyId: surveyId,
          consultantId: consultantId,
          id: workshopdata.id,
        },)

        console.log("workshopdata", workshopData);


        // Get previous data from the workshops collection in DB
        const oldData = workshopData.data();

        const _date = workshopdata['Date of Workshop or Interview'];
        const payload = {
          ...workshopdata,
          answeredEntries: workshopdata?.answeredEntries ? workshopdata?.answeredEntries : [],
          ['Date of Workshop or Interview']:
            _date && _date.seconds
              ? new Date(_date.seconds * 1000 + _date.nanoseconds / 1000000)
              : _date,
        };

        // await matrixWorkshopsRef.doc(workshopdata.id).update(payload) // --> Replace with API call

        console.log("payload", payload);

        const response = await updateWorkshops(consultantId, workshopdata.id, payload);
        console.log("Response after editing workshop", response);

        const changes = [];
        // const oldDateFormatted = formatDate(oldData['Date of Workshop or Interview']);
        // const newDateFormatted = formatDate(workshopdata['Date of Workshop or Interview']);
        const oldDateFormatted = oldData['Date of Workshop or Interview'];
        const newDateFormatted = workshopdata['Date of Workshop or Interview'];

        if (workshopdata['Name of Person'] !== oldData['Name of Person']) {
          changes.push(`Name of Person changed from ${oldData['Name of Person']} to ${workshopdata['Name of Person']}`);
        }
        if (workshopdata['Stakeholder Type'] !== oldData['Stakeholder Type']) {
          changes.push(`Stakeholder Type changed from ${oldData['Stakeholder Type']} to ${workshopdata['Stakeholder Type']}`);
        }
        if (workshopdata['Type'] !== oldData['Type']) {
          changes.push(`Type changed from ${oldData['Type']} to ${workshopdata['Type']}`);
        }


        if (workshopdata['Interviewer Name'] !== oldData['Interviewer Name']) {
          changes.push(`Interviewer Name changed from ${oldData['Interviewer Name']} to ${workshopdata['Interviewer Name']}`);
        }

        if (newDateFormatted !== oldDateFormatted) {
          changes.push(`Date of Workshop or Interview changed from ${oldDateFormatted} to ${newDateFormatted}`);
        }

        if (workshopdata['Comments'] !== oldData['Comments']) {
          const oldcomment = oldData['Comments'] || 'Blank';
          changes.push(`Comments changed from ${oldcomment} to ${workshopdata['Comments']}`);
        }
        if (workshopdata['Recommendations'] !== oldData['Recommendations']) {
          const oldrec = oldData['Recommendations'] || 'Blank';
          changes.push(`Recommendations changed from ${oldrec} to ${workshopdata['Recommendations']}`);
        }

        this.handleAddAuditLog(
          'update',
          this.state.assessmentType,
          'Assessment',
          `${this.state.user.name} Updated worksheet of ${workshopdata['Name of Person']} (${workshopdata.id}) : ${changes} `,
          'worksheet',
        );

        const index = workshops.findIndex(item => item.id == workshopdata.id);

        workshops[index] = payload;
        this.setState({
          loading: false,
          workshopdata: {},
          workshops: [...workshops],
          selectedworkshop: payload,
          showworkshopmodal: false,
        });
        return;

      }

      // Add new workshop functionality
      const payload = {
        ...workshopdata,
        ['Date of Workshop or Interview']:
          workshopdata['Date of Workshop or Interview'] || new Date(),
        companyId: this.state.companyId,
        surveyId: surveyId,
        worksheet: [],
        date: new Date(),
      };

      // const { id } = await matrixWorkshopsRef.add(payload);
      // Submit new workshop to DB

      const response = await setWorkshops(consultantId, payload);

      const answeredTopics = this.sortAnsweredTopics(this.state.answeredTopics || []);
      const payloadfinal = {
        ...payload,
        id: response.data.data.id, // Find out what to enter here instead of id from firebase add call
        // id,
        worksheet:
          payload.worksheet && payload.worksheet.length > 0
            ? payload.worksheet
            : answeredTopics.map(itm => ({ ...itm, 'Scoring Comments': '' })),
      };

      console.log("payloadfinal", payloadfinal);

      this.handleAddAuditLog(
        'add',
        this.state.assessmentType,
        'Assessment',
        `${this.state.user.name} added worksheet for ${payloadfinal['Name of Person']} (${payloadfinal.id})`,
        'worksheet',
      );

      workshops.push(payloadfinal);
      console.log("workshops", workshops);

      this.setState({
        loading: false,
        workshopdata: {},
        workshops: [...workshops],
        showworkshopmodal: false,
        selectedworkshop: payloadfinal,
        workshopViewIndex: 1,
        answeredTopics: answeredTopics.map(itm => ({ ...itm, 'Scoring Comments': '' })),
      });
    } catch (ex) {
      console.log(ex?.message);
      this.setState({
        loading: false,
        workshopdata: {},
        showworkshopmodal: false,
      });
    }
  };
handleSubmitTabComment = async (e, type) => {
    e.preventDefault();
    this.setState({ loading: true });

    const allComments = Array.from(this.state.comments);

    const newComment = {
      date: new Date(),
      user: {
        name: this.state.user.username || this.state.user.name || 'N/A',
        companyId: this.state.user.companyId || 'N/A',
        id: this.state.user.id || 'N/A',
        email: this.state.user.email || 'N/A',
      },
      comment: this.state.tabcommentvalue,
      type: type,
    };

    allComments.push(newComment);

    allComments.sort((a, b) => new Date(b.date) - new Date(a.date));

    const { surveyId, currentSurveyId, consultantId } = this.state;
    // axios(this.postOptions(postUrl, newComment))
    addComment(
      {
        surveyId,
        consultantId,
      },
      newComment,
    )
      .then(response => {
        console.log('submitted response', response);
        this.setState({
          loading: false,
          showtabcommentmodal: {
            open: false,
            type: '',
          },
          tabcommentvalue: '',
          tabComments: allComments,
        });
        const summary = `${this.state.user.name} Added new comment ${newComment.comment}`;
        this.handleAddAuditLog(
          'add',
          this.state.assessmentType,
          'Assessment',
          summary,
          'Tab Comment',
        );
      })
      .catch(error => {
        this.setState({
          loading: false,
          showtabcommentmodal: {
            open: false,
            type: '',
          },
          tabcommentvalue: '',
          tabComments: allComments,
        });
      });

   
  };
 getSurveys = async (
    surveyId,
    filterByStakeholderTypeValue,
    filterByCountryValue,
    filterByContinentValue,
    consultantId,
  ) => {
    try {
      const { assessmentType } = this.state;

      // Fetch survey details
      const surveyDetails = await getbysurveyid(surveyId, consultantId);
      const survey = surveyDetails.data();
      console.log("survey", survey);
      const submittedSurveyResults = await getsubmittedSurveyResult(surveyId, consultantId);
      const tabComments = survey["tab-comments"] || []; 
      const surveyConditions = () => (Object.keys(survey).length > 0 && survey?.approvedTopics) ? survey?.approvedTopics : false;

      const workshops = await getSurveyResultForSubcollection(surveyId, consultantId, 'workshops')
      const financialWorkshops = await getSurveyResultForSubcollection(surveyId, consultantId, 'financial-workshops')

      // this.setState({
      //   survey: { ...survey, id: survey.id },
      //   // loading: false,
      // });

      // Object to hold all state changes to schedule the state updations
      const newState = {}
      console.log("newState 1", newState)

      newState.survey = { ...survey, id: survey.id }

      if (survey.answeredTopics) {
        let allTopics = survey?.surveyTopicsShort
          ? [
            ...survey.surveyTopicsShort.business,
            ...survey.surveyTopicsShort.social,
            ...survey.surveyTopicsShort.human,
            ...survey.surveyTopicsShort.environment,
            ...survey.surveyTopicsShort.leadership,
          ]
          : [];
        newState.materialityAssessmentTopics = survey.answeredTopics;
        newState.financialConsolidatedReports = [...survey.answeredTopics, ...allTopics]
          .filter((v, i, a) => a.findIndex(t => t.topic === v.topic && t.id === v.id) === i)
          .filter(item => item.entryType !== 'comment' && item.entryType !== 'added-entry')
          .sort((a, b) => {
            if (a.framework == 'CSRD') {
              let _a =
                CSRDAllTopics?.find(
                  item2 => item2['mainId'] == a['mainId'] && item2['topic'] == a['topic'],
                )?.sortIndex || 0;
              let _b =
                CSRDAllTopics?.find(
                  item2 => item2['mainId'] == b['mainId'] && item2['topic'] == b['topic'],
                )?.sortIndex || 0;

              return _a < _b ? -1 : _a > _b ? 1 : 0;
            }

            if (a.framework == 'GRI') {
              let _a = a.id;
              let _b = b.id;

              return _a < _b ? -1 : _a > _b ? 1 : 0;
            }

            if (a.topic < b.topic) return -1;
            if (a.topic > b.topic) return 1;
          })
          ?.sort((a, b) => {
            if (a.isCustom || b.isCustom) {
              // Move objects with 'isCustom' property to the end
              if (a.isCustom && !b.isCustom) {
                return 1;
              } else if (!a.isCustom && b.isCustom) {
                return -1;
              } else {
                // If both have 'isCustom' or neither have 'isCustom', sort by customSortId
                if (a.customSortId && b.customSortId) {
                  return a.customSortId > b.customSortId ? 1 : -1;
                } else {
                  return a.topic > b.topic ? 1 : -1;
                }
              }
            }
          })
          .sort((a, b) => {
            if (this.renderESG(a.dimension) == 'Environmental') return -1;
            if (this.renderESG(b.dimension) == 'Environmental') return 1;
            if (this.renderESG(a.dimension) == 'Social') return -1;
            if (this.renderESG(b.dimension) == 'Social') return 1;
            if (this.renderESG(a.dimension) == 'Governance') return -1;
            if (this.renderESG(b.dimension) == 'Governance') return 1;

            if (this.renderESG(a.dimension) < this.renderESG(b.dimension)) return -1;
            if (this.renderESG(a.dimension) > this.renderESG(b.dimension)) return 1;
          })
          .sort((a, b) => {
            if (this.renderESG(a.dimension) == 'Environmental') return -1;
            if (this.renderESG(b.dimension) == 'Environmental') return 1;
            if (this.renderESG(a.dimension) == 'Social') return -1;
            if (this.renderESG(b.dimension) == 'Social') return 1;
            if (this.renderESG(a.dimension) == 'Governance') return -1;
            if (this.renderESG(b.dimension) == 'Governance') return 1;

            if (this.renderESG(a.dimension) < this.renderESG(b.dimension)) return -1;
            if (this.renderESG(a.dimension) > this.renderESG(b.dimension)) return 1;
          });

        newState.allTopics = allTopics;
        newState.answeredTopics = survey.answeredTopics
          ? [...survey.answeredTopics, ...allTopics].filter(
            (v, i, a) => a.findIndex(t => t.topic === v.topic && t.id === v.id) === i,
          )
          : [];
        newState.addedCommentTopics = Array.from(survey.addedCommentTopics || []);

   
      } else {
        // this.setState({ loading: false });
      }





      const properties = {
        impactMaterialityMethodology: true,
        impactMaterialityScoringMethodology: true,
        financialMaterialityMethodology: true,
        financialMaterialityScoringMethodology: true,
        financialMappingMethodology: true,
        materialityAssessmentTopics: true,
        verifiedTopics: true,
        scoringSetting: true,
        reasonForMaxOrAverage: true,
        isNotFirstTimeOpeningImpactWorksheet: true,
        isNotFirstTimeOpeningFinancialWorksheet: true
      };

      for (const key in properties) {
        if (survey[key] !== undefined) {
          newState[key] = survey[key];
        }
      }

      // Default value for stakeholderTypes
      newState.stakeholderTypes = survey.stakeholderTypes || _stakeholderTypes;

      const getProperDate = date => {
        if (date.toDate) {
          return date.toDate();
        } else {
          return date;
        }
      };

      // Survey List operations
      this.handleSubmittedSurveyListOperation(submittedSurveyResults, surveyConditions)

      const workshopList = workshops.map(workshop => {
        return {
          ...workshop,
          id: workshop.id,
          answeredEntries: workshop?.['answeredEntries']?.map(itm => ({
            ...itm,
            Scale: itm['Scale'] == '0 - None' ? '1 - Minimal' : itm['Scale'] || '',
            Scope: itm['Scope'] == '0 - No impact' ? '1 - Limited' : itm['Scope'] || '',
            Likelihood:
              itm['Likelihood'] ==
                '0 - Very Unlikely (Has not occurred, and the possible chance of occuring is low)'
                ? '1 - Rare'
                : itm['Likelihood'] || '',
            Remediability:
              itm['Remediability'] == '0 - Very Easy to remedy'
                ? '1 - Relatively easy to remedy'
                : itm['Remediability'] || '',
          })),
        };
      });

      const financialWorkshopList = financialWorkshops.map(workshop => ({
        ...workshop,
        id: workshop.id,
        answeredEntries: workshop?.['answeredEntries']?.map(itm => ({
          ...itm,
          Likelihood:
            itm['Likelihood'] ==
              '0 - Very Unlikely (Has not occurred, and the possible chance of occuring is low)'
              ? '1 - Rare'
              : itm['Likelihood'] || '',
          Magnitude:
            itm['Magnitude'] == '0 - Not material (0%)'
              ? '1 - Minimal Impact'
              : itm['Magnitude'] || '',
        })),
      }));

      const tabCommentsList = tabComments.map(comment => {
        if (!comment.comment) return; // Workaround for damaged data --> remove once data is changed from DB

        return {
          ...comment,
          id: comment.id,
          // date: getProperDate(comment.date)
          date: comment.date.toDate ? comment.date.toDate() : comment.date,
        };
      });

      newState.workshops = workshopList
      newState.financialworkshops = financialWorkshopList
      newState.tabComments = tabCommentsList
      newState.loading = false

      console.log("newState", newState);

      this.setState(newState);

    
    } catch (ex) {
      this.setState({ loading: false });
    }
  };
#wpgs-gallery.wcgs-woocommerce-product-gallery .wcgs-carousel {
    max-width: 100%;
}
<!DOCTYPE html>
<html>
<head>
    <title>Event Count</title>
    <style>
        body {
            font-family: Arial, sans-serif;
            background-color: #fdf2e9;
        }
        .container {
            background-color: #fcefe3;
            width: 400px;
            padding: 20px;
            border: 1px solid #ccc;
            margin: 100px auto;
            text-align: center;
        }
        h2 {
            text-align: center;
        }
        input {
            margin-bottom: 10px;
            padding: 5px;
            width: 200px;
        }
        button {
            padding: 10px 20px;
            font-size: 14px;
            cursor: pointer;
        }
        #result {
            margin-top: 20px;
            font-weight: bold;
        }
    </style>
</head>
<body>
    <div class="container">
        <h2>Event count for a month</h2>
        
        <label for="event1">Birthday party event :</label>
        <input type="number" id="event1"><br>
        
        <label for="event2">Engagement parties event :</label>
        <input type="number" id="event2"><br>
        
        <label for="event3">Corporate event :</label>
        <input type="number" id="event3"><br>
        
        <label for="event4">Social Gathering event :</label>
        <input type="number" id="event4"><br>
        
        <button id="button" onclick="maxevent()">Submit</button>
        
        <div id="result"></div>
    </div>

    <script>
       function maxevent() {
    // Getting event counts
    var event1 = parseInt(document.getElementById('event1').value) || 0;
    var event2 = parseInt(document.getElementById('event2').value) || 0;
    var event3 = parseInt(document.getElementById('event3').value) || 0;
    var event4 = parseInt(document.getElementById('event4').value) || 0;
    
    // Finding the maximum event count
    var maxCount = Math.max(event1, event2, event3, event4);
    
    // Displaying the result
    var resultDiv = document.getElementById('result');
    if (maxCount === event1) {
        resultDiv.innerHTML = "Maximum number of event occurred in this month is Birthday party";
    } else if (maxCount === event2) {
        resultDiv.innerHTML = "Maximum number of event occurred in this month is Engagement parties";
    } else if (maxCount === event3) {
        resultDiv.innerHTML = "Maximum number of event occurred in this month is Corporate";
    } else if (maxCount === event4) {
        resultDiv.innerHTML = "Maximum number of event occurred in this month is Social Gathering";
    }
}

    </script>
</body>
</html>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Calculator</title>
    <style>
        body {
            font-family: Arial, sans-serif;
            margin: 50px;
            text-align: center;
        }
        input {
            margin: 10px;
            padding: 10px;
            width: 80px;
        }
        button {
            padding: 10px 20px;
            margin: 5px;
        }
        #result {
            margin-top: 20px;
            font-size: 20px;
            font-weight: bold;
        }
    </style>
</head>
<body>

    <h3>Simple Calculator</h3>
    <input type="number" id="value1" placeholder="Value 1">
    <input type="number" id="value2" placeholder="Value 2"><br>
    <button name="add" onclick="add()">ADDITION</button>
    <button name="sub" onclick="sub()">SUBTRACT</button>
    <button name="mul" onclick="mul()">MULTIPLY</button>
    <button name="div" onclick="div()">DIVISION</button>

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

    <script>
        function add() {
            const value1 = parseFloat(document.getElementById("value1").value);
            const value2 = parseFloat(document.getElementById("value2").value);
            document.getElementById("result").innerText = "Addition of " + value1 + " and " + value2 + " is " + (value1 + value2);
        }

        function sub() {
            const value1 = parseFloat(document.getElementById("value1").value);
            const value2 = parseFloat(document.getElementById("value2").value);
            document.getElementById("result").innerText = "Subtraction of " + value1 + " and " + value2 + " is " + (value1 - value2);
        }

        function mul() {
            const value1 = parseFloat(document.getElementById("value1").value);
            const value2 = parseFloat(document.getElementById("value2").value);
            document.getElementById("result").innerText = "Multiplication of " + value1 + " and " + value2 + " is " + (value1 * value2);
        }

        function div() {
            const value1 = parseFloat(document.getElementById("value1").value);
            const value2 = parseFloat(document.getElementById("value2").value);
            if (value2 === 0) {
                document.getElementById("result").innerText = "Error: Division by zero";
            } else {
                document.getElementById("result").innerText = "Division of " + value1 + " and " + value2 + " is " + (value1 / value2);
            }
        }
    </script>

</body>
</html>
Flow version:
HYPERLINK(LEFT($Api.Enterprise_Server_URL_610, FIND( '/services', $Api.Enterprise_Server_URL_610)) & {!$Record.AccountId}, {!$Record.Account.Name})     
     
Forula version: 
HYPERLINK(LEFT($Api.Enterprise_Server_URL_610, FIND( '/services', $Api.Enterprise_Server_URL_610)) & AccountId, Account.Name)     
mô hình động học phân tử về cấu tạo chất 
các chất đều được cấu tạo từ phân tử nguyên tử 
các phân tử chuyển động không ngừng
nhiệt độ càng cao chuyển động càng nhanh 
giữa các phân tử có các lực hút đẩy gọi là lực liên kết các phân tử 

1. Chất Rắn:
Khoảng cách: Gần nhau.
Sự sắp xếp: Đều đặn, cấu trúc tinh thể.
Chuyển động: Rung động tại chỗ.
2. Chất Lỏng:
Khoảng cách: Xa hơn rắn nhưng gần nhau.
Sự sắp xếp: Không cố định, linh hoạt.
Chuyển động: Di chuyển và trượt qua nhau.
3. Chất Khí:
Khoảng cách: Rất xa nhau.
Sự sắp xếp: Không cố định, phân tán.
Chuyển động: Di chuyển nhanh và tự do.

1. chất rắn 
khoảng cách rất gần 
có sự sắp xếp và cấu trúc
dao động quanh vị trí cân bằng cố định 

2. chất lỏng 
khoảng cách xa hơn chất rắn nhưng vẫn gần nhau 
sự sắp xếp, linh hoạt không cố định 
di chuyển xung quanh một vị trí cân bằng 

3. chất khí 
khoảng cách: rất xa nhau
sự sắp xếp: phân tán loạn xạ 
chuyển động tự do và hỗn loạn 

chất rắn 
phân tử có sự sắp xếp chặt chẽ 
phân tử ở rất gần nhau 
di chuyển xung quanh một vị trí cân bằng cố định 

chất lỏng 
khoảng cách xa hơn chất rắn nhưng vẫn gần nhau 
có sự sắp xếp theo cấu trúc nhưng linh hoạt hơn  chất răns
di chuyển xung quanh vị trí cân bằng không cố định 

chất khí
khoảng cách rất xa nhau 
di chuyển hỗn loạn tự do 

mô hình động học của các phân tử 
mô hình động học của các phân tư r
mô hình động học của các phân tử
các chất đều được tạo nên từ các nguyên tử 
các chất di chuyển không ngừng 
nhiệt độ càng tăng di chuyển càng nhanh 
giữa các phân tử có các lực hút đẩy gọi là lực liên kết phân tử

sự chuyển thể 
rắn lỏng nóng chảy 
rắn khí thăng hoa

lỏng sang rắn đông đặc 
lỏng khí hóa hơi

khí rắn ngưng kết
khí lỏng ngưng tụ

sự bay hơi xảy ra ở bất kì nhiệt độ nào ở trên bề mặt thoáng của chất lỏng 
các phân tử di chuyển liên tục có thể vô tình va vào nhau và truyền năng lượng cho nhau 
khi các phân tử ở gần mặt thoáng nhận đủ năng lượng nó có thể thắng được lực liên kết phân tử từ đó thoát ra khỏi chất lỏng và chuyển thành thể khí 

sự sôi là sự bay hơi nhưng xảy ra cả ở bề mặt thoáng lẫn ở bên trong lòng chất lỏng 

trong lúc sôi nhiệt độ của chất ko thay đổi 
năng lượng sẽ được truyền cho các phân tử lỏng chưa bay hơi cho đến khi chúng bay hơi hết 

sự nóng chảy của chất rắn kết tinh 

Sự nóng chảy của chất rắn kết tinh:

Khái niệm: Là quá trình chất rắn kết tinh chuyển thành chất lỏng khi được làm nóng.
Quá trình: Khi nhiệt độ tăng, các phân tử trong chất rắn kết tinh được cung cấp đủ năng lượng để phá vỡ cấu trúc tinh thể, từ đó chất rắn chuyển thành chất lỏng.
Điểm nóng chảy: Đây là nhiệt độ tại đó chất rắn kết tinh bắt đầu chuyển sang trạng thái lỏng. Điểm này là đặc trưng cho mỗi chất và thường rất rõ ràng.
Cấu trúc tinh thể: Trong chất rắn kết tinh, các phân tử được sắp xếp theo một cấu trúc lặp lại đều đặn. Khi đạt đến điểm nóng chảy, cấu trúc này bị phá vỡ.
Ví dụ:


là quá trình chất rắn kết tinh chuyển thành chất lỏng khi được làm nóng 
quá trình: khi nhiệt độ tăng, các phân tử rắn kết tinh được cung cấp đủ năng lượng để phá vỡ cấu trúc tinh thể từ đó chất rắn chuyển dần thành chất lỏng

điểm nóng chảy: đây là nhiệt độ mà tại đó chất rắn kết tinh bắt đầu chuyển sang trạng thái lỏng
trong lúc nóng chảy t độ ko thay đổi 
#!/bin/bash
####################################
#
# Rolling 7 day backup to local directory
#
####################################

mysqldump_location="path_to_place_mysql_dump_file"

/usr/bin/mysqldump --opt your_database_name --single-transaction --default-character-set=utf8mb4 > $mysqldump_location/your_dump_file_name.SQL

# What to backup.
backup_files="path_to_your_website_directory"

# Where to backup to.
dest="path_to_place_your_backup_files"

# Create archive filename.
day=$(date +%A)
hostname=$(hostname -s)
archive_file="your_domain_name-$day.zip"


# Backup the files using zip.
zip -r $dest/$archive_file $backup_files
rm -f $mysqldump_location/your_dump_file.SQL
<!-- Row -->
<div class="row">


 	<!-- Column -->
	<div class="col-md-6">
		<p>TEXT</p>
	</div>


 	<!-- Column -->
	<div class="col-md-6">
		<p>TEXT</p>
	</div>


</div>
star

Fri Sep 20 2024 21:28:30 GMT+0000 (Coordinated Universal Time) https://unofficialsf.com/build-lightning-styled-screen-flows-that-users-will-love/

@dannygelf #flow #salesforce #slds

star

Fri Sep 20 2024 21:20:17 GMT+0000 (Coordinated Universal Time)

@fededeleon #sql

star

Fri Sep 20 2024 20:24:14 GMT+0000 (Coordinated Universal Time) https://github.com/WordPress/WordPress/blob/master/index.php

@systemsroncal

star

Fri Sep 20 2024 20:16:49 GMT+0000 (Coordinated Universal Time)

@cc.garylau831

star

Fri Sep 20 2024 17:35:37 GMT+0000 (Coordinated Universal Time) undefined

@lndarl28

star

Fri Sep 20 2024 16:05:04 GMT+0000 (Coordinated Universal Time)

@jrg_300i #undefined

star

Fri Sep 20 2024 16:02:56 GMT+0000 (Coordinated Universal Time)

@freepythoncode ##python #coding #python #programming #game

star

Fri Sep 20 2024 14:02:28 GMT+0000 (Coordinated Universal Time) https://www.programiz.com/cpp-programming/online-compiler/

@deshmukhvishal2

star

Fri Sep 20 2024 08:49:34 GMT+0000 (Coordinated Universal Time)

@signup

star

Fri Sep 20 2024 08:12:57 GMT+0000 (Coordinated Universal Time) https://maticz.com/white-label-crypto-exchange

@HenryJames

star

Fri Sep 20 2024 08:12:27 GMT+0000 (Coordinated Universal Time) https://www.programiz.com/cpp-programming/online-compiler/

@deshmukhvishal2

star

Fri Sep 20 2024 07:02:08 GMT+0000 (Coordinated Universal Time)

@peterjhonsonpj

star

Fri Sep 20 2024 06:44:21 GMT+0000 (Coordinated Universal Time) https://www.beleaftechnologies.com/

@sivaprasadm203 #blockchain #cryptocurrency #defi #web3

star

Fri Sep 20 2024 05:27:50 GMT+0000 (Coordinated Universal Time) https://myassignmenthelp.expert/

@steve1997 #elixir

star

Fri Sep 20 2024 00:24:23 GMT+0000 (Coordinated Universal Time) https://stackoverflow.com/questions/67045764/how-can-i-remove-white-spaces-between-words

@dannygelf #sheets #googlesheets

star

Thu Sep 19 2024 23:55:16 GMT+0000 (Coordinated Universal Time)

@gbritgs

star

Thu Sep 19 2024 23:43:17 GMT+0000 (Coordinated Universal Time) https://www.onlinegdb.com/edit/sXLBZW-Wda

@realGuyCrimson

star

Thu Sep 19 2024 22:09:36 GMT+0000 (Coordinated Universal Time)

@madgakantara #r

star

Thu Sep 19 2024 20:16:29 GMT+0000 (Coordinated Universal Time)

@mebean #flutter #laravel #api #http #2lancer

star

Thu Sep 19 2024 16:09:18 GMT+0000 (Coordinated Universal Time) https://caleksiev.wixsite.com/olzteam/post/salesforce-hacks-1-mass-delete-salesforce-flow-versions

@dannygelf #salesforce #flows #soql

star

Thu Sep 19 2024 14:33:08 GMT+0000 (Coordinated Universal Time)

@FXA

star

Thu Sep 19 2024 13:40:09 GMT+0000 (Coordinated Universal Time)

@iamkatmakhafola

star

Thu Sep 19 2024 12:35:53 GMT+0000 (Coordinated Universal Time)

@alfred.roshan

star

Thu Sep 19 2024 12:13:58 GMT+0000 (Coordinated Universal Time)

@alfred.roshan

star

Thu Sep 19 2024 12:13:20 GMT+0000 (Coordinated Universal Time)

@alfred.roshan

star

Thu Sep 19 2024 11:35:26 GMT+0000 (Coordinated Universal Time)

@Curable1600 #windows

star

Thu Sep 19 2024 11:26:24 GMT+0000 (Coordinated Universal Time)

@alfred.roshan

star

Thu Sep 19 2024 11:26:05 GMT+0000 (Coordinated Universal Time)

@alfred.roshan

star

Thu Sep 19 2024 09:54:15 GMT+0000 (Coordinated Universal Time)

@alfred.roshan

star

Thu Sep 19 2024 09:53:08 GMT+0000 (Coordinated Universal Time)

@alfred.roshan

star

Thu Sep 19 2024 09:52:40 GMT+0000 (Coordinated Universal Time)

@alfred.roshan

star

Thu Sep 19 2024 08:48:30 GMT+0000 (Coordinated Universal Time)

@alfred.roshan

star

Thu Sep 19 2024 08:47:41 GMT+0000 (Coordinated Universal Time)

@alfred.roshan

star

Thu Sep 19 2024 08:40:51 GMT+0000 (Coordinated Universal Time)

@alfred.roshan

star

Thu Sep 19 2024 05:50:03 GMT+0000 (Coordinated Universal Time) https://www.programiz.com/cpp-programming/online-compiler/

@LizzyTheCatto

star

Thu Sep 19 2024 05:40:30 GMT+0000 (Coordinated Universal Time) https://www.programiz.com/cpp-programming/online-compiler/

@LizzyTheCatto

star

Thu Sep 19 2024 05:20:01 GMT+0000 (Coordinated Universal Time)

@signup

star

Thu Sep 19 2024 04:47:27 GMT+0000 (Coordinated Universal Time)

@alfred.roshan

star

Thu Sep 19 2024 04:36:22 GMT+0000 (Coordinated Universal Time)

@alfred.roshan

star

Thu Sep 19 2024 04:35:18 GMT+0000 (Coordinated Universal Time)

@alfred.roshan

star

Thu Sep 19 2024 04:24:57 GMT+0000 (Coordinated Universal Time) https://secure.helpscout.net/inboxes/a66af2abc7090990/views/4174596

@Pulak

star

Thu Sep 19 2024 04:07:48 GMT+0000 (Coordinated Universal Time)

@adsj

star

Thu Sep 19 2024 04:07:06 GMT+0000 (Coordinated Universal Time)

@adsj

star

Wed Sep 18 2024 20:48:41 GMT+0000 (Coordinated Universal Time)

@dannygelf #apex #flow #salesforce #formula

star

Wed Sep 18 2024 20:33:34 GMT+0000 (Coordinated Universal Time) https://www.programiz.com/cpp-programming/online-compiler/

@LizzyTheCatto

star

Wed Sep 18 2024 19:29:50 GMT+0000 (Coordinated Universal Time) https://admin-junkies.com/threads/regular-backups-and-disaster-recovery-planning.15429/

@dontexpectless #bash #backup #mysql #ddbb

star

Wed Sep 18 2024 18:45:49 GMT+0000 (Coordinated Universal Time) https://clackamasnewstg2.prod.acquia-sites.com/node/145826/edit

@nmeyer

Save snippets that work with our extensions

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