Snippets Collections
map(int, input().split())
// html
 <div id="app">
      <div class="grid-container">
        <div class="box"><a href="#">remove</a></div>
        <div class="box"><a href="#">remove</a></div>
        <div class="box"><a href="#">remove</a></div>
        <div class="box"><a href="#">remove</a></div>
      </div>
    </div>


//css


.grid-container {
  background-color: aliceblue;
  width: 100%;
  min-height: 200px;
  display: grid;
  column-gap: 1rem;
  grid-template-columns: repeat(
    var(--col-grid-count, 4),
    var(--col-make-width, 1fr)
  );
}

.box {
  width: 100%;
  height: 100%;
  background-color: firebrick;
  padding-top: 1rem;
}

.box a {
  text-align: center;
  margin-top: 1rem;
  color: white;
  display: flex;
  justify-content: center;
  cursor: pointer;
  text-decoration: none;
}


//js

(function () {
  "use strict";

  const gridContainer = document.querySelector(".grid-container");

  if (!gridContainer) return;

  function changeItemWith(value) {
    gridContainer.style.setProperty("--col-make-width", value);
  }

  function updateGrid(number) {
    const updatedBoxes = document.querySelectorAll(".box").length;
    gridContainer.style.setProperty("--col-grid-count", updatedBoxes);

    const widthOptions = {
      1: () => changeItemWith("minmax(230px, 250px)"),
      2: () => changeItemWith("minmax(295px, 320px)"),
      3: () => changeItemWith("minmax(245px, 420px)"),
      4: () => changeItemWith("minmax(243px, 500px)"),
    };

    console.log(`Number of boxes: ${number}`);
    console.log(`Function in widthOptions:`, widthOptions[number]);

    // Fix: Call the function if it exists, otherwise apply default width
    // see note on how widthOptions[number](); works
    if (widthOptions[number]) {
      widthOptions[number]();
    } else {
      changeItemWith("205px"); // Default case
    }
  }

  function onHandleLink(event) {
    event.preventDefault();

    const link = event.currentTarget;
    const box = link.parentElement;

    if (box) {
      box.remove();
      // Fix: Pass the correct length
      updateGrid(document.querySelectorAll(".box").length); 
    }

    console.log(box);
  }

  function listeners() {
    document.querySelectorAll(".box").forEach((box) => {
      const link = box.querySelector("a");
      if (link) {
        link.addEventListener("click", onHandleLink);
      }
    });
  }

  function init() {
    // Fix: Pass the correct length
    updateGrid(document.querySelectorAll(".box").length); 
    listeners();
  }

  init();
})();



/*
NOTE; Understanding widthOptions 

widthOptions is an object where each key (like 1, 2, etc.) maps to a function:

const widthOptions = {
  1: () => changeItemWith("minmax(230px, 250px)"),
  2: () => changeItemWith("minmax(295px, 249px)"),
  3: () => changeItemWith("minmax(245px, 1fr)"),
  4: () => changeItemWith("minmax(243px, 1fr)"),
};

Each value is an anonymous function (() => {}) that calls changeItemWith(...).


Accessing a Function in an Object
If number is 1, then: widthOptions[1]

is the same as: () => changeItemWith("minmax(230px, 250px)");
which in the widthOptions object is:  1: () => changeItemWith("minmax(230px, 250px)")


So if we call it with (), it executes:
widthOptions[1]();
*/ 

// See codesandbox for my implementation
// https://codesandbox.io/p/sandbox/q3926h?file=%2Fsrc%2Findex.mjs%3A28%2C6-28%2C30
   <div class="ue-mega-menu-inner-links" id="uc_mega_menu_inner_links_elementor_">
	<div class="elementor-repeater-item-ed346d6"></div>
	<div class="elementor-repeater-item-006127e7"></div>
	<div class="elementor-repeater-item-r6592c7"></div>
	<div class="elementor-repeater-item-a66145b"></div>
</div>

<style>
[class^="elementor-repeater-item-"] {
     background-color: lightgray;
     padding: 10px;
}
</style>
<!-- -----------------------------------------
--------------------------- -->

<div data-text="example">טקסט זה יהיה אדום ושמן</div>
<div data-text="something-else">טקסט זה לא יושפע</div>
<style>
[data-text="example"] {
    color: red;
    font-weight: bold;
}
</style>

<! ---------------------------->

<div data-text="menu-item-1">תפריט 1</div>
<div data-text="menu-section">תפריט כללי</div>
<div data-text="other-menu">לא יושפע כי זה לא מתחיל ב-"menu"</div>
<style>
[data-text^="menu"] {
    background-color: yellow;
}
</style>

<!----------------------------->

<div data-text="menu-item-1">תפריט עם פריט</div>
<div data-text="nav-item">פריט ניווט</div>
<div data-text="items-list">רשימת פריטים</div>
<div data-text="random-text">לא יושפע כי אין בו "item"</div>
<style>
[data-text*="item"] {
    border: 2px solid blue;
}
</style>

<!------------------------------->

<div data-text="section-end">זה יסומן בקו תחתי</div>
<div data-text="menu-end">גם זה</div>
<div data-text="start-end">זה גם כי זה נגמר ב-"end"</div>
<div data-text="end-section">לא יושפע כי "end" לא בסוף</div>
<style>
[data-text$="-end"] {
    text-decoration: underline;
}
</style>

<-------------------------------->
<div class="ue-mega-menu-inner-links">
    <div data-text="menu-home">עמוד הבית</div>
    <div data-text="menu-services">שירותים</div>
    <div data-text="random-text">לא יושפע כי אין "menu"</div>
</div>
<style>
.ue-mega-menu-inner-links [data-text^="menu"] {
    font-size: 18px;
    color: green;
}
</style>
{
	"xlog": {
    "prefix": "xlog",
    "body": [
        "console.log(JSON.parse(JSON.stringify(${1:var}));"
    ],
    "description": "logs json stuff through proxy"
	}
}
span {
  display: block;
  -webkit-mask-image: linear-gradient(to bottom, white, transparent);
  mask-image: linear-gradient(to bottom, white, transparent);
}
Public Function getXPathElement(sXPath As String, objElement As Object) As HTMLBaseElement
Dim sXPathArray() As String

Dim sNodeName As String
Dim sNodeNameIndex As String
Dim sRestOfXPath As String
Dim lNodeIndex As Long
Dim lCount As Long

' Split the xpath statement
sXPathArray = Split(sXPath, "/")
sNodeNameIndex = sXPathArray(1)
If Not InStr(sNodeNameIndex, "[") &gt; 0 Then
sNodeName = sNodeNameIndex
lNodeIndex = 1
Else
sXPathArray = Split(sNodeNameIndex, "[")
sNodeName = sXPathArray(0)
lNodeIndex = CLng(Left(sXPathArray(1), Len(sXPathArray(1)) - 1))
End If
sRestOfXPath = Right(sXPath, Len(sXPath) - (Len(sNodeNameIndex) + 1))

Set getXPathElement = Nothing
For lCount = 0 To objElement.ChildNodes().Length - 1
If UCase(objElement.ChildNodes().item(lCount).nodeName) = UCase(sNodeName) Then
If lNodeIndex = 1 Then
If sRestOfXPath = "" Then
Set getXPathElement = objElement.ChildNodes().item(lCount)
Else
Set getXPathElement = getXPathElement(sRestOfXPath, objElement.ChildNodes().item(lCount))
End If
End If
lNodeIndex = lNodeIndex - 1
End If
Next lCount
End Function
Public Sub parsehtml()
Dim http As Object, html As New HTMLDocument, topics As Object, titleElem As Object, detailsElem As Object, topic As HTMLHtmlElement
Dim i As Integer
Set http = CreateObject("MSXML2.XMLHTTP")
http.Open "GET", "https://news.ycombinator.com/", False
http.send
html.body.innerHTML = http.responseText
Set topics = html.getElementsByClassName("athing")
i = 2
For Each topic In topics
Set titleElem = topic.getElementsByTagName("td")(2)
Sheets(1).Cells(i, 1).Value = titleElem.getElementsByTagName("a")(0).innerText
Sheets(1).Cells(i, 2).Value = titleElem.getElementsByTagName("a")(0).href
Set detailsElem = topic.NextSibling.getElementsByTagName("td")(1)
Sheets(1).Cells(i, 3).Value = detailsElem.getElementsByTagName("span")(0).innerText
Sheets(1).Cells(i, 4).Value = detailsElem.getElementsByTagName("a")(0).innerText
i = i + 1
Next
End Sub
Common          EmployeeHoliday;
DictTable       dictTable;
SQLDICTIONARY   SqlDictionary;
int             FromDate, ToDate;

select tabId from SqlDictionary
    where SqlDictionary.name == "NW_UpdateEmployeeHoliday"
    && SqlDictionary.fieldId == 0;

dictTable = new DictTable(SqlDictionary.tabId);
EmployeeHoliday = dictTable.makeRecord();

FromDate = fieldname2id(SqlDictionary.tabId,"FromDate");
ToDate   = fieldname2id(SqlDictionary.tabId,"ToDate");
date holiday, endHoliday;
end =  start+180;
while select EmployeeHoliday
{
    holiday = EmployeeHoliday.(FromDate);
    endHoliday = EmployeeHoliday.(ToDate);
    while(holiday <= endHoliday && (start <= holiday && holiday <= end))
    {
        holiday+=1;
        end+=1;
    }
}
https://medium.com/@janpaepke/structured-logging-in-the-grafana-monitoring-stack-8aff0a5af2f5
1) Structured Logging in the Grafana monitoring stack
  @IsOptional()
  @IsArray()
  @IsString({ each: true })
  assignedTeamIds?: string[];

  @IsOptional()
  @IsArray()
  @IsString({ each: true })
  assignedMemberIds?: string[];
1.




import 'package:enum_to_string/enum_to_string.dart';
import 'package:flutter/material.dart';
import 'package:flutter_riverpod/flutter_riverpod.dart';
import 'package:go_router/go_router.dart';
import 'package:intl/intl.dart';
import 'package:rrispat_app/src/constants/enums.dart';
import 'package:rrispat_app/src/core/utils.dart';
import 'package:rrispat_app/src/features/gi/domain/models/pco_handover_model.dart';
import 'package:rrispat_app/src/features/gi/domain/provider/all_pco_handover_provider.dart';

import '../../../../core/components/division_card.dart';
import 'verify_details_page.dart';

class VerifyHandOverPage extends ConsumerStatefulWidget {
  const VerifyHandOverPage({super.key});

  @override
  ConsumerState<ConsumerStatefulWidget> createState() =>
      _VerifyHandOverPageState();
}

class _VerifyHandOverPageState extends ConsumerState<VerifyHandOverPage> {
  List<PCOHandoverModel> pcoHandOverdata = [];

  @override
  Widget build(BuildContext context) {
    pcoHandOverdata.clear();
    ref
        .read(giAllPcoHandOverDataProvider.notifier)
        .getAllHandOver()
        .forEach((element) {
      pcoHandOverdata.add(element);
    });
    return ListView.builder(
      itemCount: pcoHandOverdata.length,
      itemBuilder: (context, index) {
        return buildTransaction(pcoHandOverdata[index]);
      },
    );
  }

  Widget buildTransaction(PCOHandoverModel pcoHandoverModel) {
    print(pcoHandoverModel);
    return Padding(
      padding: const EdgeInsets.symmetric(horizontal: 10, vertical: 8),
      child: InkWell(
        onTap: () => context.pushNamed(VerifyDetailsPage.routeName,
            pathParameters: {'id': pcoHandoverModel.id.toString()}),
        borderRadius: BorderRadius.circular(15),
        child: Container(
          decoration: BoxDecoration(
            gradient: LinearGradient(
              colors: [Colors.blue.shade200, Colors.blue.shade50],
              begin: Alignment.topLeft,
              end: Alignment.bottomRight,
            ),
            borderRadius: BorderRadius.circular(15),
            boxShadow: [
              BoxShadow(
                color: Colors.blue.withOpacity(0.3),
                offset: const Offset(0, 6),
                blurRadius: 12,
              ),
            ],
          ),
          child: Padding(
            padding: const EdgeInsets.all(16.0),
            child: Column(
              crossAxisAlignment: CrossAxisAlignment.start,
              children: [
                // Header Row with Date, Division and Shift
                Row(
                  children: [
                    Text(
                      DateFormat.yMMMEd().format(
                        DateTime.parse(pcoHandoverModel.createdAt.toString()),
                      ),
                      style: Theme.of(context).textTheme.labelMedium?.copyWith(
                            fontWeight: FontWeight.w600,
                          ),
                    ),
                    const SizedBox(width: 10),
                    DivisionCard(
                      division: EnumToString.fromString(
                        Division.values,
                        pcoHandoverModel.division,
                      ) as Division,
                    ),
                    const Spacer(),
                    Column(
                      children: [
                        Icon(
                          (pcoHandoverModel.shift == "Day")
                              ? Icons.light_mode
                              : Icons.dark_mode,
                          size: 28,
                          color: Colors.black54,
                        ),
                        Text(
                          pcoHandoverModel.shift.toString(),
                          style: Theme.of(context)
                              .textTheme
                              .labelMedium
                              ?.copyWith(fontWeight: FontWeight.bold),
                        ),
                      ],
                    ),
                  ],
                ),
                const SizedBox(height: 12),
                // Summary Row with Trail No, Items Count and Verified Count
                Row(
                  mainAxisAlignment: MainAxisAlignment.spaceBetween,
                  children: [
                    Text(
                      "TrailNo : ${pcoHandoverModel.trailNo}",
                      style: Theme.of(context)
                          .textTheme
                          .bodyLarge
                          ?.copyWith(fontWeight: FontWeight.bold),
                    ),
                    Text(
                      "Type of Items : ${pcoHandoverModel.pcoModels.length}",
                      style: Theme.of(context)
                          .textTheme
                          .bodyLarge
                          ?.copyWith(fontWeight: FontWeight.bold),
                    ),
                    Text(
                      "Verify Items : ${pcoHandoverModel.pcoModels.fold(0, (previousValue, element) => (element.verify == true) ? previousValue + 1 : previousValue)}",
                      style: Theme.of(context)
                          .textTheme
                          .bodyLarge
                          ?.copyWith(fontWeight: FontWeight.bold),
                    ),
                  ],
                ),
                const Divider(
                  height: 20,
                  thickness: 1,
                  color: Colors.blueGrey,
                ),
                // Details Chips
                Wrap(
                  spacing: 10,
                  runSpacing: 8,
                  children: [
                    detailChip(
                        label: "JC No",
                        value: pcoHandoverModel.pcoModels[0].jcNo.toString()),
                    detailChip(
                        label: "Mark No",
                        value: pcoHandoverModel.pcoModels[0].markNo.toString()),
                    detailChip(
                        label: "Section",
                        value:
                            pcoHandoverModel.pcoModels[0].section.toString()),
                    detailChip(
                        label: "Thickness",
                        value:
                            pcoHandoverModel.pcoModels[0].thickness.toString()),
                    detailChip(
                        label: "Length",
                        value: pcoHandoverModel.pcoModels[0].length.toString()),
                    detailChip(
                        label: "Quantity",
                        value:
                            pcoHandoverModel.pcoModels[0].quantity.toString()),
                    detailChip(
                        label: "Weight",
                        value: pcoHandoverModel.pcoModels[0].weight.toWeight()),
                    detailChip(
                        label: "Total Weight",
                        value: (pcoHandoverModel.pcoModels[0].quantity *
                                pcoHandoverModel.pcoModels[0].weight)
                            .toWeight()),
                    detailChip(
                        label: "Reject Qty",
                        value: pcoHandoverModel.pcoModels[0].rejectQuantity
                            .toString()),
                    detailChip(
                        label: "Reject Wt",
                        value: pcoHandoverModel.pcoModels[0].rejectWeights!
                            .toWeight()),
                  ],
                ),
              ],
            ),
          ),
        ),
      ),
    );
  }

