Snippets Collections
SELECT * from INFORMATION_SCHEMA.VIEWS
import java.util.ArrayList;
import java.util.Scanner;

public class LibrarySystem {

    private static ArrayList<Book> books = new ArrayList<>();
    private static Scanner scanner = new Scanner(System.in);

    public static void main(String[] args) {
        while (true) {
            displayMenu();
            int choice = scanner.nextInt();
            scanner.nextLine(); // Consume the newline character

            switch (choice) {
                case 1:
                    addBook();
                    break;
                case 2:
                    viewBookList();
                    break;
                case 3:
                    searchBook();
                    break;
                case 4:
                    System.out.println("Exiting program. Goodbye!");
                    System.exit(0);
                default:
                    System.out.println("Invalid choice. Please try again.");
            }
        }
    }

    private static void displayMenu() {
        System.out.println("Library System Menu:");
        System.out.println("1. Add Book");
        System.out.println("2. View Book List");
        System.out.println("3. Search for Book");
        System.out.println("4. Exit");
        System.out.print("Enter your choice: ");
    }

    private static void addBook() {
        System.out.print("Enter book title: ");
        String title = scanner.nextLine();

        System.out.print("Enter author: ");
        String author = scanner.nextLine();

        books.add(new Book(title, author));
        System.out.println("Book added successfully!");
    }

    private static void viewBookList() {
        if (books.isEmpty()) {
            System.out.println("No books in the library yet.");
        } else {
            System.out.println("Book List:");
            for (Book book : books) {
                System.out.println("Title: " + book.getTitle() + ", Author: " + book.getAuthor());
            }
        }
    }

    private static void searchBook() {
        System.out.print("Enter book title to search: ");
        String searchTitle = scanner.nextLine();

        boolean found = false;
        for (Book book : books) {
            if (book.getTitle().equalsIgnoreCase(searchTitle)) {
                System.out.println("Book found: Title: " + book.getTitle() + ", Author: " + book.getAuthor());
                found = true;
                break;
            }
        }

        if (!found) {
            System.out.println("Book with title '" + searchTitle + "' not found.");
        }
    }

    private static class Book {
        private String title;
        private String author;

        public Book(String title, String author) {
            this.title = title;
            this.author = author;
        }

        public String getTitle() {
            return title;
        }

        public String getAuthor() {
            return author;
        }
    }
}

function perimeter(l, num){
	let dict = new Object();
	dict = {
		's' : 4*num,
		'c' : 2*num*3.14,
	};
	return dict[l] || undefined;
}
function num_of_digits(num) {
	let cnt = 1;
	num = Math.abs(num);
	num = Math.floor(num/10);
	while(num != 0){
		cnt = cnt+1;
		num = Math.floor(num/10);
	}
	return cnt;
}
Sales Rep Rank =

RANKX(
	ALL( Sales[Sales Rep]),
	[Total Sales],
	Dense
)

//Dense = not skip
import java.util.Scanner;
public class RootsOfDemo {
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);

        double det,root1,root2;

        System.out.println("ENTER THE VALUES OF a,b,and c :");

        int a = sc.nextInt();
        int b = sc.nextInt();
        int c = sc.nextInt();

        det = (b*b)- 4*a*c;

        if(det>0){
            System.out.println("Roots are Real and Distinct ");
            root1 = (-b) + Math.sqrt(det)/(2*a);
            root2 = (-b) - Math.sqrt(det)/(2*a);
            System.out.println("The Roots are : "+ root1 + root2);
        }

        else if(det==0){
            System.out.println("Roots are Real and Equal ");
            root1 = -b/2*a;
            System.out.println("The Roots are : "+ root1 + root1);
        }

        else{
            System.out.println("Roots are Imaginary ");
            double img = Math.sqrt(det*-1)/2*a;
            //System.out.println("The real part is "+ -b/2*a +" The imaginary part is "+ ( Math.sqrt(det*-1)/2*a ) +"i" );
            System.out.println("The img roots are "+ -b/2*a +"+"+ img + "i");
            System.out.println("The img roots are "+ -b/2*a +"-"+ img + "i");
        }


    }
    
}
Table =

{
	("Nik", 101),
	("Hafiz", 102),
}
Table =

DATATABLE(
	"SNo", INTEGER,
	"Name", STRING,
	{
		{101, "Nik"},
		{102, "Hafiz"},
	}
)
shadow-[0_0_5px_black] hover:shadow-[0_0_15px_black] transition duration-500
var storeName = HttpUtility.ParseQueryString(urlAddress).Get("storeName");
Add following Code in Program.CS :
     builder.Services.AddSession(options =>
     {
         options.IdleTimeout = TimeSpan.FromMinutes(30);
     });
app.UseSession();

In Controller use the following Code: 
To get the Session:
 HttpContext.Session.SetString("Name", "John Smith");

To set the Session:
 ViewBag.Name = HttpContext.Session.GetString(sessionName);


Best Selling Day/Date =

CONCATENATEX(
	TOPN(
		1,
		'Calendar',
		[Total Sales]
		),
	FORMAT( 'Calendar'[Date], "dd-mmm" )
	)
 private readonly dbContext _context;

 public MonthReportsController(dbContext context)
 {
     _context = context;
 }
Top Selling Product =

TOPN(
	1,
	VALUES( Sales[ProductID] ),
	[Total Sales]
)
Best Selling Day/Date =

TOPN(
	1,
	'Calendar',
	[Total Sales]
)
In Program.Cs add following Code: 

Builder.services.Configure<IdentityOptions>(options => 
{     
    options.Password.RequireDigit = true; 
    options.Password.RequireLowercase = true; 
    options.Password.RequireNonAlphanumeric = true; 
    options.Password.RequireUppercase = true; 
    options.Password.RequiredLength = 6; 
    options.Password.RequiredUniqueChars = 1; 
});
(function($){
		'use strict';
		$(document).on('ready', function(){ 

		$('#pcp_wrapper-151 .sp-pcp-post').each(function(){

          var target_url = $(this).find('.sp-pcp-title a').attr('href');
   	 $(this).click(function(){
     			 window.open(target_url, '_self');
     });
          
 
        });
      	});
})(jQuery);
from django.shortcuts import render
from django.http import HttpResponseRedirect, HttpResponse
from django.contrib.auth.models import User
from django.shortcuts import get_object_or_404, render, redirect
from .models import CarModel
from .restapis import get_dealer_by_id, get_dealers_from_cf, get_dealers_by_state, get_dealer_reviews_from_cf, post_request
from django.contrib.auth import login, logout, authenticate
from django.contrib import messages
from datetime import datetime
import logging
import json

# Getting an instance of a logger
logger = logging.getLogger(__name__)

def dealership_list(request):
    url = "https://us-south.functions.appdomain.cloud/api/v1/web/54ee907b-434c-4f03-a1b3-513c235fbeb4/default/myAction"
    dealerships = get_dealers_from_cf(url)  # provide the url argument
    return render(request, 'djangoapp/dealership_list.html', {'dealerships': dealerships})

# View to render the index page with a list of dealerships
def get_dealerships(request):
    if request.method == "GET":
        context = {}
        url = "https://9bebcb01.eu-de.apigw.appdomain.cloud/api/dealership"
        # Get dealers from the Cloudant DB
        context["dealerships"] = get_dealers_from_cf(url)

        # dealer_names = ' '.join([dealer.short_name for dealer in context["dealerships"]])
        # return HttpResponse(dealer_names)

        return render(request, 'djangoapp/index.html', context)

# View to render a static about page
def about(request):
    context = {}
    if request.method == "GET":
        return render(request, 'djangoapp/about.html', context)


# View to return a static contact page
def contact(request):
    context = {}
    if request.method == "GET":
        return render(request, 'djangoapp/contact.html', context)


# View to handle sign in request
def login_request(request):
    context = {}
    if request.method == "POST":
        username = request.POST['username']
        password = request.POST['psw']
        user = authenticate(username=username, password=password)
        if user is not None:
            login(request, user)
            return redirect('djangoapp:index')
        else:
            context['message'] = "Invalid username or password."
            return render(request, 'djangoapp/login.html', context)
    else:
        return render(request, 'djangoapp/login.html', context)


# View to handle sign out request
def logout_request(request):
    # Get the user object based on session id in request
    print("Logging out `{}`...".format(request.user.username))
    # Logout user in the request
    logout(request)
    # Redirect user back to course list view
    return redirect('djangoapp:index')


# View to handle sign up request
def registration_request(request):
    context = {}
    # If it is a GET request, just render the registration page
    if request.method == 'GET':
        return render(request, 'djangoapp/registration.html', context)
    # If it is a POST request
    elif request.method == 'POST':
        # Get user information from request.POST
        username = request.POST['username']
        password = request.POST['psw']
        first_name = request.POST['firstname']
        last_name = request.POST['lastname']
        user_exist = False
        try:
            # Check if user already exists
            User.objects.get(username=username)
            user_exist = True
        except:
            # If not, simply log this is a new user
            logger.debug("{} is new user".format(username))
        # If it is a new user
        if not user_exist:
            # Create user in auth_user table
            user = User.objects.create_user(username=username, first_name=first_name, last_name=last_name,
                                            password=password)
            # Login the user and redirect to course list page
            login(request, user)
            return redirect("/djangoapp/")
        else:
            return render(request, 'djangoapp/registration.html', context)


# View to render the reviews of a dealer
def get_dealer_details(request, dealer_id):
    context = {}
    if request.method == "GET":
        url = 'https://9bebcb01.eu-de.apigw.appdomain.cloud/api/review'
        reviews = get_dealer_reviews_from_cf(url, dealer_id=dealer_id)
        context = {
            "reviews":  reviews, 
            "dealer_id": dealer_id
        }

        return render(request, 'djangoapp/dealer_details.html', context)


# View to submit a new review
def add_review(request, dealer_id):
    # User must be logged in before posting a review
    if request.user.is_authenticated:
        # GET request renders the page with the form for filling out a review
        if request.method == "GET":
            url = f"https://5b93346d.us-south.apigw.appdomain.cloud/dealerships/dealer-get?dealerId={dealer_id}"
            # Get dealer details from the API
            context = {
                "cars": CarModel.objects.all(),
                "dealer": get_dealer_by_id(url, dealer_id=dealer_id),
            }
            return render(request, 'djangoapp/add_review.html', context)

        # POST request posts the content in the review submission form to the Cloudant DB using the post_review Cloud Function
        if request.method == "POST":
            form = request.POST
            review = dict()
            review["name"] = f"{request.user.first_name} {request.user.last_name}"
            review["dealership"] = dealer_id
            review["review"] = form["content"]
            review["purchase"] = form.get("purchasecheck")
            if review["purchase"]:
                review["purchase_date"] = datetime.strptime(form.get("purchasedate"), "%m/%d/%Y").isoformat()
            car = CarModel.objects.get(pk=form["car"])
            review["car_make"] = car.car_make.name
            review["car_model"] = car.name
            review["car_year"] = car.year
            
            # If the user bought the car, get the purchase date
            if form.get("purchasecheck"):
                review["purchase_date"] = datetime.strptime(form.get("purchasedate"), "%m/%d/%Y").isoformat()
            else: 
                review["purchase_date"] = None

            url = "https://9bebcb01.eu-de.apigw.appdomain.cloud/api/review"  # API Cloud Function route
            json_payload = {"review": review}  # Create a JSON payload that contains the review data

            # Performing a POST request with the review
            result = post_request(url, json_payload, dealerId=dealer_id)
            if int(result.status_code) == 200:
                print("Review posted successfully.")

            # After posting the review the user is redirected back to the dealer details page
            return redirect("djangoapp:dealer_details", dealer_id=dealer_id)

    else:
        # If user isn't logged in, redirect to login page
        print("User must be authenticated before posting a review. Please log in.")
        return redirect("/djangoapp/login")

