How can I use tailwindcss without internet?

How can I compile and use tailwind css while offline? As in, have the full tailwind css and purge it to only what I require for my website, like normal, but with no internet access.

I’m definitely inexperienced in tailwind, so I first tried to just get the full css file, but I was unable to even get that far. I tried with these terminal commands:

npm install tailwindcss

npx tailwindcss init

npx tailwindcss build styles.css -o output.css

Which gave me a partial file, given that styles.css contained:

@import 'tailwindcss/base';
@import 'tailwindcss/components';
@import 'tailwindcss/utilities';

Array.push() replaces array elements with last element in a loop [closed]

Array.push() replaces array elements with last element in a loop

I’m trying to generate tints of a color. So far, I have a function hexToRGB(hex) that converts hex strings to arrays of form [r,g,b], and a function mix(f, a, b), that interpolates between two colors a and b in the ratio f . These two functions work perfectly. However, when looping to generate tints using the following code, the array tints always ends up filled with the last item, in this case [255,255,255].

document.querySelector("#colorpicker").addEventListener('change', e => {
    const color = hexToRGB(e.target.value), n = document.querySelector('#range').value;
    let tints = [];
    for (let i=1; i<=n; i++) {
        tints.push(mix(i/n, color, [255,255,255]));
    }
    console.log(tints);
}); 

// Output for n=3
// [[255,255,255],[255,255,255], [255,255,255]]

I tried logging the values to console to see if there was some problem with the for-loop output, but the issue lies in the array.push() statement. I also did not store loop output in a variable to avoid storing object references, but this did not fix the issue.

Creating a Google Workspace add on using Apps Script — variable isn’t being properly referenced across functions

I’m writing an Google Workspace add-on for Google Calendar, using Google Apps Script.

I’m having trouble getting different functions to reference the value of a variable

  1. I have a startDate variable defined at the root set to “today”
  2. In createDate it gets set to “tomorrow”
  3. It then displays it correctly in a card header as “Default start tomorrow”
  4. When you click on the button, reviseStartDate is called
  5. A new card is created, and it’s header incorrectly says “Revised start today” instead of “Revised start tomorrow”

Here is my code, you can run it as-is:

var startdate = "today"; // Define startdate as a global variable with an initial value

function onOpen() {
 var card = createCard();
  return card;
}

function createCard() {
  startdate = "tomororw"; // Update the value of startdate
  var button = CardService.newTextButton()
    .setText('Revise start date')
    .setOnClickAction(CardService.newAction()
    .setFunctionName('reviseStartDate'));

  var section = CardService.newCardSection()
    .addWidget(button);

  var card = CardService.newCardBuilder()
    .setHeader(CardService.newCardHeader().setTitle('Default start:' + startdate))
    .addSection(section)

  return card.build();
}

function reviseStartDate() {
  var card = CardService.newCardBuilder()
    .setHeader(CardService.newCardHeader().setTitle("Revised start:" +startdate));

  return card.build();
}
  