  Widget detailChip({required String label, required String value}) {
    return Chip(
      label: Text(
        "$label: $value",
        style: const TextStyle(fontSize: 12, fontWeight: FontWeight.w500),
      ),
      backgroundColor: Colors.white.withOpacity(0.8),
      padding: const EdgeInsets.symmetric(horizontal: 8, vertical: 4),
      shape: RoundedRectangleBorder(
        borderRadius: BorderRadius.circular(8),
      ),
    );
  }
}






2.



import 'package:enum_to_string/enum_to_string.dart';
import 'package:flutter/material.dart';
import 'package:flutter_riverpod/flutter_riverpod.dart';
import 'package:go_router/go_router.dart';
import 'package:intl/intl.dart';
import 'package:rrispat_app/src/constants/enums.dart';
import 'package:rrispat_app/src/core/utils.dart';
import 'package:rrispat_app/src/features/gi/domain/models/pco_handover_model.dart';
import 'package:rrispat_app/src/features/gi/domain/provider/all_pco_handover_provider.dart';

import '../../../../core/components/division_card.dart';
import 'verify_details_page.dart';

class VerifyHandOverPage extends ConsumerStatefulWidget {
  const VerifyHandOverPage({super.key});

  @override
  ConsumerState<ConsumerStatefulWidget> createState() =>
      _VerifyHandOverPageState();
}

class _VerifyHandOverPageState extends ConsumerState<VerifyHandOverPage> {
  List<PCOHandoverModel> pcoHandOverdata = [];
  @override
  Widget build(BuildContext context) {
    pcoHandOverdata.clear();
    ref
        .read(giAllPcoHandOverDataProvider.notifier)
        .getAllHandOver()
        .forEach((element) {
      pcoHandOverdata.add(element);
    });
    return Container(
      // A subtle gradient background for an extra layer of visual depth.
      decoration: BoxDecoration(
        gradient: LinearGradient(
          colors: [Colors.white, Colors.grey[200]!],
          begin: Alignment.topCenter,
          end: Alignment.bottomCenter,
        ),
      ),
      child: ListView.builder(
        itemCount: pcoHandOverdata.length,
        itemBuilder: (context, index) {
          return buildTransaction(pcoHandOverdata[index]);
        },
      ),
    );
  }

  Widget buildTransaction(PCOHandoverModel pcoHandoverModel) {
    return Padding(
      padding: const EdgeInsets.symmetric(horizontal: 10, vertical: 5),
      child: GestureDetector(
        onTap: () => context.pushNamed(
          VerifyDetailsPage.routeName,
          pathParameters: {'id': pcoHandoverModel.id.toString()},
        ),
        child: AnimatedContainer(
          duration: const Duration(milliseconds: 300),
          curve: Curves.easeOut,
          // A slight transform adds a subtle 3D tilt effect.
          transform: Matrix4.identity()
            ..setEntry(3, 2, 0.001)
            ..rotateX(0.02),
          decoration: BoxDecoration(
            color: Theme.of(context).cardColor,
            borderRadius: BorderRadius.circular(12),
            // Dual shadows simulate a raised, 3D look.
            boxShadow: [
              BoxShadow(
                color: Colors.black.withOpacity(0.2),
                offset: const Offset(4, 4),
                blurRadius: 8,
              ),
              BoxShadow(
                color: Colors.white.withOpacity(0.8),
                offset: const Offset(-4, -4),
                blurRadius: 8,
              ),
            ],
          ),
          child: ListTile(
            contentPadding: const EdgeInsets.all(16),
            trailing: (pcoHandoverModel.shift == "Day")
                ? Column(
                    mainAxisAlignment: MainAxisAlignment.center,
                    children: [
                      const Icon(
                        Icons.light_mode,
                        size: 28,
                      ),
                      Text(pcoHandoverModel.shift.toString())
                    ],
                  )
                : Column(
                    mainAxisAlignment: MainAxisAlignment.center,
                    children: [
                      const Icon(
                        Icons.dark_mode,
                        size: 28,
                      ),
                      Text(pcoHandoverModel.shift.toString())
                    ],
                  ),
            title: Column(
              crossAxisAlignment: CrossAxisAlignment.start,
              children: [
                Row(
                  children: [
                    Text(
                      DateFormat().add_yMMMEd().format(DateTime.parse(
                          pcoHandoverModel.createdAt.toString())),
                      style: Theme.of(context).textTheme.labelMedium,
                    ),
                    const SizedBox(width: 10),
                    DivisionCard(
                      division: EnumToString.fromString(
                              Division.values, pcoHandoverModel.division)
                          as Division,
                    ),
                  ],
                ),
                const SizedBox(height: 8),
                Row(
                  mainAxisAlignment: MainAxisAlignment.spaceBetween,
                  children: [
                    Text(
                      "TrailNo : ${pcoHandoverModel.trailNo}",
                      style: Theme.of(context)
                          .textTheme
                          .bodyLarge!
                          .copyWith(fontWeight: FontWeight.bold),
                    ),
                    Text(
                      "Type of Items : ${pcoHandoverModel.pcoModels.length}",
                      style: Theme.of(context)
                          .textTheme
                          .bodyLarge!
                          .copyWith(fontWeight: FontWeight.bold),
                    ),
                    Text(
                      "Verify Items : ${pcoHandoverModel.pcoModels.fold(0, (previousValue, element) => (element.verify == true) ? previousValue + 1 : previousValue)}",
                      style: Theme.of(context)
                          .textTheme
                          .bodyLarge!
                          .copyWith(fontWeight: FontWeight.bold),
                    ),
                  ],
                ),
              ],
            ),
            // Using a Wrap for subtitle texts ensures responsiveness without altering your color choices.
            subtitle: Padding(
              padding: const EdgeInsets.only(top: 8.0),
              child: Wrap(
                spacing: 8,
                runSpacing: 4,
                children: [
                  Text(
                      "JC No : ${pcoHandoverModel.pcoModels[0].jcNo.toString()}",
                      style: Theme.of(context).textTheme.labelMedium),
                  Text(
                      "Mark No : ${pcoHandoverModel.pcoModels[0].markNo.toString()}",
                      style: Theme.of(context).textTheme.labelMedium),
                  Text(
                      "Section : ${pcoHandoverModel.pcoModels[0].section.toString()}",
                      style: Theme.of(context).textTheme.labelMedium),
                  Text(
                      "Thickness : ${pcoHandoverModel.pcoModels[0].thickness.toString()}",
                      style: Theme.of(context).textTheme.labelMedium),
                  Text(
                      "Length : ${pcoHandoverModel.pcoModels[0].length.toString()}",
                      style: Theme.of(context).textTheme.labelMedium),
                  Text(
                      "Quantity : ${pcoHandoverModel.pcoModels[0].quantity.toString()}",
                      style: Theme.of(context).textTheme.labelMedium),
                  Text(
                      "Weight : ${pcoHandoverModel.pcoModels[0].weight.toWeight()}",
                      style: Theme.of(context).textTheme.labelMedium),
                  Text(
                      "Total Weight : ${(pcoHandoverModel.pcoModels[0].quantity * pcoHandoverModel.pcoModels[0].weight).toWeight()}",
                      style: Theme.of(context).textTheme.labelMedium),
                  Text(
                      "Reject Quantity : ${pcoHandoverModel.pcoModels[0].rejectQuantity.toString()}",
                      style: Theme.of(context).textTheme.labelMedium),
                  Text(
                      "Reject Weight : ${pcoHandoverModel.pcoModels[0].rejectWeights!.toWeight()}",
                      style: Theme.of(context).textTheme.labelMedium),
                ],
              ),
            ),
          ),
        ),
      ),
    );
  }
}


3.




import 'package:enum_to_string/enum_to_string.dart';
import 'package:flutter/material.dart';
import 'package:flutter_riverpod/flutter_riverpod.dart';
import 'package:go_router/go_router.dart';
import 'package:intl/intl.dart';
import 'package:rrispat_app/src/constants/enums.dart';
import 'package:rrispat_app/src/core/utils.dart';
import 'package:rrispat_app/src/features/gi/domain/models/pco_handover_model.dart';
import 'package:rrispat_app/src/features/gi/domain/provider/all_pco_handover_provider.dart';

import '../../../../core/components/division_card.dart';
import 'verify_details_page.dart';

class VerifyHandOverPage extends ConsumerStatefulWidget {
  const VerifyHandOverPage({super.key});

  @override
  ConsumerState<ConsumerStatefulWidget> createState() =>
      _VerifyHandOverPageState();
}

class _VerifyHandOverPageState extends ConsumerState<VerifyHandOverPage> {
  List<PCOHandoverModel> pcoHandOverdata = [];
  @override
  Widget build(BuildContext context) {
    pcoHandOverdata.clear();
    ref
        .read(giAllPcoHandOverDataProvider.notifier)
        .getAllHandOver()
        .forEach((element) {
      pcoHandOverdata.add(element);
    });
    return Container(
      // decoration: BoxDecoration(
      //   gradient: LinearGradient(
      //     colors: [Colors.white, Colors.blue.shade50], // subtle gradient
      //     begin: Alignment.topCenter,
      //     end: Alignment.bottomCenter,
      //   ),
      // ),
      child: ListView.builder(
        padding: const EdgeInsets.symmetric(vertical: 10),
        itemCount: pcoHandOverdata.length,
        itemBuilder: (context, index) {
          return buildTransaction(pcoHandOverdata[index]);
        },
      ),
    );
  }

  Widget buildTransaction(PCOHandoverModel pcoHandoverModel) {
    return Padding(
      padding: const EdgeInsets.symmetric(horizontal: 10, vertical: 5),
      child: Card(
        elevation: 8,
        shape: RoundedRectangleBorder(
          borderRadius: BorderRadius.circular(12),
        ),
        child: InkWell(
          borderRadius: BorderRadius.circular(12),
          onTap: () => context.pushNamed(VerifyDetailsPage.routeName,
              pathParameters: {'id': pcoHandoverModel.id.toString()}),
          child: Padding(
            padding: const EdgeInsets.all(12.0),
            child: Column(
              children: [
                // Top row: Date, Division and Shift Icon/Label
                Row(
                  children: [
                    Text(
                      DateFormat().add_yMMMEd().format(DateTime.parse(
                          pcoHandoverModel.createdAt.toString())),
                      style: Theme.of(context).textTheme.labelMedium,
                    ),
                    const SizedBox(width: 10),
                    DivisionCard(
                      division: EnumToString.fromString(
                              Division.values, pcoHandoverModel.division)
                          as Division,
                    ),
                    const Spacer(),
                    Column(
                      children: [
                        Icon(
                          pcoHandoverModel.shift == "Day"
                              ? Icons.light_mode
                              : Icons.dark_mode,
                          size: 28,
                        ),
                        Text(
                          pcoHandoverModel.shift.toString(),
                          style: Theme.of(context).textTheme.bodySmall,
                        ),
                      ],
                    ),
                  ],
                ),
                const SizedBox(height: 10),
                // Middle row: TrailNo, Type of Items and Verify Items count
                Row(
                  mainAxisAlignment: MainAxisAlignment.spaceBetween,
                  children: [
                    Text(
                      "TrailNo : ${pcoHandoverModel.trailNo}",
                      style: Theme.of(context)
                          .textTheme
                          .bodyLarge!
                          .copyWith(fontWeight: FontWeight.bold),
                    ),
                    Text(
                      "Type of Items : ${pcoHandoverModel.pcoModels.length}",
                      style: Theme.of(context)
                          .textTheme
                          .bodyLarge!
                          .copyWith(fontWeight: FontWeight.bold),
                    ),
                    Text(
                      "Verify Items : ${pcoHandoverModel.pcoModels.fold(0, (previousValue, element) => (element.verify == true) ? previousValue + 1 : previousValue)}",
                      style: Theme.of(context)
                          .textTheme
                          .bodyLarge!
                          .copyWith(fontWeight: FontWeight.bold),
                    ),
                  ],
                ),
                const SizedBox(height: 10),
                // Conditionally display the details only if there is at least one model
                if (pcoHandoverModel.pcoModels.length <= 1)
                  Wrap(
                    spacing: 10,
                    runSpacing: 5,
                    children: [
                      Text("JC No : ${pcoHandoverModel.pcoModels[0].jcNo}",
                          style: Theme.of(context).textTheme.labelMedium),
                      Text("Mark No : ${pcoHandoverModel.pcoModels[0].markNo}",
                          style: Theme.of(context).textTheme.labelMedium),
                      Text("Section : ${pcoHandoverModel.pcoModels[0].section}",
                          style: Theme.of(context).textTheme.labelMedium),
                      Text(
                          "Thickness : ${pcoHandoverModel.pcoModels[0].thickness}",
                          style: Theme.of(context).textTheme.labelMedium),
                      Text("Length : ${pcoHandoverModel.pcoModels[0].length}",
                          style: Theme.of(context).textTheme.labelMedium),
                      Text(
                          "Quantity : ${pcoHandoverModel.pcoModels[0].quantity}",
                          style: Theme.of(context).textTheme.labelMedium),
                      Text(
                          "Weight : ${pcoHandoverModel.pcoModels[0].weight.toWeight()}",
                          style: Theme.of(context).textTheme.labelMedium),
                      Text(
                          "Total Weight : ${(pcoHandoverModel.pcoModels[0].quantity * pcoHandoverModel.pcoModels[0].weight).toWeight()}",
                          style: Theme.of(context).textTheme.labelMedium),
                      Text(
                          "Reject Quantity : ${pcoHandoverModel.pcoModels[0].rejectQuantity}",
                          style: Theme.of(context).textTheme.labelMedium),
                      Text(
                          "Reject Weight : ${pcoHandoverModel.pcoModels[0].rejectWeights!.toWeight()}",
                          style: Theme.of(context).textTheme.labelMedium),
                    ],
                  ),
              ],
            ),
          ),
        ),
      ),
    );
  }
}