function printPDFfromURL(pdf) { 
	var iframe = document.createElement('iframe');
	iframe.style.display = 'none';
	document.body.appendChild(iframe);

	iframe.onload = function() {
		iframe.contentWindow.print();
		setTimeout(()=>{
			iframe.remove()
		}, 60000);
	};
	iframe.src = pdf;
}

//use:
//  printPDFfromURL("http://localhost/path_pdf.pdf");
$ git commit -m "Something terribly misguided" # (0: Your Accident)
$ git reset HEAD~                              # (1)
[ edit files as necessary ]                    # (2)
$ git add .                                    # (3)
$ git commit -c ORIG_HEAD                      # (4)
<div class=" w-full h-screen p-4">

    <div class="h-14 w-full bg-slate-100 rounded-md font-semibold text-gray-800 flex items-center text-center px-2 transition-colors">
        <div class=" basis-1/3 rounded-md bg-white py-2 shadow-sm">New Items</div>
        <div class=" basis-1/3 rounded-md ">Return Items</div>
        <div class=" basis-1/3 rounded-md ">Issue Items</div>
    </div>

</div>
Qtr =

SWITCH(
	TRUE(),
	MONTH('Calendar[Date]') <=3, "Q1",
	MONTH('Calendar[Date]') <=6, "Q2",
	MONTH('Calendar[Date]') <=9, "Q3",
	"Q4"
)
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js" ></script>
<style>
    section.heroCarousel-container.mobile {
     display: none;
    }
    @media (max-width:551px){
        section.heroCarousel-container{
            display: none;
        }
        section.heroCarousel-container.mobile {
            display: block;
        }
        section.heroCarousel-container.mobile .slick-slide {
            display: flex !important;
            justify-content: center;
            position: relative;
        }
        .mobile-carousal-btns {
            position: absolute;
            top: 65%;
            margin: 0 auto;
            width: auto;
        }
        section.heroCarousel-container.mobile .slick-slide img {
            display: block;
            width: 100%;
            /*height: 380px;*/
        }
        /*.cstm-pos{*/
        /*    position: absolute;*/
        /*    background: none !important;*/
        /*    margin-top: 41%;*/
        /*    text-align: center;*/
        /*}*/
        .cstm-pos {
            position: absolute;
            background: none !important;
            text-align: center;
            top: 50%;
        }
        .heroCarousel-content{
            background-color: transparent;
        }
        .carousal-container-mbl{
            display: flex;
            justify-content: center;
            align-items: center;
        }
    }
</style>