And here is part of my manifest

  "calendar": {
  "homepageTrigger": {
    "runFunction": "onOpen"
  },
  "eventOpenTrigger": {
    "runFunction": "showFreeTime"
  }

How can I allow start date to be read and written by multiple functions, in “regular” javascript this would work fine. Thanks

Google add-ons docmentation

Google Apps Script reference

How to recursively build a JSON tree structure in JavaScript?

I wrote an recursive function to generate an hierarchy JSON but the function is returning unexpected output i tried solving it but i am getting no where.

My Recursive Function:


function buildTree(mainRoot) {
  const items = [
    {
      label: mainRoot.Name,
      name: mainRoot.Name,
      expanded: true,
      items: [],
    },
  ];
  if (directReportee.has(mainRoot.Id)) {
    directReportee.get(mainRoot.Id).forEach((childNodes) => {
        items[0].items.push(buildTree(childNodes));
    });
  }
 
  return items;
}

Output Format my function returning:

[
  {
    "label": "Lauren Boyle",
    "name": "Lauren Boyle",
    "expanded": true,
    "items": [
      [
        {
          "label": "Banoth Srikanth",
          "name": "Banoth Srikanth",
          "expanded": true,
          "items": [
            [
              {
                "label": "Stella Pavlova",
                "name": "Stella Pavlova",
                "expanded": true,
                "items": []
              }
            ]
          ]
        }
      ],
      [
        {
          "label": "Srikanth",
          "name": "Srikanth",
          "expanded": true,
          "items": []
        }
      ]
    ]
  }
]

My output needs to items keys as list of object instead of list inside list of objects

Expected Output Format:

items = [
        {
            label: 'Western Sales Director',
            name: '1',
            expanded: true,
            items: [
                {
                    label: 'Western Sales Manager',
                    name: '2',
                    expanded: true,
                    items: [
                        {
                            label: 'CA Sales Rep',
                            name: '3',
                            expanded: true,
                            items: [],
                        },
                        {
                            label: 'OR Sales Rep',
                            name: '4',
                            expanded: true,
                            items: [],
                        },
                    ],
                },
            ],
        }
    ]
    

I have some problems with mysql data loading

I’m getting these errors, and i’ dont know how to fix.

The code is a Chart, its using the tradingview lightweight charts. Its basicly generating itself some
price and some other datas and making a “stock” chart.

I’m saving the data to a mysql server, but when i wanna to load the data i’m getting kinda stucked.
Can somebody help?

error:
connection handler failed
Traceback (most recent call last):
File “C:UsersdudasAppDataLocalProgramsPythonPython39libsite-packageswebsocketslegacyserver.py”, line 236, in handler
await self.ws_handler(self)
File “C:UsersdudasAppDataLocalProgramsPythonPython39libsite-packageswebsocketslegacyserver.py”, line 1175, in _ws_handler
return await cast(
File “C:xampphtdocschartprice.py”, line 32, in server
price = result[close]
NameError: name ‘close’ is not defined

import asyncio
import websockets
import random
from datetime import datetime, timedelta
import json
import mysql.connector

# Establishing a database connection
cnx = mysql.connector.connect(user='root', password='',
                              host='localhost',
                              database='tradewisedb')
cursor = cnx.cursor()

# Creating the data table if it doesn't exist
cursor.execute("""
CREATE TABLE IF NOT EXISTS prices (
    time BIGINT,
    open FLOAT,
    high FLOAT,
    low FLOAT,
    close FLOAT
)
""")

# Simulation parameters
price = 100.0
trend = 1
volatility = 0.02
min_price = 50.0
max_price = 150.0
fluctuation_range = 0.02
post_jump_fluctuation = 0.005
interval = timedelta(minutes=1)

async def server(websocket, path):
    cursor.execute("SELECT close FROM prices ORDER BY time DESC LIMIT 1")
    result = cursor.fetchone()

    if result is not None:
        price = result[close]
        min_price = result[low]
        max_price = result[high]

    else:
        price = 100.0
        trend = 1
        volatility = 0.02
        min_price = 50.0
        max_price = 150.0
        fluctuation_range = 0.02
        post_jump_fluctuation = 0.005
        interval = timedelta(minutes=1)     # Fetch previous data from the database

    cursor.execute("SELECT * FROM prices ORDER BY time ASC LIMIT 1000")

    rows = cursor.fetchall()

    previous_data = [{
        'time': row[0],
        'open': row[1],
        'high': row[2],
        'low': row[3],
        'close': row[4]
    } for row in rows]

    await websocket.send(json.dumps(previous_data))

    while True:
        start_time = datetime.now()
        open_price = price
        high_price = price
        low_price = price

        start_time_timestamp = int(start_time.timestamp() * 1000)  # UNIX timestamp in milliseconds

        while datetime.now() - start_time < interval:
            # Random 'news' events
            if random.random() < 0.01:
                trend *= -1
                volatility = fluctuation_range

            # After a big jump, create some sideways movement
            else:
                volatility = post_jump_fluctuation

            # Random 'market' fluctuations
            price *= 1 + trend * volatility * random.uniform(-1, 1)

            # Ensure price stays within min and max limits
            if price > max_price:
                price = max_price
                trend = -1
            elif price < min_price:
                price = min_price
                trend = 1

            high_price = max(high_price, price)
            low_price = min(low_price, price)

            temp_data = {
                "time": start_time_timestamp,
                "open": open_price,
                "high": high_price,
                "low": low_price,
                "close": price
            }

            await websocket.send(json.dumps(temp_data))

            await asyncio.sleep(1)

        close_price = price

        data = {
            "time": start_time_timestamp,
            "open": open_price,
            "high": high_price,
            "low": low_price,
            "close": close_price
        }

        await websocket.send(json.dumps(data))

        # Inserting data into the database
        add_price = ("INSERT INTO prices "
                   "(time, open, high, low, close) "
                   "VALUES (%s, %s, %s, %s, %s)")
        cursor.execute(add_price, (data['time'], data['open'], data['high'], data['low'], data['close']))
        cnx.commit()

start_server = websockets.serve(server, 'localhost', 8000)

asyncio.get_event_loop().run_until_complete(start_server)
asyncio.get_event_loop().run_forever()

# Closing the database connection
cursor.close()
cnx.close()

Like almost everything what i was know to try.

how to check particular chrome extension installed or not using javascript

How to find out particular extension installed or not. Below code for your reference.

index.html

<script>
  var id = "particular_extension_id";
  chrome.runtime.sendMessage(id, {action: "id", value : id}, function(response) {
  if(response && (response.id == id)) //extension installed
  {
    console.log(response);
  }
  else //extension not installed
  {
    console.log("Please consider installig extension");
  }

  });
 </script>

extensions.js

 chrome.runtime.onMessageExternal.addListener(function(msg, sender, sendResponse) {
  if ((msg.action == "id") && (msg.value == id))
  {
    sendResponse({id : id});
  }
  });

manifest.json

{
 "name": "extension_name",
 "description":"",
 "version": "1.0.11",
 "manifest_version": 2,
 "background": {
   "scripts": ["extension.js"],
    "persistent": true
 },
 "externally_connectable": {
  "matches": ["*://localhost/*"]
 },
 "permissions": ["desktopCapture"]
}

But am getting below error

Uncaught TypeError: Cannot read properties of undefined (reading ‘sendMessage’)

Could you pls help me. Where I missed

Issue in single-table design DynamoDB and limit query parameters

I want to be able to limit the fetch elements I am getting in each query, but I am facing the following issue here:

Since I use the single-table design in DynamoDB I am getting only four items here:

enter image description here

If I check the 10 first elements in DynamoDB, I will notice that I am getting the count here, regardless of the items I am filtering in my Scan operation
enter image description here

  async paginate<TEntity>(
    limit = 10,
    start_key: any
    TableName = $env.MAIN_TABLE
  ): Promise<Paginate<TEntity>> {
    Assert.ok(TableName)
    const items= await this.instance.scan({
       TableName
       Limit: limit,
       ExclusiveStartKey: start_key,
       FilterExpression: 'contains(PK, :PK)',
       ExpressionAttributeValues: {
         ':PK': 'QUIZ#'
       }
    })
    return items
  }

Does anyone here know a workaround for this?

Astro js dynamic nested routing.. Is this right approach?

say, there is an app shows football match data of several leagues. The match data comes from external apis.

Here is the routing. I want to show a top page for each league and monthly pages which shows match data by the month.

page structure

[league]
|- [month].astro
| index.astro

Routing for [league] index.astro

I make api requests within getStaticPaths() and create routing data like this.

export function getStaticPaths() {
  // api requests, then create routing data.
  return [
    { params: { league: "Bundesliga" }},
    { params: { league: "Laliga" }},
    { params: { league: "EnglishPremierLeague" }},
  ];
}

Routing for [month].astro

So, I should probably need data like this.

return [
  { params: { league: "Bundesliga", month: "2023-04" } },
  { params: { league: "Bundesliga", month: "2023-05" } },
  { params: { league: "Bundesliga", month: "2023-06" } },
  { params: { league: "Bundesliga", month: "2023-06" } },
  { params: { league: "Laliga", month: "2023-06" } },
  { params: { league: "Laliga", month: "2023-07" } },
  { params: { league: "Laliga", month: "2023-08" } },
  { params: { league: "Laliga", month: "2023-09" } },
  { params: { league: "EnglishPremierLeague", month: "2023-12" } },
  { params: { league: "EnglishPremierLeague", month: "2024-01" } },
];

But this method seems too verbose, because to create data like this, you need another api requests from every routing files.

Is there any better way to do it? like making just one request and create all possible routing data patterns and can be referenced from routing astro files?

I’m trying to generate form control dynamically in angular forms & i’m facing that error in console “TypeError: feature_r5.get is not a function”

I’m trying to generate form controls dynamically on click of a button in Angular v14 html template i generate it but i’m facing that error in console.

ERROR TypeError: feature_r5.get is not a function
 at PostAdvComponent_div_40_Template

Html template code

<div id="features" class="tab-pane mytab-pane">
            <div class="form-group">
                <button type="button" class="btn btn-primary" (click)="addFeatureButtonClick()">Add</button>
            </div>

            <div formArrayName="features" *ngFor="let feature of advForm.get('features')?.value; let i = index">
                    <div attr.formGroupName="{{i}}">
                        <div class="form-group" [ngClass]="{'has-error' : feature.get('fName').invalid &&
                                                                           feature.get('fName').touched}">
                            <div class="input-group">
                                <span class="input-group-prepend">
                                    <label class="input-group-text"><strong>Features</strong></label>
                                </span>
                                <input type="text" id="{{'fName'+i}}" name="fName" class="form-control" placeholder="Features"
                                    formControlName="fName"/>
                            </div>
                            <span class="help-block" *ngIf="feature.get('fName').errors.required &&
                                                            feature.get('fName').touched">
                                Feature is required
                            </span>
                        </div>
                    </div>
            </div>
        </div>

How can I convert Python API calls to Javascript arrays to make a Flask app look nicer?

Can Python API calls be converted to Javascript arrays so Javascript can be used to make it look nicer when rendered in a Flask app? I am working on a project but my friend who is a python programmer wants to use Python to make the API call, problem is I am a JavaScript / Web programmer, so I haven’t the first clue how to convert the Python API response into a Python Array, then somehow pass that data to a JavaScript Array so I can work with the data and make it look nicer on the website project we are building.

I can do the API call with fetch() way easier since we are developing a web application, but he is insisting on Python because we’re trying to use Flask.

Cypress – There was an error reconnecting to the Chrome DevTools protocol

I’m running a controlled test in cypress and after some tests, this error is randomly occurring in the electron browser:

There was an error reconnecting to the Chrome DevTools protocol. Please restart the browser.

enter image description here

in google chrome it is running without errors, but in electron it is breaking.
I need to run in electron because of settings in aws

I need to send an email from my sheets. How do I get the cell values as variables in HTML?

I am working on a code that reads the sheets and copies the whole template to an email. I am using all google tools and apps script. The problem I am facing right now is that I don’t how to link the variables I declared in the java script code with the cells values into the html file where I need the values to be displayed. Can someone please explain me and give me an example if possible. I looked at other codes available here but they don’t have the link/connection between java and html.

Thanks

Read JPG using Flask after being uploaded without being saved on the server

I’m new to HTML, CSS and JavaScript. I’m doing a website where the user uploads an image in a drag and drop container. I want to read the uploaded JPG file using Flask once a POST request have been summited, how can I do it? For now I’m confused how the file is uploaded and how can I process it in Flask.

I’m using the method readAsDataURL, is it good practice? Since I want to display it but then I want to read the image as JPG or JPEG. Also, if I try to download it, it is saved as jfif, how does this happen?

Here’s the js script where the image is uploaded:

dragArea.addEventListener('drop', (event)=>{
    event.preventDefault(); // Prevent to load the page from the submit button
    file = event.dataTransfer.files[0]; // Get the file uploaded
    displayFile();
    
});

// Savve and display image after it is dropped
function displayFile() {
    let fileType = file.type;

    let validExtensions = ['image/jpeg', 'image/jpg', 'image/png'];

    if (validExtensions.includes(fileType)){
        let fileReader = new FileReader();

        fileReader.onload = () =>{
            let fileURL = fileReader.result;
            //console.log(fileURL);
            let imgTag = `<img src = ${fileURL}>`;
            dragArea.innerHTML = imgTag;
            dragArea.classList.add('active2');
        };
        fileReader.readAsDataURL(file);
    }
    else{
        alert('This file is not an image');
        dragArea.classList.remove('active');
    }
}

Here’s the HTML

<!DOCTYPE html>
<html lang="en">
    <head>
        <meta charset="UTF-8">
        <meta http-equiv="X-UA-Compatible" content="IE=edge">
        <meta name="viewport" content="width=device-width, initial-scale=1.0">
        
        <link href="https://fonts.googleapis.com/css2?family=Montserrat:wght@500&display=swap" rel="stylesheet">
        <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.0/css/all.min.css" integrity="sha512-iecdLmaskl7CVkqkXNQ/ZH/XLlvWZOJyj7Yy7tcenmpD1ypASozpmT/E0iPtmFIB46ZmdtAc9eNBvH0H/ZpiBw==" crossorigin="anonymous" referrerpolicy="no-referrer" />
        <link rel="stylesheet" type="text/css" href="staticstyles.css"/>
    </head>

    <body>
        <div class="body2">
            <div class="container">
                <h3>Upload your file</h3>
                <div class="drag-area">
                    <div class="icon">
                        <i class="fas fa-images"></i>
                    </div>
                    <span class="header2">Drag and drop</span>
                    <span class="header2">or <span class="button">browse</span></span>
                    <input type="file" id = "opener"hidden/>
                    <span class="support">Supports: JPEG, JPG</span>
                </div>
            </div>
            
            <div class="form-container">
                <form action="/" method="post" enctype="multipart/form-data">
                    <div class="input-form">
                        <input autocomplete="off" min="1" max="10" name="amount-colors" placeholder="Amount of colors" type="number">
                    </div> 
                    <div>
                        <button type="submit" class="button-form">Upload</button>
                    </div>
                </form>
            </div>

        </div>

        <script src="/static/script.js"></script>
    </body>
</html>

I was thinking something to do in the app.py script something like this:
What are the good practices? I’ve seen ways to do it with the library PIL, but I don’t know which way suits better.

from flask import Flask, flash, jsonify, redirect, render_template, request, session
import os

app = Flask(__name__)

@app.route('/', methods = ['POST', 'GET'])
def index():
    if request.method == "GET":
        return render_template('index.html')

    elif request.method == "POST":
        # Get the amount of colors
        k = request.form.get("amount-k")

        # Load up the image
        # This part will get the JPEG that the user uploaded

        # Do algorithm
        # Pass the JPG or JPEG

        # Return
        return render_template("layout.html")

if __name__ == '__main__':
    app.debug = True
    app.run(host = '0.0.0.0', port = 5000)

Any help or documentation is appreciated

What is wrong with my if else statements for my rock paper scissor game?

I am attempting to make a Rock Paper Scissors game in JavaScript, however, every time I run it the console logs the last option “You win! Scissors beats Paper” even if my selection was something other than scissors. I believe I made an error with my if else statements but maybe the problem comes from some other part.

function getComputerChoice() {
    const randomNumber = Math.floor(Math.random()*3);
    switch(randomNumber) {
        case 0:
            return "rock";
        case 1: 
            return "paper";
        case 2:
            return "scissors";
    };
    }


function getPlayerChoice() {
    prompt("rock paper or scissors?").toLowerCase();
}




 function playRound (playerSelection,computerSelection) {
    computerSelection = getComputerChoice()
    playerSelection = getPlayerChoice()

    

        

    if (computerSelection === playerSelection) {
        console.log  ("Tie");
    }
   
    else if (computerSelection === "rock" && playerSelection === "scissors") {
        console.log ("You lose! Rock beats Scissors");
    }
    else if (computerSelection === "paper" && playerSelection === "rock") {
        console.log ("You lose! Paper beats Rock");
    }
    else if (computerSelection === "scissors" && playerSelection === "paper") {
        console.log ("You lose! Scissors beats Paper");
    }

    else if (playerSelection === "rock" && computerSelection === "scissors") {
        console.log ("You win! Rock beats Scissors");
    }
    else if (playerSelection === "paper" && computerSelection === "rock") {
        console.log ("You win! Paper beats Rock");
    }
    else  (playerSelection === "scissors" && computerSelection === "paper") ;{
        console.log ("You win! Scissors beats Paper");
    }


} 

VSCode is commenting out code after /* in string literals. How can I disable this?

VSCode is commenting out all the code behind from the part ‘/*’ in the string literal on my JS file.

enter image description here
I don’t want this behaviour.

Is there anybody who experienced some similar things like this using VSCode?

Whole code of this file is here

import { json } from '@sveltejs/kit';

async function getPost() {
    let posts = [];

    const paths = import.meta.glob('/src/posts/*.md', { eager: true });

    for (const path in paths) {
        console.log(path);
    }

    return posts;
}

export async function GET() {
    const post = await getPost();
    return json(post);
}

I tried to escape the asterisk in the string literal but the prettier auto fixed it.

'/src/posts/*.md' => /src/posts/*.md' (auto fixed by prettier)