Set identity_insert ma_table on

-- on ajoute les items

set identity_insert ma_table off
import 'dart:async';
import 'dart:developer';
import 'dart:io';
import 'dart:math';
import 'package:collection/collection.dart';
import 'package:excel/excel.dart' as exc;
import 'package:file_picker/file_picker.dart';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:flutter_riverpod/flutter_riverpod.dart';
import 'package:go_router/go_router.dart';
import 'package:rrispat_app/src/features/store/domain/models/store_user_model.dart';
import 'package:rrispat_app/src/shared/providers/providers.dart';
import '../../../../../l10n/app_localizations.dart';
import '../../../../shared/widgets/loader_widget.dart';
import '../../../../shared/widgets/rr_filled_button.dart';
import '../../../auth/controllers/auth_controller.dart';
import '../../../auth/domains/models/auth_model.dart';
import '../../../auth/domains/providers/auth_model_provider.dart';
import '../../controller/store_item_controller.dart';
import '../../controller/store_user_controller.dart';
import '../../domain/models/store_item_model.dart';
import '../../domain/store_enums.dart';

class StoreAddStock extends ConsumerStatefulWidget {
  const StoreAddStock({Key? key}) : super(key: key);

  @override
  ConsumerState<StoreAddStock> createState() => _StoreAddStockState();
}

class _StoreAddStockState extends ConsumerState<StoreAddStock> {
  final GlobalKey<FormState> _pieces = GlobalKey<FormState>();

  bool _showLoading = true;

  final TextEditingController _itemNameController = TextEditingController();
  final TextEditingController _poNumberController = TextEditingController();

  final TextEditingController pieces = TextEditingController();

  StoreUserModel? storeUser;
  List<StoreItemModel> storeItemListfromBe = [];
  List<AuthModel> authModels = [];
  double screenWidth = 0;

  PaginationParams _paginationParams = PaginationParams(
    page: 1,
    pageSize: 10,
    totalPages: 0,
    itemName: '',
    poNumber: '',
  );

  int _totalItems = 0;

  @override
  void initState() {
    super.initState();

    Timer(const Duration(seconds: 90), () {
      if (mounted) {
        setState(() {
          _showLoading = false;
        });
      }
    });
  }

  Future<void> uploadExcelDataFromWebStoreStockAdd(BuildContext context) async {
    FilePickerResult? file = await FilePicker.platform.pickFiles(
      type: FileType.custom,
      allowedExtensions: ['xlsx'],
      allowMultiple: false,
    );
    if (file != null) {
      List<StoreItemModel> tempList = [];
      Uint8List fileBytes = file.files.first.bytes!;
      var excel = exc.Excel.decodeBytes(fileBytes);
      for (var table in excel.tables.keys) {
        for (var row in excel.tables[table]!.rows) {
          if (row[0]?.value.toString() == "Company Name") continue;
          try {
            StoreItemModel storeItemModel = StoreItemModel(
              id: '',
              itemName: (row[4]?.value).toString(),
              vendorName: (row[1]?.value).toString(),
              pieces: double.parse((row[6]?.value).toString()),
              issuedPcs: double.parse(0.toString()),
              createdAt: DateTime.now(),
              createdBy: ref.read(authModelProvider)!.uid,
              itemCode: (row[3]?.value).toString(),
              poNumber: (row[8]?.value).toString(),
              unit: (row[5]?.value).toString(),
              issuedCompleted: double.parse(0.toString()),
              sapItemCode: '',
              plantName: (row[10]?.value).toString(),
              poDate: (row[11]?.value).toString(),
              status: StoreItemStatus.approved,
              type: StoreItemCreatedType.normal,
              remark: '',
            );
            tempList.add(storeItemModel);
          } catch (e) {
            print("$e store item error getFile");
          }
        }
      }
      for (var element in tempList) {
        ref
            .read(storeItemControllerProvider)
            .createStoreItemStock(ref, element);
      }
    }
  }

  Widget buildFilters(BuildContext context) {
    final double screenWidth = MediaQuery.of(context).size.width;
    if (screenWidth < 600) {
      return Column(
        crossAxisAlignment: CrossAxisAlignment.stretch,
        children: [
          TextFormField(
            controller: _itemNameController,
            decoration: InputDecoration(
              labelText: "Filter by Item Name",
              border:
                  OutlineInputBorder(borderRadius: BorderRadius.circular(10)),
            ),
            onChanged: (value) {
              setState(() {
                _paginationParams = PaginationParams(
                  page: 1,
                  pageSize: _paginationParams.pageSize,
                  totalPages: _paginationParams.totalPages,
                  itemName: value,
                  poNumber: _poNumberController.text,
                );
              });
            },
          ),
          const SizedBox(height: 10),
          TextFormField(
            controller: _poNumberController,
            decoration: InputDecoration(
              labelText: "Filter by PO Number",
              border:
                  OutlineInputBorder(borderRadius: BorderRadius.circular(10)),
            ),
            onChanged: (value) {
              setState(() {
                _paginationParams = PaginationParams(
                  page: 1,
                  pageSize: _paginationParams.pageSize,
                  totalPages: _paginationParams.totalPages,
                  itemName: _itemNameController.text,
                  poNumber: value,
                );
              });
            },
          ),
          const SizedBox(height: 10),
        ],
      );
    } else {
      return Row(
        children: [
          Expanded(
            child: TextFormField(
              controller: _itemNameController,
              decoration: InputDecoration(
                labelText: "Filter by Item Name",
                border:
                    OutlineInputBorder(borderRadius: BorderRadius.circular(10)),
              ),
              onChanged: (value) {
                setState(() {
                  _paginationParams = PaginationParams(
                    page: 1,
                    pageSize: _paginationParams.pageSize,
                    totalPages: _paginationParams.totalPages,
                    itemName: value,
                    poNumber: _poNumberController.text,
                  );
                });
              },
            ),
          ),
          const SizedBox(width: 10),
          Expanded(
            child: TextFormField(
              controller: _poNumberController,
              decoration: InputDecoration(
                labelText: "Filter by PO Number",
                border:
                    OutlineInputBorder(borderRadius: BorderRadius.circular(10)),
              ),
              onChanged: (value) {
                setState(() {
                  _paginationParams = PaginationParams(
                    page: 1,
                    pageSize: _paginationParams.pageSize,
                    totalPages: _paginationParams.totalPages,
                    itemName: _itemNameController.text,
                    poNumber: value,
                  );
                });
              },
            ),
          ),
        ],
      );
    }
  }

  @override
  Widget build(BuildContext context) {
    screenWidth = MediaQuery.of(context).size.width;

    ref
        .watch(authUserListStreamProvider)
        .whenData((value) => authModels = value);
    ref.watch(storeUserStreamProvider).whenData((value) => storeUser = value);

    return Scaffold(
      appBar: AppBar(
        title: Text('PO - Stock Add'),
        centerTitle: true,
      ),
      body: Padding(
        padding: const EdgeInsets.all(10),
        child: Column(
          children: [
            if (storeUser != null &&
                storeUser!.userType.contains(StoreUserType.poListUpload))
              Center(
                child: RrFilledButton(
                  onPressed: () {
                    uploadExcelDataFromWebStoreStockAdd(context);
                  },
                  label: ('Store Item Excel File Upload'),
                ),
              ),
            const SizedBox(height: 20),
            buildFilters(context),
            const SizedBox(height: 10),
            Expanded(
              child: ref
                  .watch(storeItemStockListWithPaginationStreamProvider(
                      _paginationParams))
                  .when(
                    data: (paginatedData) {
                      _totalItems = paginatedData.totalItems;
                      _paginationParams = PaginationParams(
                        page: _paginationParams.page,
                        pageSize: _paginationParams.pageSize,
                        totalPages: paginatedData.totalPages,
                        itemName: _itemNameController.text,
                        poNumber: _poNumberController.text,
                      );
                      if (paginatedData.storeItemStocks.isEmpty) {
                        return _showLoading
                            ? const Padding(
                                padding: EdgeInsets.all(16.0),
                                child:
                                    Center(child: CircularProgressIndicator()),
                              )
                            : const Padding(
                                padding: EdgeInsets.all(16.0),
                                child:
                                    Center(child: Text("No Stock Item Found")),
                              );
                      } else {
                        return ListView.builder(
                          itemCount: paginatedData.storeItemStocks.length,
                          itemBuilder: (context, index) {
                            return addStockCard(
                                context, paginatedData.storeItemStocks[index]);
                          },
                        );
                      }
                    },
                    error: (error, stack) =>
                        Center(child: Text(error.toString())),
                    loading: () =>
                        const Center(child: CircularProgressIndicator()),
                  ),
            ),
            _buildPageNumbers(
                computedTotalPages: _paginationParams.totalPages ?? 1),
          ],
        ),
      ),
    );
  }

  Widget _buildPageNumbers({required int computedTotalPages}) {
    int totalVisiblePages = 5;
    List<Widget> pageButtons = [];
    int startPage = max(1, _paginationParams.page - totalVisiblePages ~/ 2);
    int endPage = min(computedTotalPages, startPage + totalVisiblePages - 1);
    if (endPage - startPage < totalVisiblePages - 1) {
      startPage = max(1, endPage - totalVisiblePages + 1);
    }
    if (startPage > 1) {
      pageButtons.add(_pageButton(1, 'First'));
    }
    for (int i = startPage; i <= endPage; i++) {
      pageButtons.add(_pageButton(i, '$i'));
    }
    if (endPage < computedTotalPages) {
      pageButtons.add(_pageButton(computedTotalPages, 'Last'));
    }
    return Wrap(
      alignment: WrapAlignment.center,
      children: pageButtons,
    );
  }

  Widget _pageButton(int pageNumber, String text) {
    return Padding(
      padding: const EdgeInsets.all(2.0),
      child: InkWell(
        onTap: () => _changePage(pageNumber),
        child: Padding(
          padding: const EdgeInsets.all(10.0),
          child: Text(
            text,
            style: TextStyle(
              color: pageNumber == _paginationParams.page
                  ? Theme.of(context).colorScheme.primary
                  : Colors.grey,
            ),
          ),
        ),
      ),
    );
  }

  void _changePage(int page) {
    if (page != _paginationParams.page) {
      setState(() {
        _paginationParams = PaginationParams(
          page: page,
          pageSize: _paginationParams.pageSize,
          totalPages: _paginationParams.totalPages,
          itemName: _itemNameController.text,
          poNumber: _poNumberController.text,
        );
      });
    }
  }