{{inject 'hasMainCarousel' true}}
<section class="heroCarousel-container desktop {{#if theme_settings.carousel_banners}} heroCarousel-container--hasBanners{{/if}}">
    <div class="heroCarousel"
        data-slick='{
            "dots": true,
            "mobileFirst": true,
            "slidesToShow": 1,
            "slidesToScroll": 1,
            "autoplay": true,
            "autoplaySpeed": {{carousel.swap_frequency}},
            "lazyLoad": "anticipated"
        }'
        {{#if theme_settings.carousel_video_mute}} data-youtube-mute{{/if}}>
        {{#each carousel.slides}}
        <div class="heroCarousel-slide {{#if ../theme_settings.homepage_carousel_style '==' 'stretch'}}heroCarousel-slide--stretch{{/if}} heroCarousel-slide--{{@index}}{{#if @first}} heroCarousel-slide--first{{/if}}">
            <div class="heroCarousel-image-wrapper{{#and image_height image_width}} heroCarousel-image-wrapper--sized{{/and}}">
                <a href="{{url}}">
                    {{#if @index '==' 0}}
                        {{#if (merge this video=../../theme_settings.carousel_vid0)}}{{/if}}
                    {{/if}}
                    {{#if @index '==' 1}}
                        {{#if (merge this video=../../theme_settings.carousel_vid1)}}{{/if}}
                    {{/if}}
                    {{#if @index '==' 2}}
                        {{#if (merge this video=../../theme_settings.carousel_vid2)}}{{/if}}
                    {{/if}}
                    {{#if @index '==' 3}}
                        {{#if (merge this video=../../theme_settings.carousel_vid3)}}{{/if}}
                    {{/if}}
                    {{#if @index '==' 4}}
                        {{#if (merge this video=../../theme_settings.carousel_vid4)}}{{/if}}
                    {{/if}}

                    

                    {{#if video}}
                        <div class="heroCarousel-video-wrapper">
                            <div class="heroCarousel-image-box" style="{{#if image_width}}width:{{image_width}}px{{/if}}">
                                {{#and image_height image_width}}<div class="heroCarousel-image-box-padding" style="padding-bottom:{{multiply (divide image_height image_width) 100}}%">{{/and}}
                                    {{> components/common/responsive-img
                                        image=stencil_image
                                        class="heroCarousel-image"
                                        fallback_size='1920w'
                                        lazyload='disabled'
                                    }}
                                {{#and image_height image_width}}</div>{{/and}}
                            </div>
                            <div class="heroCarousel-video"><div data-youtube="{{video}}"></div></div>
                        </div>
                    {{else}}
                        <div class="heroCarousel-image-box" style="{{#if image_width}}width:{{image_width}}px{{/if}}">
                            {{#and image_height image_width}}<div class="heroCarousel-image-box-padding" style="padding-bottom:{{multiply (divide image_height image_width) 100}}%">{{/and}}
                                {{#if @first}}
                                    {{> components/common/responsive-img
                                        image=stencil_image
                                        class="heroCarousel-image"
                                        fallback_size='1920w'
                                        lazyload='disabled'
                                        otherAttributes=(concat (concat (concat (concat 'width="' image_width) '" height="') image_height) '"')
                                    }}
                                {{else}}
                                    {{> components/common/responsive-img
                                        image=stencil_image
                                        class="heroCarousel-image"
                                        fallback_size='1920w'
                                        lazyload='lazyload'
                                        otherAttributes=(concat (concat (concat (concat 'width="' image_width) '" height="') image_height) '"')
                                    }}
                                {{/if}}
                            {{#and image_height image_width}}</div>{{/and}}
                        </div>
                    {{/if}}
                    
                    {{#if heading}}
                        {{> components/carousel-content show_background=true}}
                    {{else}}
                        {{#if text}}
                            {{> components/carousel-content show_background=true}}
                        {{else}}
                            {{#if button_text}}
                                {{> components/carousel-content show_background=false}}
                            {{/if}}
                        {{/if}}
                    {{/if}}
                </a>
            </div>
        </div>
        {{/each}}
    </div>
    {{#if theme_settings.carousel_banners}}
        <div class="heroCarousel-banners">
            {{> components/papa-supermarket/sections/section-bc-banner find="papathemesHeroCarouselBanner"}}
        </div>
    {{/if}}
</section>


<!--Custome Carousal for Mobile-->
<section class="heroCarousel-container mobile {{#if theme_settings.carousel_banners}} heroCarousel-container--hasBanners{{/if}}">
    <div class="heroCarousel"
        data-slick='{
            "dots": true,
            "mobileFirst": true,
            "slidesToShow": 1,
            "slidesToScroll": 1,
            "autoplay": true,
            "autoplaySpeed": {{carousel.swap_frequency}},
            "lazyLoad": "anticipated"
        }'
        {{#if theme_settings.carousel_video_mute}} data-youtube-mute{{/if}}>
       
            
    <a href="/" class="cstm-l0">
            <div class="carousal-container-mbl" >
                <img src="https://cdn11.bigcommerce.com/s-r5k51kqrix/product_images/uploaded_images/mobile-carousal-66.jpg" />
    		    <!--<a href="https://www.smartwheel.ca/inokim/" class="heroCarousel-action button button--primary button--large mobile mobile-carousal-btns"></a>-->
    		    <div class="cstm-pos cstm-c0" ></div>
            </div>
        </a>
        
        <a href="/" class="cstm-l1">
            <div class="carousal-container-mbl" >
                <img src="https://cdn11.bigcommerce.com/s-r5k51kqrix/product_images/uploaded_images/mobile-carousal-57.jpg" />
    		    <!--<a href="https://www.smartwheel.ca/inokim/" class="heroCarousel-action button button--primary button--large mobile mobile-carousal-btns"></a>-->
    		    <div class="cstm-pos cstm-c1" ></div>
            </div>
        </a>
		    
        
        <a href="/" class="cstm-l2">
            <div class="carousal-container-mbl" >
                <img src="https://cdn11.bigcommerce.com/s-r5k51kqrix/product_images/uploaded_images/mobile-carousal-53.jpeg" />
            	<!--<a href="/nanrobot-d6-e-scooter-10-2000w-52v-26ah-black/" class="heroCarousel-action button button--primary button--large mobile mobile-carousal-btns">Pre-Order Now</a>-->
                <div class="cstm-pos cstm-c2" ></div>
            </div>
        </a>
       
        <a href="/" class="cstm-l3">
            <div class="carousal-container-mbl" >
                <img src="https://cdn11.bigcommerce.com/s-r5k51kqrix/product_images/uploaded_images/mobile-carousal-31.jpeg"/>
        	    <!--<a href="/OneWheel_c_114.html" class="heroCarousel-action button button--primary button--large mobile mobile-carousal-btns">Learn More</a>-->
        	    <div class="cstm-pos cstm-c3" ></div>
    	    </div>
        </a>
    
            <a href="/" class="cstm-l4">
            <div class="carousal-container-mbl" >
                <img src="https://cdn11.bigcommerce.com/s-r5k51kqrix/product_images/uploaded_images/mobile-carousal-64.jpg" />
        		<!--<a href="/SmartKick_c_127.html" class="heroCarousel-action button button--primary button--large mobile mobile-carousal-btns">Buy Now</a>-->
                <div class="cstm-pos cstm-c4" ></div>
            </div> 
        </a>
      
    </div>
    {{#if theme_settings.carousel_banners}}
        <div class="heroCarousel-banners">
            {{> components/papa-supermarket/sections/section-bc-banner find="papathemesHeroCarouselBanner"}}
        </div>
    {{/if}}
</section>

<script>
    $(document).ready(function(){
        console.log("test")
        setTimeout(function(){
            var i=0;
            $(".desktop .slick-track .heroCarousel-slide").each(function(index, element) {
                console.log("test")
                try{
                    if (!$(this).hasClass("slick-cloned")) {
                        
                        var des =$(".heroCarousel-content",$(element)).html();
                        
                        $(".cstm-c"+i).append(des);
                        
                        var href = $("a",$(element)).attr('href');
                        
                        $(".cstm-l"+i).attr("href", href);
        
                        i++;
                    }
                }
                catch(e){}
            });
        }, 1000);
    })
</script>
    r = sr.Recognizer()
    with anvil.media.TempFile(AudioFile) as file_name:
      with sr.AudioFile(file_name) as source:
        audio = r.record(source)
    response = r.recognize_google(audio)
// C++ program to find LCM of two numbers 
#include <iostream> 
using namespace std; 

// Recursive function to return gcd of a and b 
long long gcd(long long int a, long long int b) 
{ 
if (b == 0) 
	return a; 
return gcd(b, a % b); 
} 

// Function to return LCM of two numbers 
// Time Complexity: O(log(min(a,b) 
// Auxiliary Space: O(log(min(a,b))
long long lcm(int a, int b) 
{ 
	return (a / gcd(a, b)) * b; 
} 

// Function to return LCM of two numbers  Time Complexity: O(min(a,b))
int LCM(int a, int b) 
{ 
    int greater = max(a, b); 
    int smallest = min(a, b); 
    for (int i = greater; ; i += greater) { 
        if (i % smallest  == 0) 
            return i; 
    } 
} 

// Driver program to test above function 
int main() 
{ 
	int a = 15, b = 20; 
	cout <<"LCM of " << a << " and "
		<< b << " is " << lcm(a, b); 
	return 0; 
} 
#include <bits/stdc++.h>
using namespace std;

#define sr srand(time(0));
#define ra(l, h) (rand() % ((h)-(l)+1) + (l))
#define sync { ios_base::sync_with_stdio(false); cin.tie(NULL); cout.tie(NULL); }
#define ll long long int
#define vi vector<int>
#define fn(n) for(int i = 0; i < n; i++)
#define fr(i, a, b) for(int i = a; i <= b; i++)
#define rfr(i, a, b) for(int i = a; i >= b; i--)
#define pb push_back
#define all(a) a.begin(), a.end()
#define tt int test; cin >> test; while(test--)
#define ff first
#define ss second
#define en cout<< "\n"
#define cy cout << "YES" << endl
#define cn cout << "NO" << endl



int countTrailingZeros(int num) {
    int count = 0;
    while (num % 10 == 0) {
        count++;
        num /= 10;
    }
    return count;
}

bool isPrime(int n) {
    if (n <= 1) {
        return false;
    }
    for (int i = 2; i * i <= n; i++) {
        if (n % i == 0) {
            return false;
        }
    }
    return true;
}


int main() {
    sync
    tt {
        int n;
        cin >> n;
        vi v(n);
        fn(n) cin >> v[i];
    
        int commonZeros = countTrailingZeros(v[0]);

        for (int i = 1; i < n; i++) {
            int trailingZeros = countTrailingZeros(v[i]);
            commonZeros = min(commonZeros, trailingZeros);
        }
        
        // cout << commonZeros << " ";
        
        int ans = 0;
        set<int> rem;
        for(ll k=2; k<pow(10,18); k++){
            if( isPrime(k) ) {
                k = k * pow(10, commonZeros);
                for(int i=0; i<n; i++){
                    rem.insert(v[i]%k);
                }
                if(rem.size() == 2){
                    ans = k;
                    break;
                }
            }
        }
        
        cout << ans << endl;
    }
    return 0;
}
#include <bits/stdc++.h>
using namespace std;

#define sr srand(time(0));
#define ra(l, h) (rand() % ((h)-(l)+1) + (l))
#define sync { ios_base::sync_with_stdio(false); cin.tie(NULL); cout.tie(NULL); }
#define ll long long int
#define vi vector<int>
#define fn(n) for(int i = 0; i < n; i++)
#define fr(i, a, b) for(int i = a; i <= b; i++)
#define rfr(i, a, b) for(int i = a; i >= b; i--)
#define pb push_back
#define all(a) a.begin(), a.end()
#define tt int test; cin >> test; while(test--)
#define ff first
#define ss second
#define en cout<< "\n"
#define cy cout << "YES" << endl
#define cn cout << "NO" << endl


int main() {
    sync
    tt {
        int n;
        cin >> n;
        vi v(n);
        fn(n) cin >> v[i];
        
        fn(n) cout<<v[i]<<" ";
      	cout << "\n";
        
        
    }
    return 0;
}



/*
        
*/ 
            
	function getGoldPrice($apiKey,$symbol) {
  
    $curr = "USD";
    $date = "";

    $url = "https://www.goldapi.io/api/{$symbol}/{$curr}{$date}";

    $myHeaders = array(
        'x-access-token: ' . $apiKey,
        'Content-Type: application/json'
    );

    $curl = curl_init();

    curl_setopt_array($curl, array(
        CURLOPT_URL => $url,
        CURLOPT_RETURNTRANSFER => true,
        CURLOPT_FOLLOWLOCATION => true,
        CURLOPT_HTTPHEADER => $myHeaders
    ));

    $response = curl_exec($curl);
    $error = curl_error($curl);

    curl_close($curl);

    if ($error) {
        return 'Error: ' . $error;
    } else {
        $data = json_decode($response, true);

        // Check if the response contains a 'price' key
        if (isset($data['price'])) {
            return $data['price'];
        } 
    }
}
	
	function fetchDataAndInsertIntoDatabase($pdo)
	{
		$apiKey = "goldapi-xxd2ktl4miz8nf-io";
		$symbol = "XAU";
		$curr = "SAR";
		$date = "";
		$myHeaders = array(
		'x-access-token: ' . $apiKey,
		'Content-Type: application/json'
		);

		$curl = curl_init();
		$url = "https://www.goldapi.io/api/{$symbol}/{$curr}{$date}";

		curl_setopt_array($curl, array(
		CURLOPT_URL => $url,
		CURLOPT_RETURNTRANSFER => true,
		CURLOPT_FOLLOWLOCATION => true,
		CURLOPT_HTTPHEADER => $myHeaders
		));
		$response = curl_exec($curl);
		$error = curl_error($curl);
		curl_close($curl);

		if ($error) {
		//	echo 'Error: ' . $error;
		} else {
			$data = json_decode($response, true);
			if ($data !== null) {
				$price_gram_24k = $data['price_gram_24k'];
				$price_gram_22k = $data['price_gram_22k'];
				$price_gram_21k = $data['price_gram_21k'];
				$price_gram_20k = $data['price_gram_20k'];
				$price_gram_18k = $data['price_gram_18k'];
				$price_gram_16k = $data['price_gram_16k'];
				$price_gram_14k = $data['price_gram_14k'];
				$price_gram_10k = $data['price_gram_10k'];
				$timestamp = $data['timestamp'];
				$goldPrice = getGoldPrice($apiKey,$symbol);

				try {
					$stmt = $pdo->prepare("INSERT INTO gold (price_gram_24k, price_gram_22k, price_gram_21k, price_gram_20k, price_gram_18k, price_gram_16k, price_gram_14k, price_gram_10k, timestamp,price) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?,?)");

					$stmt->execute([$price_gram_24k,$price_gram_22k, $price_gram_21k, $price_gram_20k, $price_gram_18k, $price_gram_16k,$price_gram_14k,$price_gram_10k, $timestamp,$goldPrice]);

					// echo 'Data inserted successfully!';
				} catch (PDOException $e) {
				//	echo 'Error: ' . $e->getMessage();
				} finally {
					$pdo = null;
				}
			} else {
			//	echo 'Error decoding JSON';
			}
		}
	}
    r = sr.Recognizer()
    with anvil.media.TempFile(AudioFile) as file_name:
      with sr.AudioFile(file_name) as source:
        audio = r.record(source)
    response = r.recognize_google(audio)
function sortEvents(events) {
  //   return Object.keys(events)
  //     .sort()
  //     .reduce((sortedEvents, key) => {
  //       sortedEvents[key] = events[key];
  //       return sortedEvents;
  //     }, {});

  const sortedEvents = {};
  Object.keys(events)
    .sort()
    .forEach((key) => {
      sortedEvents[key] = events[key];
    });
  return sortedEvents;
}
function add_prefix_to_prices($price) {
    // قم بتحديد الكلمة أو التاج الذي تريد إضافته
    $prefix = '<div class=div_p>ajax</div>';

    // قم بإرجاع السعر مع الكلمة أو التاج
    return $prefix . $price;
}

add_filter('woocommerce_get_price_html', 'add_prefix_to_prices');
add_filter('woocommerce_cart_item_price', 'add_prefix_to_prices');
add_filter('woocommerce_cart_item_subtotal', 'add_prefix_to_prices');
@media (min-width:768px) and (max-width:920px) {
    nav ul {
        gap: 50px;
        margin-left: 0px;
    }

    .iknow {
        position: relative;
        right: 0px;
        align-items: center;
        /* top: 20px; */
        margin-top: 20%;
    }
    #aditya img{
        width: 11%;
    }
    .connect{
        top: 24%;
    }
    .banner h2{
        font-size: 16px;
        top: 16%;
    }   
    .banner {
        height: 113px;
    }
    #bannerimgrec{
        height: 115px;
    }
}
  @import url('https://fonts.googleapis.com/css2?family=Aclonica&display=swap');
  @import url('https://fonts.googleapis.com/css2?family=Aoboshi+One&display=swap');
  @import url('https://fonts.googleapis.com/css2?family=Amaranth&display=swap');
  @import url('https://fonts.googleapis.com/css2?family=Amaranth&family=Bubblegum+Sans&display=swap');
  @import url('https://fonts.googleapis.com/css2?family=Aldrich&display=swap');
  @import url('https://fonts.googleapis.com/css2?family=Andika&display=swap');
  @import url('https://fonts.googleapis.com/css2?family=Atma:wght@600&display=swap');
  @import url('https://fonts.googleapis.com/css2?family=Black+Ops+One&family=Ubuntu&display=swap');
  @import url('https://fonts.googleapis.com/css2?family=Candal&display=swap');
  @import url('https://fonts.googleapis.com/css2?family=Ubuntu:wght@700&display=swap');

  body {
      padding: 0;
      margin: 0;
      background: #392467;
      overflow-x: hidden;
      scroll-behavior: smooth;
      /* overflow-y: hidden; */
  }

  nav {
      display: flex;
      align-items: center;
      justify-content: space-between;
  }

  nav ul li a {
      text-decoration: none;
      font-family: 'Aoboshi One', serif;
      color: white;
      font-size: 25px;
  }

  nav ul li {
      list-style: none;
  }

  nav ul {
      gap: 90px;
      display: flex;
      margin-left: 46px;
  }

  .downloadcv a {
      position: absolute;
      right: 32px;
      top: 15px;
      list-style: none;
      text-decoration: none;
      /* font-family: 'Aclonica', sans-serif; */
      font-size: 25PX;
      color: white;
      font-family: 'Aoboshi One', serif;
      transition: all 0.4s ease-in-out;
  }

  .downloadcv a:hover {
      transform: scale(1.09);
      transition: all 0.4s ease-in-out;
  }

  .downloadcv img {
      width: 220px;
      position: relative;
      /* left: 37px; */
      right: 8px;
      top: 2px;
      /* height: 41px;*/
      transition: all 0.5s ease-in-out;
  }

  .banner a img {
      width: 11%;
      position: absolute;
      left: 3%;
      top: 75px;
  }

  .banner h2 {
      position: absolute;
      top: 25px;
      font-family: 'Amaranth', sans-serif;
      color: white;
      font-weight: 300;
      top: 18%;
      left: 18%;
      font-size: 20px;
  }


  .section h4 {
      font-family: 'Aoboshi One', serif;
      font-size: 15px;
      color: white;
      font-weight: 400;
      margin: 0;
  }

  .connect {
      display: flex;
      position: absolute;
      top: 29%;
      right: 2%;
      align-items: center;

  }

  .connectimg {
      display: flex;
      align-items: center;
      position: relative;
      margin-top: 9px;
      gap: 4px;

  }

  .connectimg li a {
      text-decoration: none;
  }

  .connectimg li {
      list-style: none;
      text-decoration: none;
  }

  #link img {
      width: 25px;
  }

  #x img {
      width: 19px;
  }

  .connectimg {
      margin-left: 5px;
  }

  .connectimg img {
      width: 20px;
  }

  .heading h1 {

      color: white;
      font-size: 70px;
      margin: 0;
      font-weight: 400;
      letter-spacing: 3px;
      /* font-family: 'Aclonica', sans-serif; */
      font-family: 'Aoboshi One', serif;
      text-shadow: 0px 8px 40px rgba(255, 255, 255, 0.316);
  }

  .heading h2 {
      font-size: 50px;
      margin: 0;
      letter-spacing: 3px;
      font-weight: 400;
      font-family: 'Aclonica', sans-serif;
      font-family: 'Aoboshi One', serif;
      color: white;
      text-shadow: 0px 8px 40px rgba(255, 255, 255, 0.316);

  }

  .heading {
      position: relative;
      top: 80px;
      left: 15%;
  }

  .iknow {
      position: absolute;
      right: 90px;
      align-items: center;
  }

  .iknow h1 {
      font-family: 'Bubblegum Sans', sans-serif;
      color: white;
      font-weight: 300;
  }

  .know {
      display: flex;
      justify-content: center
  }

  .img {
      display: flex;
      justify-content: center;
  }

  .img img {
      width: 60px;
  }

  .overlay {
      display: flex;
      justify-content: center;
      align-items: center;
      position: relative;
      top: 10rem;
      /* left: 11rem;
      right: 11rem; */
      /*width: 1000px;
      border-radius: 30px;
      height: 350px;
      background-color: #5D3587;
      margin-bottom: 30px; */
  }

  .inerabout {
      position: relative;
      left: 0%;
      top: -352px;
  }

  .inercontent {
      position: relative;
      top: -43vh;
  }

  .ul {
      line-height: 3;
      font-size: 1.3rem;
  }

  .about {
      display: flex;
      justify-content: center;
      align-items: center;
      text-align: center;
      margin: 0;

  }

  .about h1 {
      color: #FFF;
      margin: 0;
      margin-top: 20px;
      margin-bottom: 10px;
      font-family: 'Aclonica', sans-serif;
      font-size: 2.5rem;
      text-shadow: 0px 8px 40px rgba(0, 0, 0, 0.25);
      font-style: normal;
      font-weight: 400;
      line-height: normal;
  }

  .aboutcontent h1 {
      color: #D2D2D2;
      margin: 0;
      text-align: center;
      text-shadow: 0px 8px 40px rgba(0, 0, 0, 0.25);
      font-family: 'Aldrich', sans-serif;
      font-size: 1.8rem;
      font-style: normal;
      font-weight: 400;
      line-height: normal;
  }

  .aboutcontent p {
      font-family: 'Andika', sans-serif;
      color: #fff;
  }

  .aboutcontent ul li {
      font-family: 'Andika', sans-serif;
      color: #fff
  }

  .marquee {
      position: relative;
      top: 213px;
  }

  .marquee h1 {
      font-family: 'Ubuntu', sans-serif;
      font-size: 5rem;
      margin-bottom: px;
      color: #ffffff08;
  }

  .projects img {
      width: 28%;
  }

  .projects h1 {
      display: flex;
      justify-content: center;
      align-items: center;
      position: relative;
      top: -14vh;
      font-size: 3rem;
      color: white;
      font-family: 'Aclonica', sans-serif;
      text-shadow: 0px 8px 40px rgb(0, 0, 0);
  }

  .probg {
      display: flex;
      justify-content: center;
      align-items: center;
  }

  .project-flexo {
      display: flex;
      justify-content: center;
      align-items: center;
      /* right: -4%;
    position: relative; */
  }

  .ultable {
      display: flex;
      justify-content: center;
      align-items: center;
      text-align: justify;
  }

  /* .rectangle-shape{
    display: flex;
    justify-content: center;
    align-items: center;
  } */
  .bg-rec {
      display: flex;
      justify-content: center;
      align-items: center;
      gap: 10px;
      margin-left: 10px;
      margin-right: 10px;
      margin-bottom: 10px;
      margin-top: -69px;

  }

  .bg-rec li {
      list-style: none;
  }

  .bg-rec img {
      width: 100%;
      display: flex;
      border-top-right-radius: 10px;
      border-top-left-radius: 10px;
      transition: all 0.3s ease-in-out;
  }


  .text-rec {
      position: relative;
      top: -20px;
      /* color: white; */
      width: 100%;
      height: 15vh;
      background: #fff;
      border-bottom-right-radius: 10px;
      border-bottom-left-radius: 10px;
      transition: all 0.3s ease-in-out;
  }

  .text-rec:hover {
      box-shadow: 0px 8px 40px rgba(177, 177, 177, 0.397);
  }

  .text-rec h1 {
      font-family: 'Candal', sans-serif;
      color: #000;
      margin: 0;
      font-size: 20px;
      font-weight: 400;
      padding-left: 10px;

  }

  .text-rec p {
      font-family: 'Amarnath', sans-serif;
      font-size: 15px;
      font-weight: 400;
      color: #4f4f52;
      padding-left: 10px;
  }

  .text-rec a {
      text-decoration: none;
  }

  .marquee-projects {
      font-family: 'Ubuntu', sans-serif;
      font-size: 5rem;
      margin-bottom: 0px;
      color: #ffffff08;

  }

  .contactbg {
      display: flex;
      justify-content: center;
      align-items: center;
  }

  .contacthead-flexo {
      color: #D2D2D2;
      display: flex;
      justify-content: center;
      align-items: center;
      position: relative;
      top: -450px;
  }

  #c-us {
      font-size: 1.9rem;
      font-family: 'Ubuntu', sans-serif;
  }

  .p1 {
      font-size: 1.5rem;
      font-family: 'Ubuntu', sans-serif;
  }

  #bannerimgrec {
      width: 100%;
      height: 166px;
  }

  .p2,
  .p3,
  .p4 {
      font-size: 14.5px;
      font-family: 'Ubuntu', sans-serif;
      font-weight: 400;
  }

  .p3 a {
      color: #6b88ff;
  }

  footer {
      width: 100%;
      height: 8vh;
      background: #A367B1;
  }

  footer p {
      font-family: 'Ubuntu', sans-serif;
      font-weight: 600;


  }

  .copyrights {
      display: flex;
      justify-content: center;
      align-items: center;
      text-align: center;
      margin-top: -53px;
  }
<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Aditya Mishra Portfolio</title>
    <link rel="stylesheet" href="index.css">
    <link rel="shortcut icon" href="png/AdityaColoRimg 1.png">
    <link rel="stylesheet" href="media.css">
    <script src="https://kit.fontawesome.com/yourcode.js" crossorigin="anonymous"></script>
</head>

<body>
    <div id="home">
        <header>
            <nav>
                <!-- <input type="checkbox" id="check">
                <label for="check">
                    <i class="fa fa-bars"></i>
                </label> -->
                <ul class="navbar">
                    <li>
                        <a href="#home" target="_blank">Home</a>
                    </li>
                    <li>
                        <a href="#work" target="_blank">Work</a>
                    </li>
                    <li>
                        <a href="#about" target="_blank">About</a>
                    </li>
                    <li>
                        <a href="#contact" target="_blank">Contact Us</a>
                    </li>
                </ul>
                <div class="downloadcv">
                    <img src="png/Rectangle 6.png" alt="">
                    <a href="https://drive.google.com/file/d/1SkGOJ3pkXJMJo15rz8pp0PyT_a-I2G8Z/view?usp=sharing"
                        target="_blank" download="mypdffile">Download CV</a>
                </div>
            </nav>
        </header>
        <section class="section">


            <div class="banner">
                <img src="png/Rectangle 8 (1).png" alt="" id="bannerimgrec">
                <a href="#" id="aditya"><img src="png/AdityaColoRimg 1.png" alt="">
                    <style>
                        #aditya img {
                            width: 10%;
                        }
                    </style>
                </a>
                <div class="text">
                    <h2>Hi, I am Aditya Mishra A passionate front-end <br> Dev Based in New Delhi, India.
                    </h2>
                </div>
            </div>
            <div class="connect">
                <div class="connecttext">
                    <h4>Lets Connect :
                    </h4>

                </div>
                <div class="connectimg">
                    <a href="https://www.linkedin.com/in/adityamishra95/" target="_blank" id="link"><img
                            src="portfolio design/LinkedIn-Logos/LI-In-Bug.png" alt=""></a>
                    <a href="https://github.com/adityamishra2023" target="_blank" id="git"><img
                            src="portfolio design/github-mark-white.png" alt=""></a>
                    <a href="https://twitter.com/adityamishra_95" target="_blank" id="x"><img
                            src="portfolio design/logo-white.png" alt=""></a>
                </div>

            </div>
    </div>
    </section>
    <section class="sectiontwo">
        <div class="heading">
            <h2>Front-End</h2>
            <h1>Developer</h1>
        </div>
        <div class="iknow">
            <div class="know">
                <h1>What I Know</h1>
            </div>
            <div class="img">
                <img src="portfolio design/icons8-html-logo-48.png" alt="">
                <img src="portfolio design/icons8-css-logo-48.png" alt="">
                <!-- </div> -->
                <!-- <div class="img"> -->
                <img src="portfolio design/icons8-javascript-48.png" alt="">
                <img src="portfolio design/icons8-bootstrap-logo-48.png" alt="">
            </div>
        </div>

    </section>

    <section class="sectionthree" style="margin-top: 23px;  margin-bottom: -15%;">


        <div class="marquee">
            <marquee behavior="scroll" direction="left">
                <h1>&nbsp;ABOUT ABOUT ABOUT ABOUT ABOUT ABOUT ABOUT ABOUT ABOUT ABOUT ABOUT ABOUT ABOUT ABOUT ABOUT
                    ABOUT ABOUT ABOUT ABOUT ABOUT ABOUT ABOUT ABOUT ABOUT ABOUT ABOUT ABOUT ABOUT ABOUT ABOUT ABOUT
                    ABOUT ABOUT ABOUT ABOUT ABOUT</h1>
            </marquee>
        </div>
        <div id="about">
            <div class="about-container">
                <div class="headoverlay">
                    <div clabass="overlay" style="display: flex;
                justify-content: center;
                position: relative;
                top: 150px;">
                        <img src="png/Rectangle 2.png" alt="">
                    </div>
                </div>
                <div class="inerabout">

                    <div class="overlaycontent">
                        <div class="about">
                            <h1>About</h1>
                        </div>
                        <div class="aboutcontent">
                            <h1>Front-End Developer </h1>
                            <div class="ultable">

                                <ul class="ul">
                                    <p>🛠️ What I bring to the table:</p>
                                    <li>
                                        Expertise in creating robust and responsive interfaces
                                    </li>
                                    <li>Proficiency in modern web development technologies and frameworks</li>
                                    <li>Extensive experience in translating design concepts into seamless,
                                        high-performance
                                        applications
                                    </li>
                                    <li>Commitment to staying on the cutting edge of industry trends</li>
                                    <li>Strong problem-solving skills with a focus on code quality and maintainability
                                    </li>
                                </ul>
                            </div>
                        </div>
                    </div>
                </div>
            </div>

        </div>
    </section>
    <section>
        <div class="marquee-projects">
            <marquee behavior="scroll" direction="left">
                <h1 class="marquee-h1">&nbsp;PROJECT PROJECT PROJECT PROJECT PROJECT PROJECT PROJECT PROJECT</h1>
            </marquee>
            <div id="work">
                <div class="projects">
                    <div class="probg">
                        <img src="png/Rectangle 6.png" alt="">
                    </div>
                    <h1>Projects</h1>
                </div>
                <div class="rectangle-shape">
                    <div class="bg-rec">
                        <li id="red-box"><a href="https://netflix-project-11-2023.netlify.app/" target="_blank"><img
                                    src="portfolio design/netflixclone.png" alt="Netflix Project"></a>
                            <div class="text-rec">
                                <a href="https://netflix-project-11-2023.netlify.app/" target="_blank">
                                    <h1>Netflix Clone</h1>
                                </a>
                                <p>HTML, CSS</p>
                            </div>
                        </li>
                        <li id="pink-box"><a href="https://myntraclonework.netlify.app/" target="_blank"><img
                                    src="portfolio design/myntra.png" alt=""></a>
                            <div class="text-rec">
                                <a href="https://myntraclonework.netlify.app/" target="_blank">
                                    <h1>Myntra Clone</h1>
                                </a>
                                <p>HTML, CSS</p>
                            </div>
                        </li>
                        <li id="green-box"><img src="portfolio design/spotifyclone.png" alt="Spotify Clone">
                            <div class="text-rec">
                                <h1>Spotify Clone</h1>
                                </a>
                                <p>HTML, CSS</p>
                            </div>
                        </li>
                    </div>
                </div>
            </div>
    </section>
    <section>
        <div class="contact-container">
            <div class="marquee-projects">
                <marquee behavior="scroll" direction="left">
                    <h1 class="marquee-h1">&nbsp;LETS CONNECT LETS CONNECT LETS CONNECT LETS CONNECT LETS CONNECT LETS
                        CONNECT LETS CONNECT LETS CONNECT LETS CONNECT LETS CONNECT LETS CONNECT LETS CONNECT LETS
                        CONNECT LETS CONNECT LETS CONNECT LETS CONNECT </h1>
                </marquee>
            </div>
            <div id="contact">
                <div class="contactbg">
                    <img src="png/Rectangle 2.png" alt="">
                </div>
                <div class="contacthead-flexo">
                    <div class="contacthead">
                        <h1 id="c-us">Contact Us</h1>
                        <p class="p1"> 🚀 Cheers to creating engaging and memorable online <br> experiences!</p>
                        <p class="p2"> Let's connect! I'm always open to discussing exciting opportunities</p>
                        <p class="p3">📧 Email: <a
                                href="mailto:adityamishra80012@gmail.com">adityamishra80012@gmail.com</a>
                        </p>
                        <p class="p4">📍 Location: New Delhi, India </p>
                    </div>
                </div>
            </div>
        </div>
    </section>
    <footer>
        <div class="copyrights">
            <p>Copyright © 2023. All rights are reserved</p>
        </div>
    </footer>
</body>

</html>
curl -s https://packagecloud.io/install/repositories/github/git-lfs/script.deb.sh | sudo bash
{
  ...
  "content_scripts": [
    {
      "matches": ["https://*.example.com/*"],
      "include_globs": ["*example.com/???s/*"],
      "js": ["content-script.js"]
    }
  ],
  ...
}
:root {
    --theme--page_preview-padding: 0;
}
.notion-table-view{
    padding-left:0;
    padding-right:0;
}
.fullWidth .notion-frame .notion-scroller.vertical .notion-page-content>.notion-collection_view-block .notion-scroller div.notion-table-view, .fullWidth .notion-frame .notion-scroller.vertical .notion-page-content>.notion-collection_view-block>div[style*="padding-left"],
.fullWidth .notion-frame .notion-scroller.vertical .notion-page-content>.notion-collection_view-block .notion-scroller div.notion-gallery-view{
  padding-left:0!important;
  padding-right:0!important;
}
.enhancer--tweak-normalise_table_scroll .notion-collection-view-body .notion-table-view {
  width: 100% !important;
  padding-left: 0!important;
  padding-right: 0!important;
}
.layout.layout-wide{
  --margin-width: 30px!important;
}
.fullWidth .notion-frame .notion-scroller.vertical .notion-page-content>.notion-collection_view-block div[style*=left][style*="position: sticky"]{
  left: 0px !important;
}
sudo docker container inspect  --format='{{.LogPath}}' <container-name>
sudo truncate -s 0 <path_to_log_file>
var print = Logger.log;

var webEngageLicense = '~2024b5d8';
var usersUrl = "https://api.webengage.com/v1/accounts/" + webEngageLicense + "/bulk-users";
var eventsUrl = "https://api.webengage.com/v1/accounts/" + webEngageLicense + "/bulk-events";

var headers = {
  "Authorization": "Bearer 426a654c-89b6-4595-af9c-fd3712af56f9",
  "Content-Type": "application/json"
}

/////////////////////////////////// MENU BUTTONS ///////////////////////////////////

// function onOpen() {
//   var ui = SpreadsheetApp.getUi();
//   var add_modules = ui.createMenu("USERS_DATA");
//   add_modules.addItem('TEST', 'users_to_WE_TEST').addToUi();
//   add_modules.addItem('UPSC FORM RESP', 'users_to_WE_UPSC_FORM_RESP').addToUi();
// }

/////////////////////////////////// MAP KEYS ///////////////////////////////////

function map_keys(sheetName) {
  var mapper_keys = {}
  var ss = SpreadsheetApp.getActiveSpreadsheet();
  var ActiveSheet = ss.getSheetByName(sheetName);
  var lastColumn = ActiveSheet.getLastColumn()
  var headers = ActiveSheet.getRange(1, 1, 1, lastColumn).getValues()[0]
  for (var k = 0; k < lastColumn; k++) {
    mapper_keys[headers[k]] = k
  }
  return (mapper_keys)
}

/////////////////////////////////// CALL API ///////////////////////////////////

function callApi(targetURL, method, payload, headers) {
  var options = {
    'method': method,
    'payload': payload,
    'headers': headers
  }
  try {
    var response = UrlFetchApp.fetch(targetURL, options);
  } catch (e) {
    // print(e)
    return [e, 0]
  }
  var respText = JSON.parse(response.getContentText());
  var respStatus = response.getResponseCode();
  return [respText, respStatus]
}

///////////////////////////////////////////// GENERATE USER ID /////////////////////////////////////////////

function generateUserId(row, prefix, startCounter) {
  // var prefix = "fmp_gf_";
  // var startCounter = 198230;
  var zeros = "000000";

  var idNumber = (startCounter + row - 1).toString()
  var uniqueUserId = prefix + (zeros + idNumber).slice(-7);

  return uniqueUserId;
}

//////////////////////////////////////// USER FETCHING FROM RESPONSE SHEETs ////////////////////////////////////////

function fetch_users_from_sheet(sheetName) {
  var sheetConfigurations = {
    "UPSC_FORM_1": {
      url: "https://docs.google.com/spreadsheets/d/1a0AglRKvK8aqee1wWZnpkQDGQXLtMa9Gy3g7EgjgzSI/edit?resourcekey#gid=1768755200",
      shName: "Form Responses 1",
      startRow: 1,
      destinationSheetName: "Users_to_WE UPSC_FORM_1",
      emailIdx: 1,
      phoneIdx: 3,
      nameIdx: 6,
      prefix: "fmp_upsc1_",
      startCounter: 000000,
    },
    "UPSC_FORM_2": {
      url: "https://docs.google.com/spreadsheets/d/1a0AglRKvK8aqee1wWZnpkQDGQXLtMa9Gy3g7EgjgzSI/edit?resourcekey#gid=1244699291",
      shName: "google_form_leads",
      startRow: 1,
      destinationSheetName: "Users_to_WE UPSC_FORM_2",
      emailIdx: 1,
      phoneIdx: 2,
      nameIdx: 0,
      prefix: "fmp_upsc2_",
      startCounter: 000000,
    },
    "JUDI_FORM": {
      url: "https://docs.google.com/spreadsheets/d/1DZ9hwfJiW5-6JckwicpaVeGotgLEYm6RVScs2GhnXIk/edit#gid=0",
      shName: "Sheet1",
      startRow: 1,
      destinationSheetName: "Users_to_WE JUDI_FORM",
      emailIdx: 1,
      phoneIdx: 2,
      nameIdx: 0,
      prefix: "fmp_jud1_",
      startCounter: 000000,
    },
  };

  var sheetConfig = sheetConfigurations[sheetName];

  var sourceSheet = SpreadsheetApp.openByUrl(sheetConfig.url).getSheetByName(sheetConfig.shName);
  var lastRow = sourceSheet.getLastRow();
  var numRows = lastRow - sheetConfig.startRow + 1;
  var sourceData = sourceSheet.getRange(sheetConfig.startRow, 1, numRows, sourceSheet.getLastColumn()).getValues();

  var destinationSheet = SpreadsheetApp.getActiveSpreadsheet().getSheetByName(sheetConfig.destinationSheetName);
  var destinationData = destinationSheet.getDataRange().getValues();

  if (destinationData.length < sourceData.length) {
    var newRows = sourceData.slice(destinationData.length);
    for (var i = 0; i < newRows.length; i++) {
      var row = destinationData.length + i + 1;
      var email = String(newRows[i][sheetConfig.emailIdx]);
      var phone = String(newRows[i][sheetConfig.phoneIdx]);
      phone = (phone.length === 10) ? "91" + phone : phone;
      var name = String(newRows[i][sheetConfig.nameIdx]);

      if (email != "#ERROR!" && phone != "#ERROR!" && name != "#ERROR!" && phone.length == 12) {
        var uniqueUserId = generateUserId(row, sheetConfig.prefix, sheetConfig.startCounter);
        destinationSheet.getRange(row, 1).setValue(uniqueUserId);
        destinationSheet.getRange(row, 2).setValue(email);
        destinationSheet.getRange(row, 3).setValue(phone);
        destinationSheet.getRange(row, 4).setValue(name);
        destinationSheet.getRange(row, 5).setValue("TRUE");
      }
    }
  }
}

///////////////////////////////////////// USERS API - UPSC_FORM_1 /////////////////////////////////////////

function users_to_WE_UPSC1() {
  var mapper_keys = map_keys('Users_to_WE UPSC_FORM_1')
  SpreadsheetApp.flush()

  fetch_users_from_sheet("UPSC_FORM_1");

  var webEngageSheet = SpreadsheetApp.getActiveSpreadsheet().getSheetByName('Users_to_WE UPSC_FORM_1');

  var StartRow = 2;
  var RowRange = webEngageSheet.getLastRow() - StartRow + 1;
  var WholeRange = webEngageSheet.getRange(StartRow, 1, RowRange, 6);
  var AllValues = WholeRange.getDisplayValues();

  var userList = [];
  var batchSize = 25;

  var userIndexList = [];
  var errorUserList = [];

  for (var idx in AllValues) {
    var currentRow = AllValues[idx];
    var status = currentRow[mapper_keys['status']];

    if (status !== "Success" && status !== "Error" && status !== "User Integrated") {
      var user_id = String(currentRow[mapper_keys['user_id']]);
      var email = String(currentRow[mapper_keys['email']]);
      var mobile = String(currentRow[mapper_keys['phone']]);
      var name = String(currentRow[mapper_keys['first_name']]);

      if (email != "#ERROR!" && mobile != "#ERROR!" && name != "#ERROR!" && mobile.length == 12) {
        var user = {
          'userId': user_id,
          'email': email,
          'firstName': name,
          'phone': mobile,
          'whatsappOptIn': true,
        };
        userList.push(user);
        userIndexList.push(idx);

        if (userList.length === batchSize) {
          var payload = { "users": userList }
          payload = JSON.stringify(payload);

          var [uploadResponse, respStatus] = callApi(usersUrl, "post", payload, headers);

          if (respStatus != 201) {
            print(payload);
            print(respStatus);
            errorUserList = errorUserList.concat(...userIndexList);
          }

          var userList = [];
          var userIndexList = [];
        }
        if (idx % 50 === 0) {
          print("Delay Added: 5 Sec");
          Utilities.sleep(5000);
        }
        webEngageSheet.getRange(parseInt(idx) + StartRow, mapper_keys['status'] + 1).setValue('User Integrated');
      }
      else {
        webEngageSheet.getRange(parseInt(idx) + StartRow, mapper_keys['status'] + 1).setValue('Error');
      }
    }
  }
  if (userList.length > 0) {
    var payload = { "users": userList }
    payload = JSON.stringify(payload);

    var [uploadResponse, respStatus] = callApi(usersUrl, "post", payload, headers);

    if (respStatus != 201) {
      print(payload);
      print(respStatus);
      errorUserList = errorUserList.concat(...userIndexList);
    }
  }

  if (errorUserList.length > 0) {
    print(errorUserList);
    for (var e in errorUserList) {
      webEngageSheet.getRange(parseInt(errorUserList[e]) + StartRow, mapper_keys['status'] + 1).setValue('Failed User Api');
    }
  }

  print("Done User Integration - UPSC_FORM_1");
}

////////////////////////////////////////////////// EVENTS API - UPSC_FORM_1 //////////////////////////////////////////////////

function users_to_events_UPSC1() {
  var mapper_keys = map_keys('Users_to_WE UPSC_FORM_1')
  SpreadsheetApp.flush()

  var webEngageSheet = SpreadsheetApp.getActiveSpreadsheet().getSheetByName('Users_to_WE UPSC_FORM_1');

  var StartRow = 2;
  var RowRange = webEngageSheet.getLastRow() - StartRow + 1;
  var WholeRange = webEngageSheet.getRange(StartRow, 1, RowRange, 6);
  var AllValues = WholeRange.getDisplayValues();

  var eventName = "UPSC_FA";

  var eventUserList = [];
  var batchSize = 25;

  var userIndexList = [];
  var errorUserList = [];

  for (var idx in AllValues) {
    var currentRow = AllValues[idx];
    var status = currentRow[mapper_keys['status']];

    if (status === "User Integrated") {
      var user_id = String(currentRow[mapper_keys['user_id']]);
      if (user_id) {
        var eventUser = {
          "userId": user_id,
          "eventName": eventName
        };
        eventUserList.push(eventUser);
        userIndexList.push(idx);

        if (eventUserList.length === batchSize) {
          var payload = { "events": eventUserList }
          payload = JSON.stringify(payload);

          var [uploadResponse, respStatus] = callApi(eventsUrl, "post", payload, headers);

          if (respStatus != 201) {
            print(payload);
            print(respStatus);
            errorUserList = errorUserList.concat(...userIndexList);
          }

          var eventUserList = [];
          var userIndexList = [];
        }
        if (idx % 50 === 0) {
          print("Delay Added: 5 Sec");
          Utilities.sleep(5000);
        }
        webEngageSheet.getRange(parseInt(idx) + StartRow, mapper_keys['status'] + 1).setValue('Success');
      }
      else {
        webEngageSheet.getRange(parseInt(idx) + StartRow, mapper_keys['status'] + 1).setValue('Error');
      }
    }
  }
  if (eventUserList.length > 0) {
    var payload = { "events": eventUserList }
    payload = JSON.stringify(payload);

    var [uploadResponse, respStatus] = callApi(eventsUrl, "post", payload, headers);

    if (respStatus != 201) {
      print(payload);
      print(respStatus);
      errorUserList = errorUserList.concat(...userIndexList);
    }
  }

  if (errorUserList.length > 0) {
    print(errorUserList);
    for (var e in errorUserList) {
      webEngageSheet.getRange(parseInt(errorUserList[e]) + StartRow, mapper_keys['status'] + 1).setValue('Failed Event Api');
    }
  }

  print("Done User To Event - UPSC_FORM_1")
}

////////////////////////////////////////////////// USERS API - UPSC_FORM_2 //////////////////////////////////////////////////

function users_to_WE_UPSC2() {
  var mapper_keys = map_keys('Users_to_WE UPSC_FORM_2')
  SpreadsheetApp.flush()

  fetch_users_from_sheet("UPSC_FORM_2");

  var webEngageSheet = SpreadsheetApp.getActiveSpreadsheet().getSheetByName('Users_to_WE UPSC_FORM_2');

  var StartRow = 2;
  var RowRange = webEngageSheet.getLastRow() - StartRow + 1;
  var WholeRange = webEngageSheet.getRange(StartRow, 1, RowRange, 6);
  var AllValues = WholeRange.getDisplayValues();

  var userList = [];
  var batchSize = 25;

  var userIndexList = [];
  var errorUserList = [];

  for (var idx in AllValues) {
    var currentRow = AllValues[idx];
    var status = currentRow[mapper_keys['status']];

    if (status !== "Success" && status !== "Error" && status !== "User Integrated") {
      var user_id = String(currentRow[mapper_keys['user_id']]);
      var email = String(currentRow[mapper_keys['email']]);
      var mobile = String(currentRow[mapper_keys['phone']]);
      var name = String(currentRow[mapper_keys['first_name']]);

      if (email != "#ERROR!" && mobile != "#ERROR!" && name != "#ERROR!" && mobile.length == 12) {
        var user = {
          'userId': user_id,
          'email': email,
          'firstName': name,
          'phone': mobile,
          'whatsappOptIn': true,
        };
        userList.push(user);
        userIndexList.push(idx);

        if (userList.length === batchSize) {
          var payload = { "users": userList }
          payload = JSON.stringify(payload);

          var [uploadResponse, respStatus] = callApi(usersUrl, "post", payload, headers);

          if (respStatus != 201) {
            print(payload);
            print(respStatus);
            errorUserList = errorUserList.concat(...userIndexList);
          }

          var userList = [];
          var userIndexList = [];
        }
        if (idx % 50 === 0) {
          print("Delay Added: 5 Sec");
          Utilities.sleep(5000);
        }
        webEngageSheet.getRange(parseInt(idx) + StartRow, mapper_keys['status'] + 1).setValue('User Integrated');
      }
      else {
        webEngageSheet.getRange(parseInt(idx) + StartRow, mapper_keys['status'] + 1).setValue('Error');
      }
    }
  }
  if (userList.length > 0) {
    var payload = { "users": userList }
    payload = JSON.stringify(payload);

    var [uploadResponse, respStatus] = callApi(usersUrl, "post", payload, headers);

    if (respStatus != 201) {
      print(payload);
      print(respStatus);
      errorUserList = errorUserList.concat(...userIndexList);
    }
  }

  if (errorUserList.length > 0) {
    print(errorUserList);
    for (var e in errorUserList) {
      webEngageSheet.getRange(parseInt(errorUserList[e]) + StartRow, mapper_keys['status'] + 1).setValue('Failed User Api');
    }
  }

  print("Done User Integration - UPSC_FORM_2");
}

////////////////////////////////////////////////// EVENTS API - UPSC_FORM_2 //////////////////////////////////////////////////

function users_to_events_UPSC2() {
  var mapper_keys = map_keys('Users_to_WE UPSC_FORM_2')
  SpreadsheetApp.flush()

  var webEngageSheet = SpreadsheetApp.getActiveSpreadsheet().getSheetByName('Users_to_WE UPSC_FORM_2');

  var StartRow = 2;
  var RowRange = webEngageSheet.getLastRow() - StartRow + 1;
  var WholeRange = webEngageSheet.getRange(StartRow, 1, RowRange, 6);
  var AllValues = WholeRange.getDisplayValues();

  var eventName = "UPSC_FA";

  var eventUserList = [];
  var batchSize = 25;

  var userIndexList = [];
  var errorUserList = [];

  for (var idx in AllValues) {
    var currentRow = AllValues[idx];
    var status = currentRow[mapper_keys['status']];

    if (status === "User Integrated") {
      var user_id = String(currentRow[mapper_keys['user_id']]);
      if (user_id) {
        var eventUser = {
          "userId": user_id,
          "eventName": eventName
        };
        eventUserList.push(eventUser);
        userIndexList.push(idx);

        if (eventUserList.length === batchSize) {
          var payload = { "events": eventUserList }
          payload = JSON.stringify(payload);

          var [uploadResponse, respStatus] = callApi(eventsUrl, "post", payload, headers);

          if (respStatus != 201) {
            print(payload);
            print(respStatus);
            errorUserList = errorUserList.concat(...userIndexList);
          }

          var eventUserList = [];
          var userIndexList = [];
        }
        if (idx % 50 === 0) {
          print("Delay Added: 5 Sec");
          Utilities.sleep(5000);
        }
        webEngageSheet.getRange(parseInt(idx) + StartRow, mapper_keys['status'] + 1).setValue('Success');
      }
      else {
        webEngageSheet.getRange(parseInt(idx) + StartRow, mapper_keys['status'] + 1).setValue('Error');
      }
    }
  }
  if (eventUserList.length > 0) {
    var payload = { "events": eventUserList }
    payload = JSON.stringify(payload);

    var [uploadResponse, respStatus] = callApi(eventsUrl, "post", payload, headers);

    if (respStatus != 201) {
      print(payload);
      print(respStatus);
      errorUserList = errorUserList.concat(...userIndexList);
    }
  }

  if (errorUserList.length > 0) {
    print(errorUserList);
    for (var e in errorUserList) {
      webEngageSheet.getRange(parseInt(errorUserList[e]) + StartRow, mapper_keys['status'] + 1).setValue('Failed Event Api');
    }
  }

  print("Done User To Event - UPSC_FORM_2")
}

////////////////////////////////////////////////// USERS API - UPSC_FORM_2 //////////////////////////////////////////////////

function users_to_WE_JUDI() {
  var mapper_keys = map_keys('Users_to_WE JUDI_FORM')
  SpreadsheetApp.flush()

  fetch_users_from_sheet("JUDI_FORM");

  var webEngageSheet = SpreadsheetApp.getActiveSpreadsheet().getSheetByName('Users_to_WE JUDI_FORM');

  var StartRow = 2;
  var RowRange = webEngageSheet.getLastRow() - StartRow + 1;
  var WholeRange = webEngageSheet.getRange(StartRow, 1, RowRange, 6);
  var AllValues = WholeRange.getDisplayValues();

  var userList = [];
  var batchSize = 25;

  var userIndexList = [];
  var errorUserList = [];

  for (var idx in AllValues) {
    var currentRow = AllValues[idx];
    var status = currentRow[mapper_keys['status']];

    if (status !== "Success" && status !== "Error" && status !== "User Integrated") {
      var user_id = String(currentRow[mapper_keys['user_id']]);
      var email = String(currentRow[mapper_keys['email']]);
      var mobile = String(currentRow[mapper_keys['phone']]);
      var name = String(currentRow[mapper_keys['first_name']]);

      if (email != "#ERROR!" && mobile != "#ERROR!" && name != "#ERROR!" && mobile.length == 12) {
        var user = {
          'userId': user_id,
          'email': email,
          'firstName': name,
          'phone': mobile,
          'whatsappOptIn': true,
        };
        userList.push(user);
        userIndexList.push(idx);

        if (userList.length === batchSize) {
          var payload = { "users": userList }
          payload = JSON.stringify(payload);

          var [uploadResponse, respStatus] = callApi(usersUrl, "post", payload, headers);

          if (respStatus != 201) {
            print(payload);
            print(respStatus);
            errorUserList = errorUserList.concat(...userIndexList);
          }

          var userList = [];
          var userIndexList = [];
        }
        if (idx % 50 === 0) {
          print("Delay Added: 5 Sec");
          Utilities.sleep(5000);
        }
        webEngageSheet.getRange(parseInt(idx) + StartRow, mapper_keys['status'] + 1).setValue('User Integrated');
      }
      else {
        webEngageSheet.getRange(parseInt(idx) + StartRow, mapper_keys['status'] + 1).setValue('Error');
      }
    }
  }
  if (userList.length > 0) {
    var payload = { "users": userList }
    payload = JSON.stringify(payload);

    var [uploadResponse, respStatus] = callApi(usersUrl, "post", payload, headers);

    if (respStatus != 201) {
      print(payload);
      print(respStatus);
      errorUserList = errorUserList.concat(...userIndexList);
    }
  }

  if (errorUserList.length > 0) {
    print(errorUserList);
    for (var e in errorUserList) {
      webEngageSheet.getRange(parseInt(errorUserList[e]) + StartRow, mapper_keys['status'] + 1).setValue('Failed User Api');
    }
  }

  print("Done User Integration - JUDI_FORM");
}

////////////////////////////////////////////////// EVENTS API - JUDI_FORM //////////////////////////////////////////////////

function users_to_events_JUDI() {
  var mapper_keys = map_keys('Users_to_WE JUDI_FORM')
  SpreadsheetApp.flush()

  var webEngageSheet = SpreadsheetApp.getActiveSpreadsheet().getSheetByName('Users_to_WE JUDI_FORM');

  var StartRow = 2;
  var RowRange = webEngageSheet.getLastRow() - StartRow + 1;
  var WholeRange = webEngageSheet.getRange(StartRow, 1, RowRange, 6);
  var AllValues = WholeRange.getDisplayValues();

  var eventName = "JUDI_FA";

  var eventUserList = [];
  var batchSize = 25;

  var userIndexList = [];
  var errorUserList = [];

  for (var idx in AllValues) {
    var currentRow = AllValues[idx];
    var status = currentRow[mapper_keys['status']];

    if (status === "User Integrated") {
      var user_id = String(currentRow[mapper_keys['user_id']]);
      if (user_id) {
        var eventUser = {
          "userId": user_id,
          "eventName": eventName
        };
        eventUserList.push(eventUser);
        userIndexList.push(idx);

        if (eventUserList.length === batchSize) {
          var payload = { "events": eventUserList }
          payload = JSON.stringify(payload);

          var [uploadResponse, respStatus] = callApi(eventsUrl, "post", payload, headers);

          if (respStatus != 201) {
            print(payload);
            print(respStatus);
            errorUserList = errorUserList.concat(...userIndexList);
          }

          var eventUserList = [];
          var userIndexList = [];
        }
        if (idx % 50 === 0) {
          print("Delay Added: 5 Sec");
          Utilities.sleep(5000);
        }
        webEngageSheet.getRange(parseInt(idx) + StartRow, mapper_keys['status'] + 1).setValue('Success');
      }
      else {
        webEngageSheet.getRange(parseInt(idx) + StartRow, mapper_keys['status'] + 1).setValue('Error');
      }
    }
  }
  if (eventUserList.length > 0) {
    var payload = { "events": eventUserList }
    payload = JSON.stringify(payload);

    var [uploadResponse, respStatus] = callApi(eventsUrl, "post", payload, headers);

    if (respStatus != 201) {
      print(payload);
      print(respStatus);
      errorUserList = errorUserList.concat(...userIndexList);
    }
  }

  if (errorUserList.length > 0) {
    print(errorUserList);
    for (var e in errorUserList) {
      webEngageSheet.getRange(parseInt(errorUserList[e]) + StartRow, mapper_keys['status'] + 1).setValue('Failed Event Api');
    }
  }

  print("Done User To Event - JUDI_FORM")
}

/////////////////////////////////////////////////////////////////////////////// TESTING ///////////////////////////////////////////////////////////////////////////////

function fetchUserData_TEST() {
  var sourceSheet = SpreadsheetApp.getActiveSpreadsheet().getSheetByName("ResponseSheet TEST");
  var destinationSheet = SpreadsheetApp.getActiveSpreadsheet().getSheetByName("Users_to_WE TEST");

  var sourceData = sourceSheet.getDataRange().getValues();
  var destinationData = destinationSheet.getDataRange().getValues();

  if (destinationData.length < sourceData.length) {
    var newRows = sourceData.slice(destinationData.length);
    for (var i = 0; i < newRows.length; i++) {
      var row = destinationData.length + i + 1;
      var email = String(newRows[i][1]);
      var phone = String(newRows[i][2]);
      phone = (phone.length === 10) ? "91" + phone : phone;
      var name = String(newRows[i][3]);

      if (email != "#ERROR!" && phone != "#ERROR!" && name != "#ERROR!" && phone.length == 12) {
        var prefix = "test_1_"
        var startCounter = 400000
        var uniqueUserId = generateUserId(row, prefix, startCounter);
        destinationSheet.getRange(row, 1).setValue(uniqueUserId);
        destinationSheet.getRange(row, 2).setValue(email);
        destinationSheet.getRange(row, 3).setValue(phone);
        destinationSheet.getRange(row, 4).setValue(name);
        destinationSheet.getRange(row, 5).setValue("TRUE");
      }
    }
  }
  print("Done Test Fetching!");
}

////////////////////////////////////////////////// USERS API - UPSC_FORM_2 //////////////////////////////////////////////////

function users_to_WE_TEST() {
  var mapper_keys = map_keys('Users_to_WE TEST')
  SpreadsheetApp.flush()

  fetchUserData_TEST();

  var webEngageSheet = SpreadsheetApp.getActiveSpreadsheet().getSheetByName('Users_to_WE TEST');

  var StartRow = 2;
  var RowRange = webEngageSheet.getLastRow() - StartRow + 1;
  var WholeRange = webEngageSheet.getRange(StartRow, 1, RowRange, 6);
  var AllValues = WholeRange.getDisplayValues();

  var userList = [];
  var batchSize = 25;

  var userIndexList = [];
  var errorUserList = [];

  for (var idx in AllValues) {
    var currentRow = AllValues[idx];
    var status = currentRow[mapper_keys['status']];

    if (status !== "Success" && status !== "Error" && status !== "User Integrated") {
      var user_id = String(currentRow[mapper_keys['user_id']]);
      var email = String(currentRow[mapper_keys['email']]);
      var mobile = String(currentRow[mapper_keys['phone']]);
      var name = String(currentRow[mapper_keys['first_name']]);

      if (email != "#ERROR!" && mobile != "#ERROR!" && name != "#ERROR!" && mobile.length == 12) {
        var user = {
          'userId': user_id,
          'email': email,
          'firstName': name,
          'phone': mobile,
          'whatsappOptIn': true,
        };
        userList.push(user);
        userIndexList.push(idx);

        if (userList.length === batchSize) {
          var payload = { "users": userList }
          payload = JSON.stringify(payload);

          var [uploadResponse, respStatus] = callApi(usersUrl, "post", payload, headers);

          if (respStatus != 201) {
            print(payload);
            print(respStatus);
            errorUserList = errorUserList.concat(...userIndexList);
          }

          var userList = [];
          var userIndexList = [];
        }
        if (idx % 50 === 0) {
          print("Delay Added: 5 Sec");
          Utilities.sleep(5000);
        }
        webEngageSheet.getRange(parseInt(idx) + StartRow, mapper_keys['status'] + 1).setValue('User Integrated');
      }
      else {
        webEngageSheet.getRange(parseInt(idx) + StartRow, mapper_keys['status'] + 1).setValue('Error');
      }
    }
  }
  if (userList.length > 0) {
    var payload = { "users": userList }
    payload = JSON.stringify(payload);

    var [uploadResponse, respStatus] = callApi(usersUrl, "post", payload, headers);

    if (respStatus != 201) {
      print(payload);
      print(respStatus);
      errorUserList = errorUserList.concat(...userIndexList);
    }
  }

  if (errorUserList.length > 0) {
    print(errorUserList);
    for (var e in errorUserList) {
      webEngageSheet.getRange(parseInt(errorUserList[e]) + StartRow, mapper_keys['status'] + 1).setValue('Failed User Api');
    }
  }

  print("Done User Integration - TEST");
}

////////////////////////////////////////////////// EVENTS API - JUDI_FORM //////////////////////////////////////////////////

function users_to_events_TEST() {
  var mapper_keys = map_keys('Users_to_WE TEST')
  SpreadsheetApp.flush()

  var webEngageSheet = SpreadsheetApp.getActiveSpreadsheet().getSheetByName('Users_to_WE TEST');

  var StartRow = 2;
  var RowRange = webEngageSheet.getLastRow() - StartRow + 1;
  var WholeRange = webEngageSheet.getRange(StartRow, 1, RowRange, 6);
  var AllValues = WholeRange.getDisplayValues();

  var eventName = "Testing User Event";

  var eventUserList = [];
  var batchSize = 25;

  var userIndexList = [];
  var errorUserList = [];

  for (var idx in AllValues) {
    var currentRow = AllValues[idx];
    var status = currentRow[mapper_keys['status']];

    if (status === "User Integrated") {
      var user_id = String(currentRow[mapper_keys['user_id']]);
      if (user_id) {
        var eventUser = {
          "userId": user_id,
          "eventName": eventName
        };
        eventUserList.push(eventUser);
        userIndexList.push(idx);

        if (eventUserList.length === batchSize) {
          var payload = { "events": eventUserList }
          payload = JSON.stringify(payload);

          var [uploadResponse, respStatus] = callApi(eventsUrl, "post", payload, headers);

          if (respStatus != 201) {
            print(payload);
            print(respStatus);
            errorUserList = errorUserList.concat(...userIndexList);
          }

          var eventUserList = [];
          var userIndexList = [];
        }
        if (idx % 50 === 0) {
          print("Delay Added: 5 Sec");
          Utilities.sleep(5000);
        }
        webEngageSheet.getRange(parseInt(idx) + StartRow, mapper_keys['status'] + 1).setValue('Success');
      }
      else {
        webEngageSheet.getRange(parseInt(idx) + StartRow, mapper_keys['status'] + 1).setValue('Error');
      }
    }
  }
  if (eventUserList.length > 0) {
    var payload = { "events": eventUserList }
    payload = JSON.stringify(payload);

    var [uploadResponse, respStatus] = callApi(eventsUrl, "post", payload, headers);

    if (respStatus != 201) {
      print(payload);
      print(respStatus);
      errorUserList = errorUserList.concat(...userIndexList);
    }
  }

  if (errorUserList.length > 0) {
    print(errorUserList);
    for (var e in errorUserList) {
      webEngageSheet.getRange(parseInt(errorUserList[e]) + StartRow, mapper_keys['status'] + 1).setValue('Failed Event Api');
    }
  }

  print("Done User To Event - TEST")
}
class Solution {
    public int longestConsecutive(int[] nums) {
        if(nums.length==0)
            return 0;
        HashSet<Integer>set=new HashSet<Integer>();
        for(int num:nums)
        {
            set.add(num);
        }
        int ans=1;
        for(int num:nums)
        {
            int count=1;
            if(!set.contains(num-1))
            {
                while(set.contains(num+1))
                {
                    num++;
                    count++;
                }
                ans=Math.max(num,count);
            }
        }
        return ans;
    }
}
import os
from google.cloud import storage
import openai
from openai import OpenAI
import requests
from google.oauth2 import service_account

def upload_to_google_cloud(local_file_path, bucket_name, destination_blob_name, credentials_json):
    # Initialize the Google Cloud client
    storage_client = storage.Client.from_service_account_json(credentials_json)
    bucket = storage_client.bucket(bucket_name)
    blob = bucket.blob(destination_blob_name)

    # Upload the file
    blob.upload_from_filename(local_file_path)

    # The public URL can be used to directly access the uploaded file via HTTP
    return blob.public_url

def upload_folder(folder_path, bucket_name, credentials_json):
    urls = []
    for filename in os.listdir(folder_path):
        if filename.lower().endswith(('.png', '.jpg', '.jpeg')):
            local_file_path = os.path.join(folder_path, filename)
            destination_blob_name = filename
            url = upload_to_google_cloud(local_file_path, bucket_name, destination_blob_name, credentials_json)
            urls.append(url)
    return urls

def save_urls_to_file(urls, file_path):
    with open(file_path, 'w') as file:
        for url in urls:
            file.write(url + '\n')
    print(f"URLs saved to {file_path}")

# Example usage
folder_path = 'C:/Users/Cibe/Downloads/apartments'
credentials_json = 'C:/Users/Cibe/Google-Json/credentials.json'
bucket_name = 'monkempire-test-1'

 #Upload the folder and get URLs
#uploaded_urls = upload_folder(folder_path, bucket_name, credentials_json)

 #Save the URLs to a file
#(uploaded_urls, 'uploaded_images_urls.txt')


def read_urls_from_file(file_path):
    with open(file_path, 'r') as file:
        return [line.strip() for line in file.readlines()]


client = OpenAI(api_key='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')


def generate_description(text):
    try:
        response = client.chat.completions.create(
            model="gpt-4-vision-preview",
            messages=[
                {
                    "role": "user",
                    "content": [
                        {"type": "text", "text": "You are a real estate agent, and you want to generate a sales description of the listing based of the pictures."},
                        {
                            "type": "image_url",
                            "image_url": {
                                "url": text,
                            },
                        },
                    ],
                }
            ],
            max_tokens=150,
        )
        return response.choices[0]
    except Exception as e:
            return str(e)


# Example usage
file_path = 'uploaded_image_url.txt'

# Read URLs from the file
#image_urls = read_urls_from_file(file_path)
with open('uploaded_image_url.txt', 'r') as file:
    image_urls = file.read().rstrip()

# Generate and print descriptions for each image
description = generate_description(image_urls)
print(f"Description for the image:\n{description}\n")
star

Tue Dec 26 2023 14:37:35 GMT+0000 (Coordinated Universal Time)

@darshcode #sql

star

Tue Dec 26 2023 13:31:32 GMT+0000 (Coordinated Universal Time) https://www.addustechnologies.com/blog/build-your-own-blockchain-network

@jonathandaveiam

star

Tue Dec 26 2023 12:53:12 GMT+0000 (Coordinated Universal Time) https://www.programiz.com/java-programming/online-compiler/

@Fahrine

star

Tue Dec 26 2023 09:24:36 GMT+0000 (Coordinated Universal Time) https://edabit.com/challenges/javascript

@msagr

star

Tue Dec 26 2023 08:49:13 GMT+0000 (Coordinated Universal Time) https://edabit.com/challenges/javascript

@msagr

star

Tue Dec 26 2023 07:58:24 GMT+0000 (Coordinated Universal Time)

@nikahafiz #ms.pbi #dax #dax.ranks #dax.all #ranking

star

Tue Dec 26 2023 06:47:06 GMT+0000 (Coordinated Universal Time)

@python

star

Tue Dec 26 2023 03:29:11 GMT+0000 (Coordinated Universal Time)

@nikahafiz #ms.pbi #dax #table

star

Tue Dec 26 2023 03:28:03 GMT+0000 (Coordinated Universal Time)

@nikahafiz #ms.pbi #dax #dax.datatable #dax.integer #dax.string #table

star

Mon Dec 25 2023 20:28:13 GMT+0000 (Coordinated Universal Time) https://chat.openai.com/?__cf_chl_tk

@eziokittu

star

Mon Dec 25 2023 16:37:40 GMT+0000 (Coordinated Universal Time)

@abhikash01

star

Mon Dec 25 2023 16:22:36 GMT+0000 (Coordinated Universal Time)

@abhikash01

star

Mon Dec 25 2023 14:08:24 GMT+0000 (Coordinated Universal Time)

@segaplay15

star

Mon Dec 25 2023 14:00:51 GMT+0000 (Coordinated Universal Time)

@abhikash01

star

Mon Dec 25 2023 13:57:48 GMT+0000 (Coordinated Universal Time)

@nikahafiz #ms.pbi #dax #dax.topn #ranking #dax.values

star

Mon Dec 25 2023 13:55:40 GMT+0000 (Coordinated Universal Time)

@nikahafiz #ms.pbi #dax #dax.topn #ranking

star

Mon Dec 25 2023 11:25:19 GMT+0000 (Coordinated Universal Time)

@abhikash01

star

Mon Dec 25 2023 10:26:16 GMT+0000 (Coordinated Universal Time)

@Pulak

star

Mon Dec 25 2023 04:29:40 GMT+0000 (Coordinated Universal Time) https://pastecode.io/s/2vx337en

@styners1

star

Sun Dec 24 2023 21:08:18 GMT+0000 (Coordinated Universal Time)

@marcopinero #javascript

star

Sun Dec 24 2023 16:45:29 GMT+0000 (Coordinated Universal Time) https://stackoverflow.com/questions/927358/how-do-i-undo-the-most-recent-local-commits-in-git

@hirsch #bash

star

Sun Dec 24 2023 15:17:13 GMT+0000 (Coordinated Universal Time)

@akilavikum #html #tailwindcss

star

Sun Dec 24 2023 00:28:48 GMT+0000 (Coordinated Universal Time)

@misha@11

star

Sat Dec 23 2023 18:07:33 GMT+0000 (Coordinated Universal Time) https://anvil.works/forum/t/simple-audio-player/3479/3?u

@webdeveloper_

star

Sat Dec 23 2023 17:22:51 GMT+0000 (Coordinated Universal Time) https://anvil.works/forum/t/converting-audio-file-to-text/6625/6

@webdeveloper_

star

Sat Dec 23 2023 16:10:52 GMT+0000 (Coordinated Universal Time) https://github.com/codesFolder/Submissions/tree/master

@coderworld

star

Sat Dec 23 2023 16:08:32 GMT+0000 (Coordinated Universal Time)

@coderworld

star

Sat Dec 23 2023 16:02:58 GMT+0000 (Coordinated Universal Time)

@coderworld

star

Sat Dec 23 2023 15:58:21 GMT+0000 (Coordinated Universal Time)

@coderworld

star

Sat Dec 23 2023 15:40:38 GMT+0000 (Coordinated Universal Time)

@mebean

star

Sat Dec 23 2023 15:29:41 GMT+0000 (Coordinated Universal Time) https://anvil.works/forum/t/converting-audio-file-to-text/6625/6

@webdeveloper_

star

Sat Dec 23 2023 14:33:30 GMT+0000 (Coordinated Universal Time)

@Paloma #vue.js #js

star

Sat Dec 23 2023 13:49:53 GMT+0000 (Coordinated Universal Time)

@mebean #بهار #جو #لد

star

Sat Dec 23 2023 11:05:03 GMT+0000 (Coordinated Universal Time) https://filetransfer.io/data-package/PqVlozHU#link

@Jevin2090

star

Sat Dec 23 2023 11:02:28 GMT+0000 (Coordinated Universal Time) https://laravel.com/docs/10.x/installation

@rashed

star

Sat Dec 23 2023 10:27:58 GMT+0000 (Coordinated Universal Time)

@saa_adit

star

Sat Dec 23 2023 10:27:34 GMT+0000 (Coordinated Universal Time)

@saa_adit

star

Sat Dec 23 2023 10:26:52 GMT+0000 (Coordinated Universal Time)

@saa_adit

star

Sat Dec 23 2023 03:01:36 GMT+0000 (Coordinated Universal Time) https://zhuanlan.zhihu.com/p/545762616

@mikeee

star

Sat Dec 23 2023 01:40:13 GMT+0000 (Coordinated Universal Time) https://developer.chrome.com/docs/extensions/reference/manifest/content-scripts

@K #json/5

star

Sat Dec 23 2023 00:05:25 GMT+0000 (Coordinated Universal Time)

@leninzapata #css

star

Fri Dec 22 2023 23:18:44 GMT+0000 (Coordinated Universal Time)

@swina

star

Fri Dec 22 2023 16:50:58 GMT+0000 (Coordinated Universal Time)

@aatish

star

Fri Dec 22 2023 16:38:47 GMT+0000 (Coordinated Universal Time) https://leetcode.com/problems/longest-consecutive-sequence/

@sumanthbijapur

star

Fri Dec 22 2023 16:28:45 GMT+0000 (Coordinated Universal Time)

@darshcode #excel

star

Fri Dec 22 2023 16:01:09 GMT+0000 (Coordinated Universal Time)

@ivxn

star

Fri Dec 22 2023 15:36:19 GMT+0000 (Coordinated Universal Time) https://ru.bongacams26.com/members/purchase-tokens?spd

@fathulla666

Save snippets that work with our extensions

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