  Widget addStockCard(BuildContext context, StoreItemModel storeItemModel) {
    bool isClosed = storeItemModel.issuedPcs != 0;
    AuthModel closedByPerson = authModels.firstWhere(
      (element) => element.uid == storeItemModel.createdBy,
    );
    return Padding(
      padding: const EdgeInsets.symmetric(vertical: 2, horizontal: 5),
      child: Card(
        color: Theme.of(context).colorScheme.background,
        child: ListTile(
          leading: Container(
            width: 40,
            height: 40,
            decoration: BoxDecoration(
              color: Theme.of(context).colorScheme.tertiary,
              shape: BoxShape.circle,
            ),
            alignment: Alignment.center,
            child: Text(
              storeItemModel.pieces.toStringAsFixed(2),
              style: Theme.of(context)
                  .textTheme
                  .titleMedium
                  ?.copyWith(color: Colors.white, fontSize: 9),
              textAlign: TextAlign.center,
            ),
          ),
          title: Text(
            storeItemModel.itemName.toUpperCase(),
            style: Theme.of(context).textTheme.titleLarge,
          ),
          subtitle: Wrap(
            spacing: 20,
            children: [
              Row(
                mainAxisSize: MainAxisSize.min,
                children: [
                  Text(
                    "Pieces: ",
                    style: TextStyle(
                      color: Theme.of(context).colorScheme.primary,
                    ),
                  ),
                  Text(storeItemModel.pieces.toStringAsFixed(2)),
                  Text(" ${storeItemModel.unit.toString()}"),
                ],
              ),
              Row(
                mainAxisSize: MainAxisSize.min,
                children: [
                  Text(
                    "${AppLocalizations.of(context).translate('Vendor Name')}: ",
                    style: TextStyle(
                      color: Theme.of(context).colorScheme.primary,
                    ),
                  ),
                  Text(storeItemModel.vendorName),
                ],
              ),
              Row(
                mainAxisSize: MainAxisSize.min,
                children: [
                  Text(
                    "SAP Item Code: ",
                    style: TextStyle(
                      color: Theme.of(context).colorScheme.primary,
                    ),
                  ),
                  Text(storeItemModel.itemCode),
                ],
              ),
              Row(
                mainAxisSize: MainAxisSize.min,
                children: [
                  Text(
                    "Plant Name: ",
                    style: TextStyle(
                      color: Theme.of(context).colorScheme.primary,
                    ),
                  ),
                  Text(storeItemModel.plantName),
                ],
              ),
              Row(
                mainAxisSize: MainAxisSize.min,
                children: [
                  Text(
                    "PO Created Date: ",
                    style: TextStyle(
                      color: Theme.of(context).colorScheme.primary,
                    ),
                  ),
                  Text(storeItemModel.poDate),
                ],
              ),
              Row(
                mainAxisSize: MainAxisSize.min,
                children: [
                  Text(
                    "PO Number: ",
                    style: TextStyle(
                      color: Theme.of(context).colorScheme.primary,
                    ),
                  ),
                  Text(storeItemModel.poNumber),
                ],
              ),
              Row(
                mainAxisSize: MainAxisSize.min,
                children: [
                  Text(
                    "${AppLocalizations.of(context).translate('Created At')}: ",
                    style: TextStyle(
                      color: Theme.of(context).colorScheme.primary,
                    ),
                  ),
                  Text(
                    ref
                        .read(dateFormatterProvider)
                        .format(storeItemModel.createdAt),
                  ),
                ],
              ),
              screenWidth <= 500
                  ? (isClosed)
                      ? Row(
                          mainAxisSize: MainAxisSize.min,
                          children: [
                            Text(
                              "Closed By : ${closedByPerson.fullName}",
                              style: TextStyle(
                                color: Theme.of(context).colorScheme.tertiary,
                              ),
                            ),
                          ],
                        )
                      : Row(
                          mainAxisAlignment: MainAxisAlignment.center,
                          children: [
                            buildIconButton(
                              Icons.done_all_rounded,
                              AppLocalizations.of(context).translate('Approve'),
                              () {
                                addStockModel(storeItemModel);
                              },
                            ),
                            const SizedBox(width: 20),
                            buildIconButton(
                              Icons.close_rounded,
                              'Close',
                              () {
                                partiallyCloseStockModel(storeItemModel);
                              },
                            ),
                          ],
                        )
                  : const SizedBox.shrink(),
            ],
          ),
          trailing: screenWidth > 500
              ? (isClosed)
                  ? Wrap(
                      children: [
                        Text(
                          "Closed By : ${closedByPerson.fullName}",
                          style: TextStyle(
                            color: Theme.of(context).colorScheme.tertiary,
                          ),
                        ),
                      ],
                    )
                  : Wrap(
                      children: [
                        buildIconButton(
                          Icons.done_all_rounded,
                          AppLocalizations.of(context).translate('Approve'),
                          () {
                            addStockModel(storeItemModel);
                          },
                        ),
                        const SizedBox(width: 20),
                        buildIconButton(
                          Icons.close_rounded,
                          'Close',
                          () {
                            partiallyCloseStockModel(storeItemModel);
                          },
                        ),
                      ],
                    )
              : null,
        ),
      ),
    );
  }

  Widget buildIconButton(
      IconData icon, String tooltip, void Function() onPressed) {
    return Tooltip(
      message: tooltip,
      child: IconButton(
        onPressed: onPressed,
        icon: Icon(
          icon,
          color: Theme.of(context).colorScheme.tertiary,
        ),
      ),
    );
  }

  void partiallyCloseStockModel(StoreItemModel storeItemModel) {
    try {
      showDialog(
        barrierDismissible: false,
        context: context,
        builder: (context) {
          return AlertDialog(
            title: Center(
              child: Text(
                "Verify",
                style: Theme.of(context).textTheme.bodyLarge,
              ),
            ),
            content: const SizedBox(
              height: 80,
              child: Center(
                child: Column(
                  children: [
                    Text('Are you sure you want to close this stock item?'),
                    SizedBox(height: 5),
                  ],
                ),
              ),
            ),
            actions: <Widget>[
              TextButton(
                child: const Text('Cancel'),
                onPressed: () {
                  context.pop(true);
                },
              ),
              ElevatedButton(
                child: const Text('Close'),
                onPressed: () async {
                  String closedBy = ref.read(authModelProvider)!.uid;
                  ref.read(storeItemControllerProvider).updateStoreItemStock(
                      ref, storeItemModel, storeItemModel.pieces, closedBy);
                  context.pop(true);
                  ref.invalidate(
                      storeItemStockListWithPaginationStreamProvider);
                },
              )
            ],
          );
        },
      );
    } catch (e) {
      print(e.toString());
    }
  }

  void addStockModel(StoreItemModel storeItemModel) {
    try {
      showDialog(
        barrierDismissible: false,
        context: context,
        builder: (context) {
          return AlertDialog(
            title: Center(
              child: Text(
                "Verify",
                style: Theme.of(context).textTheme.bodyLarge,
              ),
            ),
            content: SizedBox(
              height: 180,
              child: Center(
                child: Column(
                  children: [
                    Text('Item Name : ${storeItemModel.itemName}'),
                    const SizedBox(height: 5),
                    Text(
                        'Total pcs. in Po list : ${storeItemModel.pieces} ${storeItemModel.unit}'),
                    const SizedBox(height: 10),
                    Form(
                      key: _pieces,
                      child: TextFormField(
                        validator: (text) {
                          if (text == null ||
                              text.isEmpty ||
                              double.parse(text) < 1) {
                            return 'Please enter Pieces to add';
                          }
                          if (double.parse(text) >
                              (storeItemModel.pieces +
                                  (storeItemModel.pieces * 0.1))) {
                            return 'Pcs should not be greater than available stock';
                          }
                          return null;
                        },
                        controller: pieces,
                        keyboardType: TextInputType.number,
                        textCapitalization: TextCapitalization.words,
                        decoration: InputDecoration(
                          labelText: "Pieces",
                          hintText: "Enter Pieces",
                          border: OutlineInputBorder(
                            borderRadius: BorderRadius.circular(10),
                          ),
                        ),
                      ),
                    ),
                    const SizedBox(height: 5),
                  ],
                ),
              ),
            ),
            actions: <Widget>[
              TextButton(
                child: const Text('Cancel'),
                onPressed: () {
                  context.pop(true);
                },
              ),
              ElevatedButton(
                child: const Text('OK'),
                onPressed: () async {
                  if (_pieces.currentState!.validate()) {
                    double pcs = double.parse(pieces.text);
                    String updateBy = ref.read(authModelProvider)!.uid;
                    ref
                        .read(storeItemControllerProvider)
                        .updateStoreItem(ref, storeItemModel, pcs, updateBy);
                    context.pop(true);
                    pieces.clear();
                    _itemNameController.clear();
                    _poNumberController.clear();
                    ref.invalidate(
                        storeItemStockListWithPaginationStreamProvider);
                    _pieces.currentState?.reset();
                  }
                },
              )
            ],
          );
        },
      );
    } catch (e) {
      print(e.toString());
    }
  }
}
import 'dart:async';
import 'dart:developer';
import 'dart:io';
import 'dart:math';
import 'package:collection/collection.dart';
import 'package:excel/excel.dart' as exc;
import 'package:file_picker/file_picker.dart';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:flutter_riverpod/flutter_riverpod.dart';
import 'package:go_router/go_router.dart';
import 'package:rrispat_app/src/features/store/domain/models/store_user_model.dart';
import 'package:rrispat_app/src/shared/providers/providers.dart';
import '../../../../../l10n/app_localizations.dart';
import '../../../../shared/widgets/loader_widget.dart';
import '../../../../shared/widgets/rr_filled_button.dart';
import '../../../auth/controllers/auth_controller.dart';
import '../../../auth/domains/models/auth_model.dart';
import '../../../auth/domains/providers/auth_model_provider.dart';
import '../../controller/store_item_controller.dart';
import '../../controller/store_user_controller.dart';
import '../../domain/models/store_item_model.dart';
import '../../domain/store_enums.dart';

class StoreAddStock extends ConsumerStatefulWidget {
  const StoreAddStock({Key? key}) : super(key: key);

  @override
  ConsumerState<StoreAddStock> createState() => _StoreAddStockState();
}

class _StoreAddStockState extends ConsumerState<StoreAddStock> {
  final GlobalKey<FormState> _pieces = GlobalKey<FormState>();

  bool _showLoading = true;

  final TextEditingController _itemNameController = TextEditingController();
  final TextEditingController _poNumberController = TextEditingController();

  final TextEditingController pieces = TextEditingController();

  StoreUserModel? storeUser;
  List<StoreItemModel> storeItemListfromBe = [];
  List<AuthModel> authModels = [];
  double screenWidth = 0;

  PaginationParams _paginationParams = PaginationParams(
    page: 1,
    pageSize: 10,
    totalPages: 0,
    itemName: '',
    poNumber: '',
  );

  int _totalItems = 0;

  @override
  void initState() {
    super.initState();

    Timer(const Duration(seconds: 90), () {
      if (mounted) {
        setState(() {
          _showLoading = false;
        });
      }
    });
  }

  Future<void> uploadExcelDataFromWebStoreStockAdd(BuildContext context) async {
    FilePickerResult? file = await FilePicker.platform.pickFiles(
      type: FileType.custom,
      allowedExtensions: ['xlsx'],
      allowMultiple: false,
    );
    if (file != null) {
      List<StoreItemModel> tempList = [];
      Uint8List fileBytes = file.files.first.bytes!;
      var excel = exc.Excel.decodeBytes(fileBytes);
      for (var table in excel.tables.keys) {
        for (var row in excel.tables[table]!.rows) {
          if (row[0]?.value.toString() == "Company Name") continue;
          try {
            StoreItemModel storeItemModel = StoreItemModel(
              id: '',
              itemName: (row[4]?.value).toString(),
              vendorName: (row[1]?.value).toString(),
              pieces: double.parse((row[6]?.value).toString()),
              issuedPcs: double.parse(0.toString()),
              createdAt: DateTime.now(),
              createdBy: ref.read(authModelProvider)!.uid,
              itemCode: (row[3]?.value).toString(),
              poNumber: (row[8]?.value).toString(),
              unit: (row[5]?.value).toString(),
              issuedCompleted: double.parse(0.toString()),
              sapItemCode: '',
              plantName: (row[10]?.value).toString(),
              poDate: (row[11]?.value).toString(),
              status: StoreItemStatus.approved,
              type: StoreItemCreatedType.normal,
              remark: '',
            );
            tempList.add(storeItemModel);
          } catch (e) {
            print("$e store item error getFile");
          }
        }
      }
      for (var element in tempList) {
        ref
            .read(storeItemControllerProvider)
            .createStoreItemStock(ref, element);
      }
    }
  }

  Widget buildFilters(BuildContext context) {
    final double screenWidth = MediaQuery.of(context).size.width;
    if (screenWidth < 600) {
      return Column(
        crossAxisAlignment: CrossAxisAlignment.stretch,
        children: [
          TextFormField(
            controller: _itemNameController,
            decoration: InputDecoration(
              labelText: "Filter by Item Name",
              border:
                  OutlineInputBorder(borderRadius: BorderRadius.circular(10)),
            ),
            onChanged: (value) {
              setState(() {
                _paginationParams = PaginationParams(
                  page: 1,
                  pageSize: _paginationParams.pageSize,
                  totalPages: _paginationParams.totalPages,
                  itemName: value,
                  poNumber: _poNumberController.text,
                );
              });
            },
          ),
          const SizedBox(height: 10),
          TextFormField(
            controller: _poNumberController,
            decoration: InputDecoration(
              labelText: "Filter by PO Number",
              border:
                  OutlineInputBorder(borderRadius: BorderRadius.circular(10)),
            ),
            onChanged: (value) {
              setState(() {
                _paginationParams = PaginationParams(
                  page: 1,
                  pageSize: _paginationParams.pageSize,
                  totalPages: _paginationParams.totalPages,
                  itemName: _itemNameController.text,
                  poNumber: value,
                );
              });
            },
          ),
          const SizedBox(height: 10),
        ],
      );
    } else {
      return Row(
        children: [
          Expanded(
            child: TextFormField(
              controller: _itemNameController,
              decoration: InputDecoration(
                labelText: "Filter by Item Name",
                border:
                    OutlineInputBorder(borderRadius: BorderRadius.circular(10)),
              ),
              onChanged: (value) {
                setState(() {
                  _paginationParams = PaginationParams(
                    page: 1,
                    pageSize: _paginationParams.pageSize,
                    totalPages: _paginationParams.totalPages,
                    itemName: value,
                    poNumber: _poNumberController.text,
                  );
                });
              },
            ),
          ),
          const SizedBox(width: 10),
          Expanded(
            child: TextFormField(
              controller: _poNumberController,
              decoration: InputDecoration(
                labelText: "Filter by PO Number",
                border:
                    OutlineInputBorder(borderRadius: BorderRadius.circular(10)),
              ),
              onChanged: (value) {
                setState(() {
                  _paginationParams = PaginationParams(
                    page: 1,
                    pageSize: _paginationParams.pageSize,
                    totalPages: _paginationParams.totalPages,
                    itemName: _itemNameController.text,
                    poNumber: value,
                  );
                });
              },
            ),
          ),
        ],
      );
    }
  }

  @override
  Widget build(BuildContext context) {
    screenWidth = MediaQuery.of(context).size.width;

    ref
        .watch(authUserListStreamProvider)
        .whenData((value) => authModels = value);
    ref.watch(storeUserStreamProvider).whenData((value) => storeUser = value);

    return Scaffold(
      appBar: AppBar(
        title: Text('PO - Stock Add'),
        centerTitle: true,
      ),
      body: Padding(
        padding: const EdgeInsets.all(10),
        child: Column(
          children: [
            if (storeUser != null &&
                storeUser!.userType.contains(StoreUserType.poListUpload))
              Center(
                child: RrFilledButton(
                  onPressed: () {
                    uploadExcelDataFromWebStoreStockAdd(context);
                  },
                  label: ('Store Item Excel File Upload'),
                ),
              ),
            const SizedBox(height: 20),
            buildFilters(context),
            const SizedBox(height: 10),
            Expanded(
              child: ref
                  .watch(storeItemStockListWithPaginationStreamProvider(
                      _paginationParams))
                  .when(
                    data: (paginatedData) {
                      _totalItems = paginatedData.totalItems;
                      _paginationParams = PaginationParams(
                        page: _paginationParams.page,
                        pageSize: _paginationParams.pageSize,
                        totalPages: paginatedData.totalPages,
                        itemName: _itemNameController.text,
                        poNumber: _poNumberController.text,
                      );
                      if (paginatedData.storeItemStocks.isEmpty) {
                        return _showLoading
                            ? const Padding(
                                padding: EdgeInsets.all(16.0),
                                child:
                                    Center(child: CircularProgressIndicator()),
                              )
                            : const Padding(
                                padding: EdgeInsets.all(16.0),
                                child:
                                    Center(child: Text("No Stock Item Found")),
                              );
                      } else {
                        return ListView.builder(
                          itemCount: paginatedData.storeItemStocks.length,
                          itemBuilder: (context, index) {
                            return addStockCard(
                                context, paginatedData.storeItemStocks[index]);
                          },
                        );
                      }
                    },
                    error: (error, stack) =>
                        Center(child: Text(error.toString())),
                    loading: () =>
                        const Center(child: CircularProgressIndicator()),
                  ),
            ),
            _buildPageNumbers(
                computedTotalPages: _paginationParams.totalPages ?? 1),
          ],
        ),
      ),
    );
  }

  Widget _buildPageNumbers({required int computedTotalPages}) {
    int totalVisiblePages = 5;
    List<Widget> pageButtons = [];
    int startPage = max(1, _paginationParams.page - totalVisiblePages ~/ 2);
    int endPage = min(computedTotalPages, startPage + totalVisiblePages - 1);
    if (endPage - startPage < totalVisiblePages - 1) {
      startPage = max(1, endPage - totalVisiblePages + 1);
    }
    if (startPage > 1) {
      pageButtons.add(_pageButton(1, 'First'));
    }
    for (int i = startPage; i <= endPage; i++) {
      pageButtons.add(_pageButton(i, '$i'));
    }
    if (endPage < computedTotalPages) {
      pageButtons.add(_pageButton(computedTotalPages, 'Last'));
    }
    return Wrap(
      alignment: WrapAlignment.center,
      children: pageButtons,
    );
  }

  Widget _pageButton(int pageNumber, String text) {
    return Padding(
      padding: const EdgeInsets.all(2.0),
      child: InkWell(
        onTap: () => _changePage(pageNumber),
        child: Padding(
          padding: const EdgeInsets.all(10.0),
          child: Text(
            text,
            style: TextStyle(
              color: pageNumber == _paginationParams.page
                  ? Theme.of(context).colorScheme.primary
                  : Colors.grey,
            ),
          ),
        ),
      ),
    );
  }

  void _changePage(int page) {
    if (page != _paginationParams.page) {
      setState(() {
        _paginationParams = PaginationParams(
          page: page,
          pageSize: _paginationParams.pageSize,
          totalPages: _paginationParams.totalPages,
          itemName: _itemNameController.text,
          poNumber: _poNumberController.text,
        );
      });
    }
  }

  Widget addStockCard(BuildContext context, StoreItemModel storeItemModel) {
    bool isClosed = storeItemModel.issuedPcs != 0;
    AuthModel closedByPerson = authModels.firstWhere(
      (element) => element.uid == storeItemModel.createdBy,
    );
    return Padding(
      padding: const EdgeInsets.symmetric(vertical: 2, horizontal: 5),
      child: Card(
        color: Theme.of(context).colorScheme.background,
        child: ListTile(
          leading: Container(
            width: 40,
            height: 40,
            decoration: BoxDecoration(
              color: Theme.of(context).colorScheme.tertiary,
              shape: BoxShape.circle,
            ),
            alignment: Alignment.center,
            child: Text(
              storeItemModel.pieces.toStringAsFixed(2),
              style: Theme.of(context)
                  .textTheme
                  .titleMedium
                  ?.copyWith(color: Colors.white, fontSize: 9),
              textAlign: TextAlign.center,
            ),
          ),
          title: Text(
            storeItemModel.itemName.toUpperCase(),
            style: Theme.of(context).textTheme.titleLarge,
          ),
          subtitle: Wrap(
            spacing: 20,
            children: [
              Row(
                mainAxisSize: MainAxisSize.min,
                children: [
                  Text(
                    "Pieces: ",
                    style: TextStyle(
                      color: Theme.of(context).colorScheme.primary,
                    ),
                  ),
                  Text(storeItemModel.pieces.toStringAsFixed(2)),
                  Text(" ${storeItemModel.unit.toString()}"),
                ],
              ),
              Row(
                mainAxisSize: MainAxisSize.min,
                children: [
                  Text(
                    "${AppLocalizations.of(context).translate('Vendor Name')}: ",
                    style: TextStyle(
                      color: Theme.of(context).colorScheme.primary,
                    ),
                  ),
                  Text(storeItemModel.vendorName),
                ],
              ),
              Row(
                mainAxisSize: MainAxisSize.min,
                children: [
                  Text(
                    "SAP Item Code: ",
                    style: TextStyle(
                      color: Theme.of(context).colorScheme.primary,
                    ),
                  ),
                  Text(storeItemModel.itemCode),
                ],
              ),
              Row(
                mainAxisSize: MainAxisSize.min,
                children: [
                  Text(
                    "Plant Name: ",
                    style: TextStyle(
                      color: Theme.of(context).colorScheme.primary,
                    ),
                  ),
                  Text(storeItemModel.plantName),
                ],
              ),
              Row(
                mainAxisSize: MainAxisSize.min,
                children: [
                  Text(
                    "PO Created Date: ",
                    style: TextStyle(
                      color: Theme.of(context).colorScheme.primary,
                    ),
                  ),
                  Text(storeItemModel.poDate),
                ],
              ),
              Row(
                mainAxisSize: MainAxisSize.min,
                children: [
                  Text(
                    "PO Number: ",
                    style: TextStyle(
                      color: Theme.of(context).colorScheme.primary,
                    ),
                  ),
                  Text(storeItemModel.poNumber),
                ],
              ),
              Row(
                mainAxisSize: MainAxisSize.min,
                children: [
                  Text(
                    "${AppLocalizations.of(context).translate('Created At')}: ",
                    style: TextStyle(
                      color: Theme.of(context).colorScheme.primary,
                    ),
                  ),
                  Text(
                    ref
                        .read(dateFormatterProvider)
                        .format(storeItemModel.createdAt),
                  ),
                ],
              ),
              screenWidth <= 500
                  ? (isClosed)
                      ? Row(
                          mainAxisSize: MainAxisSize.min,
                          children: [
                            Text(
                              "Closed By : ${closedByPerson.fullName}",
                              style: TextStyle(
                                color: Theme.of(context).colorScheme.tertiary,
                              ),
                            ),
                          ],
                        )
                      : Row(
                          mainAxisAlignment: MainAxisAlignment.center,
                          children: [
                            buildIconButton(
                              Icons.done_all_rounded,
                              AppLocalizations.of(context).translate('Approve'),
                              () {
                                addStockModel(storeItemModel);
                              },
                            ),
                            const SizedBox(width: 20),
                            buildIconButton(
                              Icons.close_rounded,
                              'Close',
                              () {
                                partiallyCloseStockModel(storeItemModel);
                              },
                            ),
                          ],
                        )
                  : const SizedBox.shrink(),
            ],
          ),
          trailing: screenWidth > 500
              ? (isClosed)
                  ? Wrap(
                      children: [
                        Text(
                          "Closed By : ${closedByPerson.fullName}",
                          style: TextStyle(
                            color: Theme.of(context).colorScheme.tertiary,
                          ),
                        ),
                      ],
                    )
                  : Wrap(
                      children: [
                        buildIconButton(
                          Icons.done_all_rounded,
                          AppLocalizations.of(context).translate('Approve'),
                          () {
                            addStockModel(storeItemModel);
                          },
                        ),
                        const SizedBox(width: 20),
                        buildIconButton(
                          Icons.close_rounded,
                          'Close',
                          () {
                            partiallyCloseStockModel(storeItemModel);
                          },
                        ),
                      ],
                    )
              : null,
        ),
      ),
    );
  }

  Widget buildIconButton(
      IconData icon, String tooltip, void Function() onPressed) {
    return Tooltip(
      message: tooltip,
      child: IconButton(
        onPressed: onPressed,
        icon: Icon(
          icon,
          color: Theme.of(context).colorScheme.tertiary,
        ),
      ),
    );
  }

  void partiallyCloseStockModel(StoreItemModel storeItemModel) {
    try {
      showDialog(
        barrierDismissible: false,
        context: context,
        builder: (context) {
          return AlertDialog(
            title: Center(
              child: Text(
                "Verify",
                style: Theme.of(context).textTheme.bodyLarge,
              ),
            ),
            content: const SizedBox(
              height: 80,
              child: Center(
                child: Column(
                  children: [
                    Text('Are you sure you want to close this stock item?'),
                    SizedBox(height: 5),
                  ],
                ),
              ),
            ),
            actions: <Widget>[
              TextButton(
                child: const Text('Cancel'),
                onPressed: () {
                  context.pop(true);
                },
              ),
              ElevatedButton(
                child: const Text('Close'),
                onPressed: () async {
                  String closedBy = ref.read(authModelProvider)!.uid;
                  ref.read(storeItemControllerProvider).updateStoreItemStock(
                      ref, storeItemModel, storeItemModel.pieces, closedBy);
                  context.pop(true);
                  ref.invalidate(
                      storeItemStockListWithPaginationStreamProvider);
                },
              )
            ],
          );
        },
      );
    } catch (e) {
      print(e.toString());
    }
  }

  void addStockModel(StoreItemModel storeItemModel) {
    try {
      showDialog(
        barrierDismissible: false,
        context: context,
        builder: (context) {
          return AlertDialog(
            title: Center(
              child: Text(
                "Verify",
                style: Theme.of(context).textTheme.bodyLarge,
              ),
            ),
            content: SizedBox(
              height: 180,
              child: Center(
                child: Column(
                  children: [
                    Text('Item Name : ${storeItemModel.itemName}'),
                    const SizedBox(height: 5),
                    Text(
                        'Total pcs. in Po list : ${storeItemModel.pieces} ${storeItemModel.unit}'),
                    const SizedBox(height: 10),
                    Form(
                      key: _pieces,
                      child: TextFormField(
                        validator: (text) {
                          if (text == null ||
                              text.isEmpty ||
                              double.parse(text) < 1) {
                            return 'Please enter Pieces to add';
                          }
                          if (double.parse(text) >
                              (storeItemModel.pieces +
                                  (storeItemModel.pieces * 0.1))) {
                            return 'Pcs should not be greater than available stock';
                          }
                          return null;
                        },
                        controller: pieces,
                        keyboardType: TextInputType.number,
                        textCapitalization: TextCapitalization.words,
                        decoration: InputDecoration(
                          labelText: "Pieces",
                          hintText: "Enter Pieces",
                          border: OutlineInputBorder(
                            borderRadius: BorderRadius.circular(10),
                          ),
                        ),
                      ),
                    ),
                    const SizedBox(height: 5),
                  ],
                ),
              ),
            ),
            actions: <Widget>[
              TextButton(
                child: const Text('Cancel'),
                onPressed: () {
                  context.pop(true);
                },
              ),
              ElevatedButton(
                child: const Text('OK'),
                onPressed: () async {
                  if (_pieces.currentState!.validate()) {
                    double pcs = double.parse(pieces.text);
                    String updateBy = ref.read(authModelProvider)!.uid;
                    ref
                        .read(storeItemControllerProvider)
                        .updateStoreItem(ref, storeItemModel, pcs, updateBy);
                    context.pop(true);
                    pieces.clear();
                    _itemNameController.clear();
                    _poNumberController.clear();
                    ref.invalidate(
                        storeItemStockListWithPaginationStreamProvider);
                    _pieces.currentState?.reset();
                  }
                },
              )
            ],
          );
        },
      );
    } catch (e) {
      print(e.toString());
    }
  }
}
/**
We want to change the grid repeat() depending on the items in a grid
where repeat(4, 1fr) are dynamic values we can change in JS using setProperty()
note: setProperty(property-name, value)
*/
 
// our html = we add a data-grid attribure to show the grid number
<div class="qld-compare_page__courses" data-grid></div>
 
// our css
.courses{
  	//repeat(4, 1fr); replace with 2 new css variables, and a fallback
  	// in this case var(--compare-col-count) has a fallback of 4 
   repeat(var(--compare-col-count, 4), var(--compare-col-width, 205px));
}
 
// JS function



// create the changeGrid function outside the main function below
   function changeGrid(value){
       parentGrid.style.setProperty("--compare-col-width", value);
    }
       
 
function adjustGrid(number) { // number will the dynamic value that changes
  	// get the parent to which the grid willl be appplied
    const parentGrid = document.querySelector(".qld-compare_page__courses");
 
 	 // if element exists
     if (parentGrid) { 
      // set the grid attribute in the html to the number value in the param
      parentGrid.dataset.grid = `courses-${number}`; 
	  // now we are using the set Property to get the var give it the number value
      parentGrid.style.setProperty("--compare-col-count", number);
 
       /**
       switch (number) { // if numbers 1, 2, 3 or 4 is reached then do your thing!
            case 1:
           // here we are using setProperty() to target that css var, and apply value
            parentGrid.style.setProperty("--compare-col-width", "minmax(205px, 230px)");
            break;
           
            case 2:
			// here we are using setProperty() to target that css var, and apply value
            parentGrid.style.setProperty("--compare-col-width", "minmax(205px, 249px)");
            break;
 
            case 3:
			// here we are using setProperty() to target that css var, and apply value
            parentGrid.style.setProperty("--compare-col-width", "minmax(205px, 1fr)");
            break;
 
           	case 4:
			// here we are using setProperty() to target that css var, and apply value
         	parentGrid.style.setProperty("--compare-col-width", "minmax(205px, 1fr)");
            break;
           
                default:
                parentGrid.style.setProperty("--compare-col-width", "205px");
                break;
            }
        }
       */
       
       
       /**
       1. create object with all options
       2. create a function to call inside the object
       3. The function returns the code want to repeat with params
       4. Call that function using the object[dynamic] number
       */ 
       
       
       // Note we are still using number from the main function as this is the value
	  // that will output 1, 2, 3, 4
       
       const options = {
         // use cases here for key value pairs
				 1: () => changeGrid("minmax(205px, 230px)"),
                2: () => changeGrid("minmax(205px, 249px)"),
                3: () => changeGrid("minmax(205px, 1fr)"),
                4: () => changeGrid("minmax(205px, 1fr)"),
       }
      
       
       // call it
       // param should be the dynamic value of the oject and the matching number param
       changeGrid(options[number]) 
       
       
       
    }
 
 
 
	//use local storage for the  number we want
  adjustGrid(JSON.parse(localStorage.getItem("courses") || "[]").length);
 
 
 
 


// here is the full JS code with CSS variables
	

    function cssColWidthVariable(value) {
        const parentGrid = document.querySelector(".qld-compare_page__courses");
        parentGrid.style.setProperty("--compare-col-width", value);
    }

  
    function adjustGrid(number) {
        const parentGrid = document.querySelector(".qld-compare_page__courses");
        if (parentGrid) {
            parentGrid.dataset.grid = `courses-${number}`;
            parentGrid.style.setProperty("--compare-col-count", number);

            const gridOptions = {
                1: () => cssColWidthVariable("minmax(205px, 230px)"),
                2: () => cssColWidthVariable("minmax(205px, 249px)"),
                3: () => cssColWidthVariable("minmax(205px, 1fr)"),
                4: () => cssColWidthVariable("minmax(205px, 1fr)"),
            };

            cssColWidthVariable(gridOptions[number] || "205px");
        }
    }

   
  
// call the function based on a changing number
adjustGrid(JSON.parse(localStorage.getItem("courses") || "[]").length);
        


#include <iostream>
#include <unordered_map>
using namespace std;

int main() 
{
  int n, frequentNum, maxCount = 0;
  cin >> n;
  
  int a[n];
  for(int i = 0; i < n; ++i)
    cin >> a[i];
    
  unordered_map<int, int> container;
  for(const int& num : a)
    container[num]++;
    
  for(const auto& num : container)
  {
    if(num.second > maxCount)
    {
      maxCount = num.second;
      frequentNum = num.first;
    }
  }
  
  cout << frequentNum;
  
  return 0;
}
/**
We want to change the grid repeat() depending on the items in a grid
where repeat(4, 1fr) are dynamic values we can change in JS using setProperty()
note: setProperty(property-name, value)
*/

// our html = we add a data-grid attribure to show the grid number
<div class="qld-compare_page__courses" data-grid></div>

// our css
.courses{
  	//repeat(4, 1fr); replace with 2 new css variables, and a fallback
  	// in this case var(--compare-col-count) has a fallback of 4 
   repeat(var(--compare-col-count, 4), var(--compare-col-width, 205px));
}

// JS function

function adjustGrid(number) { // number will the dynamic value that changes
  	// get the parent to which the grid willl be appplied
    const parentGrid = document.querySelector(".qld-compare_page__courses");

 	 // if element exists
     if (parentGrid) { 
      // set the grid attribute in the html to the number value in the param
      parentGrid.dataset.grid = `courses-${number}`; 
	  // now we are using the set Property to get the var give it the number value
      parentGrid.style.setProperty("--compare-col-count", number);

       switch (number) { // if numbers 1, 2, 3 or 4 is reached then do your thing!
            case 1:
           // here we are using setProperty() to target that css var, and apply value
            parentGrid.style.setProperty("--compare-col-width", "minmax(205px, 230px)");
            break;
           
            case 2:
			// here we are using setProperty() to target that css var, and apply value
            parentGrid.style.setProperty("--compare-col-width", "minmax(205px, 249px)");
            break;

            case 3:
			// here we are using setProperty() to target that css var, and apply value
            parentGrid.style.setProperty("--compare-col-width", "minmax(205px, 1fr)");
            break;

           	case 4:
			// here we are using setProperty() to target that css var, and apply value
         	parentGrid.style.setProperty("--compare-col-width", "minmax(205px, 1fr)");
            break;
           
                default:
                parentGrid.style.setProperty("--compare-col-width", "205px");
                break;
            }
        }
    }



	//use local storage for the  number we want
  adjustGrid(JSON.parse(localStorage.getItem("courses") || "[]").length);




// the css starter
// note we are resetting the --compare-col-count
 &__courses {
      display: grid;
      grid-template-columns: clamp(120px, 39vw, 180px) repeat(var(--compare-col-count, 4), var(--compare-col-width, 205px));
      grid-template-rows: repeat(2, 1fr) repeat(6, 90px) repeat(1, 1fr);
      z-index: 1;
      column-gap: 1.6rem;


// NEXT SEE: CONVERT setProperty with CSS variables to object and functions
<!-------- Fareharbor Lightframe -------->
<script src="https://fareharbor.com/embeds/api/v1/?autolightframe=yes"></script>
<a href="https://fareharbor.com/embeds/book/autocaresdavid/?full-items=yes" style="-webkit-transform: rotate(0deg) !important;margin-top: 22em !important;  padding: .3em 2em !important; font-family:Aeonik, sans-serif !important; border:2px solid #000000 !important; text-decoration:none !important; font-weight: 700 !important; font-size:1.2em !important; box-shadow:none !important; border-radius: 56px !important;" class="fh-lang fh-fixed--side fh-button-1 fh-hide--desktop fh-size--small fh-button-true-flat-white fh-shape--round fh-color--black">Reserva ahora</a>


Imagine the thrill of building your financial empire without the constraints of a suit or the frenzy of Wall Street. 

	Well, the cryptocurrency exchange script could be your golden ticket to achieving that dream.

	Instead of countless hours of coding an exchange from scratch or spending a fortune on a developer, you can opt for a ready-made cryptocurrency exchange script. This allows you to set up your crypto trading platform quickly.

	It’s hassle-free so connect easily. Customize and start profiting while others dive into the trading frenzy!

Increase in demand
A growing wave of individuals is diving into the crypto market. Indicating that a large group of traders looking for a reliable crypto exchange

Endless possibilities for profits
From transaction fees to withdrawal fees and staking options, you are on the verge of creating your digital wealth!

No coding nightmares
Pre-build cryptocurrency exchange script take the burden off your shoulders. Allows you to save time, reduces stress, and avoids any existential crises.

	Why be satisfied with just watching the fluctuations in Bitcoin prices? Dive in and reap the benefits!

	Start your crypto exchange and get an exciting crypto wave of success.

	Who knows? In a few years, people might be talking about your crypto exchange in forums like this!
      
Website: https://www.trioangle.com/cryptocurrency-exchange-script/ 
WhatsApp us: +91 9361357439
Email us: sales@innblockchain.com
header {
  position: sticky; 
  top: 0;
  left: 0;
  right: 0;
  display: flex;
  justify-content: center; 
 }
#!/usr/bin/env python3

"""
Extract responses from a HAR file, which can be exported by browser dev tools.
Files are written for URLs that match a certain regular expression.
"""
# XXX: Warning - Quick best effort script, i.e. no proper error handling.


import re
import sys
import json
import base64
import argparse

from typing import Dict, Iterator, Tuple, Optional


def parse_har_log(filename: str) -> Iterator[Tuple[Dict, Dict]]:
    with open(filename, "r") as fp:
        har = json.load(fp)
    if not isinstance(har, dict) or \
            "log" not in har or not isinstance(har["log"], dict)\
            or "entries" not in har["log"] or not isinstance(har["log"]["entries"], list):
        raise ValueError(f"No/invalid log entries in {filename}")
    yield from ((_["request"], _["response"]) for _ in har["log"]["entries"])


def match_request(request: Dict, url_rx: re.Pattern) -> bool:
    return "url" in request and isinstance(request["url"], str) and url_rx.match(request["url"]) is not None


def match_response(response: Dict) -> bool:
    return "status" in response and isinstance(response["status"], int) and response["status"] == 200


def dump_response(response: Dict, filename: str) -> bool:
    if "content" in response and isinstance(response["content"], dict):
        content: Dict = response["content"]
        if "text" in content and isinstance(content["text"], str):
            if "encoding" not in content:
                data: bytes = content["text"].encode("utf-8")
            elif isinstance(content["encoding"], str) and content["encoding"] == "base64":
                data = base64.b64decode(content["text"])
            else:
                return False
            try:
                with open(filename, "wb") as fp:
                    fp.write(data)
                    return True
            except OSError:
                return False
    return False


def main() -> int:
    parser = argparse.ArgumentParser(description=__doc__)
    parser.add_argument("--url", type=str, default=None,
                        help="regular expression for the request url, no response content dump otherwise")
    parser.add_argument("file", metavar="archive.har",
                        help="http archive file to process")

    args = parser.parse_args()
    filename: str = args.file
    url_rx: Optional[re.Pattern] = re.compile(args.url) if args.url is not None else None

    for request, response in parse_har_log(filename):
        url: str = request["url"]
        fn: str = re.sub('[^a-zA-Z0-9_-]', '_', url)
        if url_rx is not None and match_request(request, url_rx) and match_response(response):
            if dump_response(response, fn):
                print(f"DUMP: {url}")
            else:
                print(f"FAIL: {url}")
        else:
            print(f"SKIP: {url}")

    return 0


if __name__ == "__main__":
    sys.exit(main())
### **Python Programming Basics for Beginners**
 
 
 
**Role:** You are an expert Python programming tutor. Your goal is to guide students through a personalized, step-by-step learning journey, helping them grasp essential Python programming concepts, particularly if they are beginners. The learning experience should be interactive, goal-driven, and completed within 3-4 hours. Follow the structured steps below, ensuring you introduce each concept progressively to avoid overwhelming the student by presenting everything at once.
 
 
 
**Session Outline:**
 
 
 
#### **0\. Initial Setup and Orientation**
 
 
 
**0.1 Google Colab Setup**
 
 
 
- **Step 1:** Introduce Google Colab and explain its purpose.
 
- **Step 2:** Guide the student through setting up a Google Colab notebook.
 
- **Step 3:** Explain how to write and run Python code in Colab.
 
 
 
**Interactive Checkpoint:** Have the student write and run a simple "Hello, World!" program. Provide immediate feedback before moving on.
 
 
 
---
 
 
 
#### **1\. Initial Assessment and Goal Setting**
 
 
 
**1.1 Student Assessment**
 
 
 
- **Step 1:** Ask the student about their experience with Python, including:
 
  - Variables and Data Types
 
  - Loops and Functions
 
- **Step 2:** Discuss their learning goals and any specific areas of interest.
 
 
 
**1.2 Goal Setting**
 
 
 
- **Step 1:** Based on the assessment, set a personalized learning goal:
 
  - **For Beginners:** Focus on Python basics and simple coding exercises.
 
  - **For Intermediate Students:** Emphasize more complex data manipulations or problem-solving.
 
- **Step 2:** Create and share a step-by-step learning plan tailored to their needs.
 
 
 
**Note:** Confirm the student's background and goals before proceeding to the next section.
 
 
 
---
 
 
 
#### **2\. Python Fundamentals**
 
 
 
**2.1 Core Concepts**
 
 
 
- **Step 1:** Introduce basic Python concepts one by one:
 
  - Variables and Data Types
 
  - Basic operations
 
- **Step 2:** Provide a small coding challenge after each concept, ensuring the student understands before moving to the next.
 
 
 
**Interactive Checkpoint:** Have the student write code to declare variables of different types and perform basic operations. Provide feedback and clarify any misunderstandings.
 
 
 
---
 
 
 
#### **3\. Control Flow: Lists, Loops, and Functions**
 
 
 
**3.1 Lists and Loops**
 
 
 
- **Step 1:** Introduce lists, explaining their structure and use.
 
- **Step 2:** Guide the student in writing simple loops to iterate over lists.
 
 
 
**3.2 Functions**
 
 
 
- **Step 1:** Explain the concept of functions and their importance in Python.
 
- **Step 2:** Walk the student through writing their own functions.
 
 
 
**3.3 Interactive Coding**
 
 
 
- **Step 1:** Encourage the student to write their own code for loops and functions.
 
- **Step 2:** Offer guidance as needed, providing hints or partial code.
 
 
 
**Interactive Checkpoint:** After completing loops and functions, present a problem for the student to solve using these concepts. Review their solution and offer feedback.
 
 
 
---
 
 
 
#### **4\. Object-Oriented Programming (OOP) and Classes**
 
 
 
**4.1 Introduction to Classes and Objects**
 
 
 
- **Step 1:** Explain the concept of Object-Oriented Programming (OOP) and its benefits.
 
- **Step 2:** Introduce classes and objects, using simple examples.
 
 
 
**4.2 Creating and Using Classes**
 
 
 
- **Step 1:** Walk the student through creating a class with attributes and methods.
 
- **Step 2:** Demonstrate how to create objects from the class and use its methods.
 
 
 
**Interactive Checkpoint:** Have the student create a simple class and use it in a short program. Provide feedback and correct any issues.
 
 
 
---
 
 
 
#### **5\. Error Handling and Debugging**
 
 
 
**5.1 Introduction to Error Handling**
 
 
 
- **Step 1:** Explain common types of errors in Python and the importance of handling them gracefully.
 
- **Step 2:** Introduce try, except, and finally blocks for error handling.
 
 
 
**5.2 Practical Error Handling**
 
 
 
- **Step 1:** Guide the student through writing code that includes error handling.
 
- **Step 2:** Discuss strategies for debugging and finding errors in code.
 
 
 
**Interactive Checkpoint:** Provide a buggy code snippet for the student to debug. Review their approach and offer guidance as needed.
 
 
 
---
 
 
 
#### **6\. File Handling and Data Input/Output**
 
 
 
**6.1 Reading from and Writing to Files**
 
 
 
- **Step 1:** Introduce file operations, explaining how to read from and write to files in Python.
 
- **Step 2:** Demonstrate reading data from a file and processing it.
 
 
 
**Interactive Checkpoint:** Have the student write a program to read a file and perform a simple task, such as counting lines. Review their work and provide feedback.
 
 
 
---
 
 
 
#### **7\. Practical Application Project**
 
 
 
**7.1 Hands-On Project**
 
 
 
- **Step 1:** Introduce a hands-on project, such as a simple text analysis.
 
- **Step 2:** Guide the student step by step in tasks like counting word occurrences or analyzing data patterns.
 
 
 
**Interactive Experimentation:** Encourage the student to experiment with the code, making modifications to observe different results. Provide feedback on their approach and reasoning after each step.
 
 
 
---
 
 
 
#### **8\. Reflection, Q&A, and Next Steps**
 
 
 
**8.1 Reflection**
 
 
 
- **Step 1:** Encourage the student to reflect on what they've learned.
 
- **Step 2:** Discuss any areas they found challenging and what they'd like to explore further.
 
 
 
**8.2 Interactive Discussion**
 
 
 
- **Step 1:** Facilitate a Q&A session where the student can ask questions or seek clarification on any topic.
 
 
 
**8.3 Next Steps**
 
 
 
- **Step 1:** Suggest further resources or topics for continued learning.
 
- **Step 2:** Provide a clear action plan for the student's continued learning journey.
 
 
 
---
 
 
 
**Session Guidelines:**
 
 
 
1. **Interactive Learning:**
 
   - Encourage the student to code as much as possible by themselves.
 
   - Provide hints, but do not give direct answers. Allow the student to struggle a bit before offering more guidance.
 
   - Confirm understanding before moving to the next step.
 
 
 
2. **Time Management:**
 
   - Ensure the session stays within the 3-4 hour timeframe.
 
   - Adjust the pace and depth based on the student's progress.
 
 
 
3. **Continuous Feedback:**
 
   - Offer regular feedback on the student's code and understanding.
 
   - Address any questions or difficulties the student encounters.
 
 
 
4. **Expectations After Pasting the Prompt** 
 
  - Clear instructions on what students should expect after pasting the prompt into ChatGPT, such as assessment, coding exercises, problem-solving, and feedback loops.
 
 
 
Now, let's start with the first step and guide you through getting started. Remember, always confirm your understanding by asking questions or proposing exercises to ensure you're comfortable before moving on.
https://community.dynamics.com/blogs/post/?postid=be407572-9096-47a7-af67-5d9b0f0d4894
Want to launch a profitable gambling business? Addus Technologies is a trusted Casino Gambling Game Development Company offering casino games, Lucky Draw games, and sports betting software. As a Casino Gambling Game Development Company, Addus helps business people, entrepreneurs, and investors start their gambling businesses with innovative solutions.
#include <iostream>
#include <vector>
using namespace std;
 
int main() 
{
  int n1, n2, i1=0, i2=0;
  
  cin >> n1;
  int a[n1];
  for(int i = 0; i < n1; ++i)
    cin >> a[i];
    
  cin >> n2;
  int b[n2];
  for(int i = 0; i < n2; ++i)
    cin >> b[i];
    
  vector<int> answer;
    
  while(i1 < n1 && i2 < n2)
  {
    if(a[i1] < b[i2])
    {
      answer.push_back(a[i1]);
      ++i1;
    }
    else if(a[i1] > b[i2])
    {
      answer.push_back(b[i2]);
      ++i2;
    }
  }
  
  while(i1 < n1)
  {
    answer.push_back(a[i1]);
    ++i1;
  }
  
  while(i2 < n2)
  {
    answer.push_back(b[i2]);
    ++i2;
  }
  
  for(int num : answer)
    cout << num << " ";
  
  return 0;
}
#include <iostream>
using namespace std;

void PrintArray(int a[], int n)
{
  for(int i = 0; i < n; ++i)
    cout << a[i] << " ";
}

int main() 
{
  int n, p1 = 0, p2 = 0;
  cin >> n;
  
  int a[n];
  for(int i = 0; i < n; ++i)
    cin >> a[i];
  
  while(p2 < n)
  {
    if(a[p2] % 2 == 0)
    {
      swap(a[p1], a[p2]);
      ++p1;
    }
    ++p2;
  }
  
  PrintArray(a, n);
  
  return 0;
}
@RestController
public class EventProducerController {
    private final KafkaTemplate<String, String> kafkaTemplate;
    @Autowired
    public EventProducerController(KafkaTemplate<String, String> kafkaTemplate) {
        this.kafkaTemplate = kafkaTemplate;
    }
    @GetMapping("/message/{message}")
    public String trigger(@PathVariable String message) {
        kafkaTemplate.send("messageTopic", message);
        return "Hello, Your message has been published: " + message;
    }
}
const req = await fetch(
    "http://localhost:3000/api/auth/signin", {
      method: "POST",
      header:{
        'Accept':'application/json',
        'Content-Type': 'application/json'
      },
      body: JSON.stringify({
        username:myusername,
        password:mypassword
      })
    },
    
  )
HTTP 500 - error - {"success":true,"message":""}


Unzip the PrestaShop installation package and find the /prestashop folder.
Open /app/AppKernel.php file in a text editor.
Locate the getContainerClearCacheLockPath function.
Replace the existing code with the following:


protected function getContainerClearCacheLockPath(): string
{
    $class = $this->getContainerClass();
    $cacheDir = sys_get_temp_dir(); //$this->getCacheDir();

    return sprintf('%s/%s.php.cache_clear.lock', $cacheDir, $class);
}

Important: Revert After Installation


### **Python Programming Basics for Beginners**



**Role:** You are an expert Python programming tutor. Your goal is to guide students through a personalized, step-by-step learning journey, helping them grasp essential Python programming concepts, particularly if they are beginners. The learning experience should be interactive, goal-driven, and completed within 3-4 hours. Follow the structured steps below, ensuring you introduce each concept progressively to avoid overwhelming the student by presenting everything at once.



**Session Outline:**



#### **0\. Initial Setup and Orientation**



**0.1 Google Colab Setup**



- **Step 1:** Introduce Google Colab and explain its purpose.

- **Step 2:** Guide the student through setting up a Google Colab notebook.

- **Step 3:** Explain how to write and run Python code in Colab.



**Interactive Checkpoint:** Have the student write and run a simple "Hello, World!" program. Provide immediate feedback before moving on.



---



#### **1\. Initial Assessment and Goal Setting**



**1.1 Student Assessment**



- **Step 1:** Ask the student about their experience with Python, including:

  - Variables and Data Types

  - Loops and Functions

- **Step 2:** Discuss their learning goals and any specific areas of interest.



**1.2 Goal Setting**



- **Step 1:** Based on the assessment, set a personalized learning goal:

  - **For Beginners:** Focus on Python basics and simple coding exercises.

  - **For Intermediate Students:** Emphasize more complex data manipulations or problem-solving.

- **Step 2:** Create and share a step-by-step learning plan tailored to their needs.



**Note:** Confirm the student's background and goals before proceeding to the next section.



---



#### **2\. Python Fundamentals**



**2.1 Core Concepts**



- **Step 1:** Introduce basic Python concepts one by one:

  - Variables and Data Types

  - Basic operations

- **Step 2:** Provide a small coding challenge after each concept, ensuring the student understands before moving to the next.



**Interactive Checkpoint:** Have the student write code to declare variables of different types and perform basic operations. Provide feedback and clarify any misunderstandings.



---



#### **3\. Control Flow: Lists, Loops, and Functions**



**3.1 Lists and Loops**



- **Step 1:** Introduce lists, explaining their structure and use.

- **Step 2:** Guide the student in writing simple loops to iterate over lists.



**3.2 Functions**



- **Step 1:** Explain the concept of functions and their importance in Python.

- **Step 2:** Walk the student through writing their own functions.



**3.3 Interactive Coding**



- **Step 1:** Encourage the student to write their own code for loops and functions.

- **Step 2:** Offer guidance as needed, providing hints or partial code.



**Interactive Checkpoint:** After completing loops and functions, present a problem for the student to solve using these concepts. Review their solution and offer feedback.



---



#### **4\. Object-Oriented Programming (OOP) and Classes**



**4.1 Introduction to Classes and Objects**



- **Step 1:** Explain the concept of Object-Oriented Programming (OOP) and its benefits.

- **Step 2:** Introduce classes and objects, using simple examples.



**4.2 Creating and Using Classes**



- **Step 1:** Walk the student through creating a class with attributes and methods.

- **Step 2:** Demonstrate how to create objects from the class and use its methods.



**Interactive Checkpoint:** Have the student create a simple class and use it in a short program. Provide feedback and correct any issues.



---



#### **5\. Error Handling and Debugging**



**5.1 Introduction to Error Handling**



- **Step 1:** Explain common types of errors in Python and the importance of handling them gracefully.

- **Step 2:** Introduce try, except, and finally blocks for error handling.



**5.2 Practical Error Handling**



- **Step 1:** Guide the student through writing code that includes error handling.

- **Step 2:** Discuss strategies for debugging and finding errors in code.



**Interactive Checkpoint:** Provide a buggy code snippet for the student to debug. Review their approach and offer guidance as needed.



---



#### **6\. File Handling and Data Input/Output**



**6.1 Reading from and Writing to Files**



- **Step 1:** Introduce file operations, explaining how to read from and write to files in Python.

- **Step 2:** Demonstrate reading data from a file and processing it.



**Interactive Checkpoint:** Have the student write a program to read a file and perform a simple task, such as counting lines. Review their work and provide feedback.



---



#### **7\. Practical Application Project**



**7.1 Hands-On Project**



- **Step 1:** Introduce a hands-on project, such as a simple text analysis.

- **Step 2:** Guide the student step by step in tasks like counting word occurrences or analyzing data patterns.



**Interactive Experimentation:** Encourage the student to experiment with the code, making modifications to observe different results. Provide feedback on their approach and reasoning after each step.



---



#### **8\. Reflection, Q&A, and Next Steps**



**8.1 Reflection**



- **Step 1:** Encourage the student to reflect on what they've learned.

- **Step 2:** Discuss any areas they found challenging and what they'd like to explore further.



**8.2 Interactive Discussion**



- **Step 1:** Facilitate a Q&A session where the student can ask questions or seek clarification on any topic.



**8.3 Next Steps**



- **Step 1:** Suggest further resources or topics for continued learning.

- **Step 2:** Provide a clear action plan for the student's continued learning journey.



---



**Session Guidelines:**



1. **Interactive Learning:**

   - Encourage the student to code as much as possible by themselves.

   - Provide hints, but do not give direct answers. Allow the student to struggle a bit before offering more guidance.

   - Confirm understanding before moving to the next step.



2. **Time Management:**

   - Ensure the session stays within the 3-4 hour timeframe.

   - Adjust the pace and depth based on the student's progress.



3. **Continuous Feedback:**

   - Offer regular feedback on the student's code and understanding.

   - Address any questions or difficulties the student encounters.



4. **Expectations After Pasting the Prompt** 

  - Clear instructions on what students should expect after pasting the prompt into ChatGPT, such as assessment, coding exercises, problem-solving, and feedback loops.



Now, let's start with the first step and guide you through getting started. Remember, always confirm your understanding by asking questions or proposing exercises to ensure you're comfortable before moving on.
using System.Drawing.Drawing2D;

namespace CtrlCPopup {
    public partial class PopupForm : Form {
        private int targetY;
        private const int slideSpeed = 15;

        private System.Windows.Forms.Timer timerSlide;
        private System.Windows.Forms.Timer timerClose;

        private const int cornerRadius = 20;

        private static PopupForm currentPopup;

        public PopupForm() {
            InitializeForm();
        }

        private void InitializeForm() {
            this.StartPosition = FormStartPosition.Manual;
            this.FormBorderStyle = FormBorderStyle.None;
            this.BackColor = SystemAccentColorHelper.GetAccentColor();
            this.Size = new Size(180, 100);
            this.TopMost = true;
            this.ShowInTaskbar = false;

            Label lblMessage = new Label();
            lblMessage.Text = "Copied!";
            lblMessage.AutoSize = true;
            lblMessage.Font = new Font("Segoe UI", 20, FontStyle.Regular);
            lblMessage.ForeColor = Color.White;
            lblMessage.Location = new Point(33, 32);
            this.Controls.Add(lblMessage);

            timerSlide = new System.Windows.Forms.Timer();
            timerSlide.Interval = 10;
            timerSlide.Tick += TimerSlide_Tick;

            timerClose = new System.Windows.Forms.Timer();
            timerClose.Interval = 3000; //* 3 seconds auto-close
            timerClose.Tick += TimerClose_Tick;

            ApplyRoundedCorners();
        }

        private void ApplyRoundedCorners() {
            GraphicsPath path = new GraphicsPath();
            Rectangle bounds = new Rectangle(0, 0, this.Width, this.Height);

            path.AddArc(bounds.X, bounds.Y, cornerRadius * 2, cornerRadius * 2, 180, 90); // Top-left
            path.AddArc(bounds.Right - cornerRadius * 2, bounds.Y, cornerRadius * 2, cornerRadius * 2, 270, 90); // Top-right
            path.AddArc(bounds.Right - cornerRadius * 2, bounds.Bottom - cornerRadius * 2, cornerRadius * 2, cornerRadius * 2, 0, 90); // Bottom-right
            path.AddArc(bounds.X, bounds.Bottom - cornerRadius * 2, cornerRadius * 2, cornerRadius * 2, 90, 90); // Bottom-left
            path.CloseFigure();

            this.Region = new Region(path);
        }

        public void ShowPopup() {
            //! Close any existing popup
            if (currentPopup != null && !currentPopup.IsDisposed) {
                currentPopup.Close();
            }

            this.Left = (Screen.PrimaryScreen.WorkingArea.Width - this.Width) / 2;
            this.Top = Screen.PrimaryScreen.WorkingArea.Height;
            targetY = Screen.PrimaryScreen.WorkingArea.Height - this.Height - 20; // 20 pixels from the bottom

            this.Show();
            timerSlide.Start();
            timerClose.Start();

            currentPopup = this;
        }

        private void TimerSlide_Tick(object sender, EventArgs e) {
            if (this.Top > targetY) {
                this.Top -= slideSpeed;
            }
            else {
                timerSlide.Stop();
            }
        }

        private void TimerClose_Tick(object sender, EventArgs e) {
            this.Close();
        }
    }
}
<p>Struggling with complex equations or challenging math problems? MyAssignmenthelp offers expert Mathematics Assignment Help https://myassignmenthelp.com/uk/mathematics-assignment-help.html to simplify your academic journey. From algebra to calculus, our professionals provide accurate solutions tailored to your needs. Get timely and affordable assistance to achieve academic excellence.</p>
#include <iostream>
using namespace std;

void InsertionSort(int a[], int n)
{
  for(int i = 1; i < n; ++i)
  {
    int key = a[i];
    int j = i-1;
    
    while(j >= 0 && key < a[j])
    {
      a[j+1] = a[j];
      --j;
    }
    
    a[j+1] = key;
  }
}

int main() 
{
  int n;
  cin >> n;
  
  int a[n];
  for(int i = 0; i < n; ++i)
  {
    cin >> a[i];
    a[i] *= a[i];
  }
  
  InsertionSort(a, n);
  
  for(int i = 0; i < n; ++i)
  {
    cout << a[i] << " ";
  }
  
  return 0;
}
#include <iostream>
#include <vector>
#include <unordered_map>
#include <algorithm>
using namespace std;

int main() 
{
  int n; 
  cin >> n;
  
  vector<int> a(n), b(n);
  unordered_map<int, int> rankMap;
  
  for(int i = 0; i < n; ++i)
  {
    cin >> a[i];
    b[i] = a[i];
  }
  
  sort(b.begin(), b.end());
  
  for(int i = 0; i < n; ++i)
  {
    rankMap[b[i]] = i+1;
  }
  
  for(int i = 0; i < n; ++i)
  {
    cout << rankMap[a[i]] << " ";
  }
  
  return 0;
}
import React, { useState, useRef } from 'react';

const UploadFolderModal = ({ disableBackgroundClose = true }) => {
  const [active, setActive] = useState(false);
  const [folderName, setFolderName] = useState('');
  const [fileList, setFileList] = useState([]);
  const [uploadProgress, setUploadProgress] = useState({});
  const dropArea = useRef(null);
  const fileInput = useRef(null);

  const handleDrop = (e) => {
    e.preventDefault();
    e.stopPropagation();
    dropArea.current.classList.remove('dragging');

    const items = e.dataTransfer.items;
    if (items.length > 0) {
      const folder = items[0].webkitGetAsEntry();
      if (folder?.isDirectory) {
        handleFolder(folder);
      } else {
        alert('Please drop a folder!');
      }
    }
  };

  const handleFolder = async (folder, parentPath = '') => {
    setFolderName(folder.name || 'Root');

    const reader = folder.createReader();
    const entries = await readEntries(reader);

    for (const entry of entries) {
      if (entry.isFile) {
        const file = await new Promise((resolve) => entry.file(resolve));
        setFileList((prevFileList) => [
          ...prevFileList,
          { name: file.name, size: file.size, type: file.type, folderPath: parentPath },
        ]);
      } else if (entry.isDirectory) {
        await handleFolder(entry, `${parentPath}/${entry.name}`);
      }
    }

    if (fileList.length > 0) startUpload();
  };

  const readEntries = (reader) => new Promise((resolve, reject) => {
    reader.readEntries(resolve, reject);
  });

  const uploadFileToS3 = (file, index) => {
    const formData = new FormData();
    formData.append('file', file);

    return new Promise((resolve, reject) => {
      const xhr = new XMLHttpRequest();
      xhr.open('POST', '/api/v1/upload', true);

      xhr.upload.onprogress = (e) => {
        if (e.lengthComputable) {
          const percent = (e.loaded / e.total) * 100;
          setUploadProgress((prevProgress) => ({
            ...prevProgress,
            [index]: Math.round(percent),
          }));
        }
      };

      xhr.onload = () => xhr.status === 200 ? resolve(JSON.parse(xhr.responseText).fileUrl) : reject('Error uploading file');
      xhr.onerror = () => reject('Error uploading file');
      xhr.send(formData);
    });
  };

  const handleFileSelect = (e) => {
    const files = Array.from(e.target.files).map((file) => ({
      name: file.name,
      size: file.size,
      type: file.type,
      folderPath: 'Root',
    }));
    setFileList(files);
  };

  const startUpload = async () => {
    for (let i = 0; i < fileList.length; i++) {
      await uploadFileToS3(fileList[i], i);
    }
  };

  const closeModal = () => {
    setActive(false);
    setTimeout(() => {}, 200);
  };

  const handleDragOver = (e) => {
    e.preventDefault();
    e.stopPropagation();
    dropArea.current.classList.add('dragging');
  };

  const handleDragLeave = (e) => {
    e.preventDefault();
    e.stopPropagation();
    dropArea.current.classList.remove('dragging');
  };

  return (
    <div className={`wrap-upload-modal${active ? ' active' : ''}`}>
      <div className="wrap-modal d-flex align-items-center justify-content-center">
        <div className="wrap-content">
          <div className="body-modal">
            <div
              ref={dropArea}
              className="wrap-area-drop"
              onDrop={handleDrop}
              onDragOver={handleDragOver}
              onDragLeave={handleDragLeave}
            >
              <p className="text-center main">Kéo và thả thư mục vào đây để lấy thông tin và các tệp bên trong</p>
              <p className="text-center sub">Chỉ thả thư mục vào đây</p>
            </div>
            <div className="text-center">
              <button onClick={() => fileInput.current.click()} className="btn btn-primary">Tải tệp lên</button>
              <input ref={fileInput} type="file" multiple onChange={handleFileSelect} style={{ display: 'none' }} />
            </div>
            <div className="text-center">
              <button onClick={startUpload} className="btn btn-success mt-3">Bắt đầu tải lên</button>
            </div>
          </div>
          <div className="footer-modal">
            <div><strong>Folder Name:</strong> {folderName}</div>
            <div><strong>List of Files:</strong>
              {fileList.length > 0 ? (
                fileList.map((file, index) => (
                  <div key={index}>
                    {file.name} - {file.size} bytes - {file.type} - <strong> Folder: {file.folderPath}</strong>
                    <div>
                      <progress value={uploadProgress[index] || 0} max={100}></progress>
                      <span>{uploadProgress[index] ? `${uploadProgress[index]}%` : 'Đang chờ'}</span>
                    </div>
                  </div>
                ))
              ) : (
                <p>No files to display</p>
              )}
            </div>
          </div>
        </div>
      </div>
    </div>
  );
};

export default UploadFolderModal;
Launch a secure and scalable cryptocurrency exchange with advanced trading features and high liquidity. Build a robust platform with seamless transactions and top-tier security

Email id : sales@opris.exchange
Phone number : +91 99942 48706
Choosing the right rummy game development company involves evaluating various key factors to ensure a high-quality, captivating, and user-friendly gaming experience. Look for a company that understands your vision and offers customization options to tailor the game to your specific requirements and target audience.

It’s important to assess their technical expertise in areas such as security, scalability, and platform compatibility. Make sure they provide customizable solutions to meet your unique needs. Additionally, prioritize companies that offer ongoing support and updates to keep your game competitive in the ever-evolving gaming market.

Partner with Maticz, a leading rummy game development company. With their experienced game developers, they specialize in creating customized solutions for web and mobile multiplayer rummy games tailored to your vision.

posts = list()
result = client.tiktok_user_posts_from_username(
    username="zachking",
    depth=1,
)
posts.extend(result.data["data"])
next_cursor = result.get("nextCursor")

if next_cursor is not None:
    result = client.tiktok_user_posts_from_username(
        username="zachking",
        depth=5,
        cursor=next_cursor,
    )
    posts.extend(result.data["data"])

print("Posts:", len(posts))
result = client.tiktok_user_posts_from_username(
    username="zachking",
    depth=1,
    alternative_method=True,
)
result = client.tiktok.user_info_from_username(
    username="zachking"
)
result = client.tiktok.user_info_from_secuid(
    sec_uid="MS4wLjABAAA..."
)

user = result.data["user"]
print("Username:", user["unique_id"])
print("Nickname:", user["nickname"])
print("Followers:", user["follower_count"])
print("Posts:", user["aweme_count"])
print("Likes:", user["total_favorited"])
star

Fri Feb 21 2025 04:20:59 GMT+0000 (Coordinated Universal Time)

@leah2301 #python

star

Fri Feb 21 2025 03:17:47 GMT+0000 (Coordinated Universal Time)

@ASPX #css #webkit #-webkit

star

Fri Feb 21 2025 01:43:42 GMT+0000 (Coordinated Universal Time)

@gbritgs

star

Thu Feb 20 2025 23:24:36 GMT+0000 (Coordinated Universal Time)

@kanatov

star

Thu Feb 20 2025 15:45:54 GMT+0000 (Coordinated Universal Time) https://codingislove.com/parse-html-in-excel-vba/

@acassell

star

Thu Feb 20 2025 15:44:31 GMT+0000 (Coordinated Universal Time) https://codingislove.com/parse-html-in-excel-vba/

@acassell

star

Thu Feb 20 2025 14:42:39 GMT+0000 (Coordinated Universal Time)

@MinaTimo

star

Thu Feb 20 2025 12:59:18 GMT+0000 (Coordinated Universal Time)

@StephenThevar #grafana

star

Thu Feb 20 2025 11:56:11 GMT+0000 (Coordinated Universal Time)

@Rishi1808

star

Thu Feb 20 2025 09:20:30 GMT+0000 (Coordinated Universal Time) https://www.coinsclone.com/metamask-wallet-clone-script/

@CharleenStewar

star

Thu Feb 20 2025 09:13:36 GMT+0000 (Coordinated Universal Time)

@lafcha #sql

star

Thu Feb 20 2025 06:51:44 GMT+0000 (Coordinated Universal Time)

@Rishi1808

star

Thu Feb 20 2025 06:51:41 GMT+0000 (Coordinated Universal Time)

@Rishi1808

star

Thu Feb 20 2025 01:50:29 GMT+0000 (Coordinated Universal Time)

@Rohan@99

star

Thu Feb 20 2025 00:46:19 GMT+0000 (Coordinated Universal Time)

@davidmchale #setproperty #cssvariables

star

Wed Feb 19 2025 17:54:05 GMT+0000 (Coordinated Universal Time) /hacking.com

@wrigd8449@wrdsb #hacking

star

Wed Feb 19 2025 16:58:38 GMT+0000 (Coordinated Universal Time) https://www.thiscodeworks.com/user/wrigd8449@wrdsb

@wrigd8449@wrdsb #hacking

star

Wed Feb 19 2025 16:07:14 GMT+0000 (Coordinated Universal Time)

@Shira

star

Wed Feb 19 2025 12:32:39 GMT+0000 (Coordinated Universal Time) https://www.trioangle.com/cryptocurrency-exchange-script/

@Johnhendrick #java #javascript #django #nodejs #react.js #css

star

Wed Feb 19 2025 10:58:20 GMT+0000 (Coordinated Universal Time)

@SophieLCDZ

star

Wed Feb 19 2025 09:43:39 GMT+0000 (Coordinated Universal Time) https://www.hackitu.de/har_dump/har_dump.py.html

@rhce143

star

Wed Feb 19 2025 09:22:53 GMT+0000 (Coordinated Universal Time) https://www.coinsclone.com/cryptocurrency-exchange-development-company/

@CharleenStewar

star

Wed Feb 19 2025 09:19:22 GMT+0000 (Coordinated Universal Time)

@jak123

star

Wed Feb 19 2025 07:34:27 GMT+0000 (Coordinated Universal Time)

@MinaTimo

star

Wed Feb 19 2025 07:05:53 GMT+0000 (Coordinated Universal Time) https://myassignmenthelp.expert/case-study-assignment-help.html

@steve1997 #commandline

star

Wed Feb 19 2025 06:23:51 GMT+0000 (Coordinated Universal Time) https://www.addustechnologies.com/casino-gambling-game-development

@Seraphina

star

Wed Feb 19 2025 02:45:07 GMT+0000 (Coordinated Universal Time)

@Rohan@99

star

Wed Feb 19 2025 02:15:53 GMT+0000 (Coordinated Universal Time)

@Rohan@99

star

Tue Feb 18 2025 20:59:26 GMT+0000 (Coordinated Universal Time) https://subscription.packtpub.com/book/web-development/9781803230788

@Luciano

star

Tue Feb 18 2025 18:46:05 GMT+0000 (Coordinated Universal Time) https://stackoverflow.com/questions/69332201/i-tried-to-request-body-json-to-node-js-using-await-fetch-the-body-is-empty

@Luciano #javascript

star

Tue Feb 18 2025 17:23:24 GMT+0000 (Coordinated Universal Time)

@caovillanueva #php

star

Tue Feb 18 2025 14:17:08 GMT+0000 (Coordinated Universal Time) https://ddls.aicell.io/post/learn-python-with-chatgpt/

@Marsel

star

Tue Feb 18 2025 10:12:22 GMT+0000 (Coordinated Universal Time) https://www.coinsclone.com/trustwallet-clone-app-development/

@CharleenStewar

star

Tue Feb 18 2025 09:40:44 GMT+0000 (Coordinated Universal Time)

@Kareem_Al_Hamwi #c#

star

Tue Feb 18 2025 07:42:36 GMT+0000 (Coordinated Universal Time) https://myassignmenthelp.com/uk/mathematics-assignment-help.html

@parkerharry0005 #assignment

star

Tue Feb 18 2025 02:52:07 GMT+0000 (Coordinated Universal Time)

@Rohan@99

star

Tue Feb 18 2025 02:33:58 GMT+0000 (Coordinated Universal Time)

@Rohan@99

star

Tue Feb 18 2025 01:53:23 GMT+0000 (Coordinated Universal Time)

@khainguyenhm

star

Mon Feb 17 2025 12:33:30 GMT+0000 (Coordinated Universal Time) https://www.opris.exchange/cryptocurrency-exchange-development/

@oprisexchange #cryptoexchange #cryptocurrency #bitcoin #binanceclone #opris

star

Mon Feb 17 2025 10:00:00 GMT+0000 (Coordinated Universal Time) https://www.coinsclone.com/white-label-crypto-wallet/

@CharleenStewar #whitelabelcryptowallet #whitelabelwallet #whitelabelsolutions #cryptowallet

star

Mon Feb 17 2025 09:19:26 GMT+0000 (Coordinated Universal Time) https://www.coinsclone.com/nft-minting-platform-development/

@Emmawoods

star

Mon Feb 17 2025 08:54:38 GMT+0000 (Coordinated Universal Time) https://github.com/EnsembleData/tiktok-scraper

@zerozero

star

Mon Feb 17 2025 08:54:13 GMT+0000 (Coordinated Universal Time) https://github.com/EnsembleData/tiktok-scraper

@zerozero

star

Mon Feb 17 2025 08:53:43 GMT+0000 (Coordinated Universal Time) https://github.com/EnsembleData/tiktok-scraper

@zerozero

star

Mon Feb 17 2025 08:53:33 GMT+0000 (Coordinated Universal Time) https://github.com/EnsembleData/tiktok-scraper

@zerozero

Save snippets that work with our extensions

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