How to stop users from manually changing the URL of a website

I’m building a website using stripe and in stripe we have a success URL page but the thing is users can easily go around this without paying if they decide to change the URL to the success URL page. And I’m wondering if I can stop this from happening?

I have researched hear on stack overflow but I still don’t understand

Can’t set width of elements

<template>
  <div class="card">
    <table class="table table-hover custom-table table-responsive">
      <thead>
        <draggable v-model="tableHeaders" :options="{ handle: '.handle' }">
          <th class="handle" v-for="header in tableHeaders" :key="header">
            {{ header }}
          </th>
        </draggable>
      </thead>
      <tbody>
        <draggable
          v-model="tableData"
          :options="{
            handle: '.handle',
            ghostClass: 'ghost-class',
            chosenClass: 'chosen-class',
          }"
        >
          <tr v-for="item in tableData" :key="item.id" class="handle">
            <td v-for="header in tableHeaders">
              {{ item[header.toLowerCase()] }}
            </td>
          </tr>
        </draggable>
      </tbody>
    </table>
  </div>
</template>

<style>
th:hover,
td:hover {
  cursor: pointer;
}
.ghost-class {
  opacity: 0.5;
  z-index: 9999;
  transition: all 0.3s ease-in-out;
}

.chosen-class {
  opacity: 0.5;
  transition: all 0.3s ease-in-out;
}

.custom-table td,
.custom-table th {
  transition: all 0.3s ease-in-out;
  text-align: center;
  vertical-align: middle;
  font-size: 13px;
  border: 1px solid red;
  width: 5%;
  table-layout: fixed;
}

.custom-table .handle {
  cursor: move;
}

.custom-table .handle:active {
  cursor: grabbing;
}

.custom-table .handle:hover {
  background-color: #323346;
  color: #ffffff;
}

.custom-table .handle:hover td,
.custom-table .handle:hover th {
  opacity: 0.6;
}

.custom-table .handle:hover .chosen-class,
.custom-table .handle:hover .ghost-class {
  opacity: 0.6;
}

.custom-table .handle:hover .chosen-class {
  cursor: grabbing;
}

.custom-table .handle:hover .ghost-class {
  cursor: move;
}
</style>

I cannot set the width of the td elements – even if i try to directly set width on the td element I cannot do it. There are twenty items within the grid table and i have the headers set to 5% and im trying to get the td elements set to 5%

I tried to change the width of the td elements but im finding i cannot change the data cells width

How do i change the width of the cells?

Mocking odata endpoints in mswjs

Is it possible to mock odata endpoints using mswjs?

I currently use json-server as my temporary backend until the odata endpoint is ready, at which point I’ll migrate my queries to use that. I plan to use mswjs to mock the server in my tests, but would like to migrate now to use for development too.

Is it possible to replicate the odata filter functionality, or will I need to define explicit endpoints for each possible $filter query I want to use for testing?

Eg ‘/users$filter=id in (‘1’, ‘2’)’

I’m unsure how to replicate the $filter functionality that I need.

I keep getting an error that states “Failed to load resource: the server responded with a status of 500 (Internal Server Error)”

I’m building a multi-vendor e-commerce website. I’m currently trying to implement Admins to be able to delete products. I keep getting an error that states “Failed to load resource: the server responded with a status of 500 (Internal Server Error)”. Any ideas? In my productRouter.js I have the route below:

        import express from 'express';
    import expressAsyncHandler from 'express-async-handler';
    import data from '../data.js';
    import Product from '../models/productModel.js';
    import { isAdmin, isAuth } from '../utils.js';
    const productRouter = express.Router();
    productRouter.get(
      '/',
      expressAsyncHandler(async (req, res) => {
        const products = await Product.find({});
        res.send(products);
      })
    );
    productRouter.get(
      '/seed',
      expressAsyncHandler(async (req, res) => {
        // await Product.remove({});
        const createdProducts = await Product.insertMany(data.products);
        res.send({ createdProducts });
      })
    );
    productRouter.get(
      '/:id',
      expressAsyncHandler(async (req, res) => {
        const product = await Product.findById(req.params.id);
        if (product) {
          res.send(product);
        } else {
          res.status(404).send({ message: 'Product Not Found' });
        }
      })
    );
    productRouter.post(
      '/',
      isAuth,
      isAdmin,
      expressAsyncHandler(async (req, res) => {
        const product = new Product({
          name: 'sample name ' + Date.now(),
          image: '/images/p1.jpg',
          price: 0,
          category: 'sample category',
          brand: 'sample brand',
          countInStock: 0,
          rating: 0,
          numReviews: 0,
          description: 'sample description',
        });
        const createdProduct = await product.save();
        res.send({ message: 'Product Created', product: createdProduct });
      })
    );
    productRouter.put(
      '/:id',
      isAuth,
      isAdmin,
      expressAsyncHandler(async (req, res) => {
        const productId = req.params.id;
        const product = await Product.findById(productId);
        if (product) {
          product.name = req.body.name;
          product.price = req.body.price;
          product.image = req.body.image;
          product.category = req.body.category;
          product.brand = req.body.brand;
          product.countInStock = req.body.countInStock;
          product.description = req.body.description;
          const updatedProduct = await product.save();
          res.send({ message: 'Product Updated', product: updatedProduct });
        } else {
          res.status(404).send({ message: 'Product Not Found' });
        }
      })
    );
    
    productRouter.delete(
      '/:id',
      isAuth,
      isAdmin,
      expressAsyncHandler(async (req, res) => {
        const product = await Product.findById(req.params.id);
        if (product) {
          const deleteProduct = await product.remove();
          res.send({ message: 'Product Deleted', product: deleteProduct });
        } else {
          res.status(404).send({ message: 'Product Not Found' });
        }
      })
    );
    
    export default productRouter;

Here is my productActions.js below I’ve been suspecting that the error could be caused by this file, however I’m unsure:

        import Axios from 'axios';
    import {
      PRODUCT_CREATE_FAIL,
      PRODUCT_CREATE_REQUEST,
      PRODUCT_CREATE_SUCCESS,
      PRODUCT_DETAILS_FAIL,
      PRODUCT_DETAILS_REQUEST,
      PRODUCT_DETAILS_SUCCESS,
      PRODUCT_LIST_FAIL,
      PRODUCT_LIST_REQUEST,
      PRODUCT_LIST_SUCCESS,
      PRODUCT_UPDATE_REQUEST,
      PRODUCT_UPDATE_SUCCESS,
      PRODUCT_UPDATE_FAIL,
      PRODUCT_DELETE_REQUEST,
      PRODUCT_DELETE_FAIL,
      PRODUCT_DELETE_SUCCESS,
    } from '../constants/productConstants';
    
    export const listProducts = () => async (dispatch) => {
      dispatch({
        type: PRODUCT_LIST_REQUEST,
      });
      try {
        const { data } = await Axios.get('/api/products');
        dispatch({ type: PRODUCT_LIST_SUCCESS, payload: data });
      } catch (error) {
        dispatch({ type: PRODUCT_LIST_FAIL, payload: error.message });
      }
    };
    export const detailsProduct = (productId) => async (dispatch) => {
      dispatch({ type: PRODUCT_DETAILS_REQUEST, payload: productId });
      try {
        const { data } = await Axios.get(`/api/products/${productId}`);
        dispatch({ type: PRODUCT_DETAILS_SUCCESS, payload: data });
      } catch (error) {
        dispatch({
          type: PRODUCT_DETAILS_FAIL,
          payload:
            error.response && error.response.data.message
              ? error.response.data.message
              : error.message,
        });
      }
    };
    export const createProduct = () => async (dispatch, getState) => {
      dispatch({ type: PRODUCT_CREATE_REQUEST });
      const {
        userSignin: { userInfo },
      } = getState();
      try {
        const { data } = await Axios.post(
          '/api/products',
          {},
          {
            headers: { Authorization: `Bearer ${userInfo.token}` },
          }
        );
        dispatch({
          type: PRODUCT_CREATE_SUCCESS,
          payload: data.product,
        });
      } catch (error) {
        const message =
          error.response && error.response.data.message
            ? error.response.data.message
            : error.message;
        dispatch({ type: PRODUCT_CREATE_FAIL, payload: message });
      }
    };
    export const updateProduct = (product) => async (dispatch, getState) => {
      dispatch({ type: PRODUCT_UPDATE_REQUEST, payload: product });
      const {
        userSignin: { userInfo },
      } = getState();
      try {
        const { data } = await Axios.put(`/api/products/${product._id}`, product, {
          headers: { Authorization: `Bearer ${userInfo.token}` },
        });
        dispatch({ type: PRODUCT_UPDATE_SUCCESS, payload: data });
      } catch (error) {
        const message =
          error.response && error.response.data.message
            ? error.response.data.message
            : error.message;
        dispatch({ type: PRODUCT_UPDATE_FAIL, error: message });
      }
    };
    export const deleteProduct = (productId) => async (dispatch, getState) => {
      dispatch({ type: PRODUCT_DELETE_REQUEST, payload: productId });
      const {
        userSignin: { userInfo },
      } = getState();
      try {
        await Axios.delete(`/api/products/${productId}`, {
          headers: { Authorization: `Bearer ${userInfo.token}` },
        });
        dispatch({ type: PRODUCT_DELETE_SUCCESS });
      } catch (error) {
        const message =
          error.response && error.response.data.message
            ? error.response.data.message
            : error.message;
        dispatch({ type: PRODUCT_DELETE_FAIL, payload: message });
      }
    };
    

Next I have my productConstants but I think that one doesn’t really need to be shown so here is my productReducers.js below:

        import {
      PRODUCT_LIST_REQUEST,
      PRODUCT_LIST_SUCCESS,
      PRODUCT_LIST_FAIL,
      PRODUCT_DETAILS_REQUEST,
      PRODUCT_DETAILS_SUCCESS,
      PRODUCT_DETAILS_FAIL,
      PRODUCT_CREATE_REQUEST,
      PRODUCT_CREATE_SUCCESS,
      PRODUCT_CREATE_FAIL,
      PRODUCT_CREATE_RESET,
      PRODUCT_UPDATE_REQUEST,
      PRODUCT_UPDATE_SUCCESS,
      PRODUCT_UPDATE_FAIL,
      PRODUCT_UPDATE_RESET,
      PRODUCT_DELETE_REQUEST,
      PRODUCT_DELETE_SUCCESS,
      PRODUCT_DELETE_FAIL,
      PRODUCT_DELETE_RESET,
    } from '../constants/productConstants';
    
    export const productListReducer = (
      state = { loading: true, products: [] },
      action
    ) => {
      switch (action.type) {
        case PRODUCT_LIST_REQUEST:
          return { loading: true };
        case PRODUCT_LIST_SUCCESS:
          return { loading: false, products: action.payload };
        case PRODUCT_LIST_FAIL:
          return { loading: false, error: action.payload };
        default:
          return state;
      }
    };
    
    export const productDetailsReducer = (state = { loading: true }, action) => {
      switch (action.type) {
        case PRODUCT_DETAILS_REQUEST:
          return { loading: true };
        case PRODUCT_DETAILS_SUCCESS:
          return { loading: false, product: action.payload };
        case PRODUCT_DETAILS_FAIL:
          return { loading: false, error: action.payload };
        default:
          return state;
      }
    };
    export const productCreateReducer = (state = {}, action) => {
      switch (action.type) {
        case PRODUCT_CREATE_REQUEST:
          return { loading: true };
        case PRODUCT_CREATE_SUCCESS:
          return { loading: false, success: true, product: action.payload };
        case PRODUCT_CREATE_FAIL:
          return { loading: false, error: action.payload };
        case PRODUCT_CREATE_RESET:
          return {};
        default:
          return state;
      }
    };
    export const productUpdateReducer = (state = {}, action) => {
      switch (action.type) {
        case PRODUCT_UPDATE_REQUEST:
          return { loading: true };
        case PRODUCT_UPDATE_SUCCESS:
          return { loading: false, success: true };
        case PRODUCT_UPDATE_FAIL:
          return { loading: false, error: action.payload };
        case PRODUCT_UPDATE_RESET:
          return {};
        default:
          return state;
      }
    };
    export const productDeleteReducer = (state = {}, action) => {
      switch (action.type) {
        case PRODUCT_DELETE_REQUEST:
          return { loading: true };
        case PRODUCT_DELETE_SUCCESS:
          return { loading: false, success: true };
        case PRODUCT_DELETE_FAIL:
          return { loading: false, error: action.payload };
        case PRODUCT_DELETE_RESET:
          return {};
        default:
          return state;
      }
    };
    

I also have speculated that the error could be caused by my ProductListScreen.js down below:

                import React, { useEffect } from 'react';
            import { useDispatch, useSelector } from 'react-redux';
            import { Link, useParams, useNavigate } from 'react-router-dom';
            import {
              createProduct,
              deleteProduct,
              listProducts,
            } from '../actions/productActions';
            import LoadingBox from '../components/LoadingBox';
            import MessageBox from '../components/MessageBox';
            import {
              PRODUCT_CREATE_RESET,
              PRODUCT_DELETE_RESET,
            } from '../constants/productConstants';
            
            export default function ProductListScreen(props) {
              const navigate = useNavigate();
              const productList = useSelector((state) => state.productList);
              const { loading, error, products } = productList;
            
              const productCreate = useSelector((state) => state.productCreate);
              const {
                loading: loadingCreate,
                error: errorCreate,
                success: successCreate,
                product: createdProduct,
              } = productCreate;
          
              const productDelete = useSelector((state) => state.productDelete);
              const {
                loading: loadingDelete,
                error: errorDelete,
                success: successDelete,
              } = productDelete;
          
              const dispatch = useDispatch();
              useEffect(() => {
                if (successCreate) {
                  dispatch({ type: PRODUCT_CREATE_RESET });
                  navigate(`/product/${createdProduct._id}/edit`);
                }
                if (successDelete) {
                  dispatch({ type: PRODUCT_DELETE_RESET });
                }
                dispatch(listProducts());
              }, [createdProduct, dispatch, navigate, successCreate, successDelete]);
          
              const deleteHandler = (product) => {
                if (window.confirm('Are you sure to delete?')) {
                  dispatch(deleteProduct(product._id));
                }
              };
              const createHandler = () => {
                dispatch(createProduct());
              };
              return (
                <div>
                  <div className="row">
                    <h1>Products</h1>
                    <button type="button" className="primary" onClick={createHandler}>
                      Create Product
                    </button>
                  </div>
            
                  {loadingDelete && <LoadingBox></LoadingBox>}
                  {errorDelete && <MessageBox variant="danger">{errorDelete}</MessageBox>}
            
                  {loadingCreate && <LoadingBox></LoadingBox>}
                  {errorCreate && <MessageBox variant="danger">{errorCreate}</MessageBox>}
                  {loading ? (
                    <LoadingBox></LoadingBox>
                  ) : error ? (
                    <MessageBox variant="danger">{error}</MessageBox>
                  ) : (
                    <table className="table">
                      <thead>
                        <tr>
                          <th>ID</th>
                          <th>NAME</th>
                          <th>PRICE</th>
                          <th>CATEGORY</th>
                          <th>BRAND</th>
                          <th>ACTIONS</th>
                        </tr>
                      </thead>
                      <tbody>
                        {products.map((product) => (
                          <tr key={product._id}>
                            <td>{product._id}</td>
                            <td>{product.name}</td>
                            <td>{product.price}</td>
                            <td>{product.category}</td>
                            <td>{product.brand}</td>
                            <td>
                              <button
                                type="button"
                                className="small"
                                onClick={() => navigate(`/product/${product._id}/edit`)}
                              >
                                Edit
                              </button>
                              <button
                                type="button"
                                className="small"
                                onClick={() => deleteHandler(product)}
                              >
                                Delete
                              </button>
                            </td>
                          </tr>
                        ))}
                      </tbody>
                    </table>
                  )}
                </div>
              );
            }
            

Thats all.

How to avoid adding an undefined key that won’t be accessed because of an early return in TypeScript?

I’m looking for a way to write a function where I don’t have to include a key with undefined value in TypeScript. Partly for stylistic reasons and partly because I feel like I may be misunderstanding something or missing a more defensive way to write it.

In the function I potentially access an object using a key that’s one of the arguments. If the optional argument has a specific key, there’s an early return with no accessing involved.

type MyType = 'foo' | 'bar' | 'baz'

function foo(type: MyType, objectArgument?: Record<string, number>) {
  if (objectArgument && objectArgument.someProperty) {
    return {
      someKey: `hello ${someComputation(objectArgument.someProperty)}`,
      anotherKey: `goodbye ${someComputation(objectArgument.someProperty)}`
    }
  }

  const opts = {
    foo: {
      x: 'some string'
    },
    bar: {
      y: 'another string'
    }
    baz: undefined // without this baz the error the compiler errors with:
    // `Property 'baz' does not exist on type '{ foo: { x: string; }; bar: { y: string; }; }`
  }

  return opts[type]
}

some example invocations:

foo('foo')
foo('bar')
foo('baz', { someProperty: 123 })

In the example above, is there a way that I can write the opts object without the baz: undefined kvp?

I’ve tried wrapping the second opts obj in an if statement (the remaining two types) and also successfully silenced the error by using return opts[type as keyof typeof opts] but after reading up on as keyof typeof notation in other questions I’m not sure I understand it and want to make sure I haven’t just tricked the compiler erroneously.

JavaScript to flatten nested JSON object based on key value

Any suggestions on how to update below JSON object as expected one in Javascript?

Have been trying to flatten JSON object based on JSON key,

  • ..outer_component[x] contains section{} then moved to outer_component[x].outer_body.outer_component[x]
  • ..outer_component[x] contains outer_body{} then keep on iterate till it reaches section{} and move outer_component[x].outer_body.outer_component[x]

Received JSON Object:

{
  "document": {
    "outer_component": [
      {
        "outer_body": {
          "outer_component": [
            {
              "outer_body": {
                "outer_component": [
                  {
                    "section": {
                      "id": [
                        {
                          "root": "INNER_11"
                        }
                      ]
                    }
                  },
                  {
                    "section": {
                      "id": [
                        {
                          "root": "INNER_12"
                        }
                      ]
                    }
                  }
                ]
              }
            },
            {
              "outer_body": {
                "outer_component": [
                  {
                    "section": {
                      "id": [
                        {
                          "root": "INNER_21"
                        }
                      ]
                    }
                  },
                  {
                    "section": {
                      "id": [
                        {
                          "root": "INNER_22"
                        }
                      ]
                    }
                  }
                ]
              }
            }
          ]
        }
      },
      {
        "outer_body": {
          "outer_component": [
            {
              "outer_body": {
                "outer_component": [
                  {
                    "outer_body": {
                      "outer_component": [
                        {
                          "outer_body": {
                            "outer_component": [
                              {
                                "section": {
                                  "id": [
                                    {
                                      "root": "INNER_31"
                                    }
                                  ]
                                }
                              },
                              {
                                "section": {
                                  "id": [
                                    {
                                      "root": "INNER_32"
                                    }
                                  ]
                                }
                              }
                            ]
                          }
                        },
                        {
                          "outer_body": {
                            "outer_component": [
                              {
                                "section": {
                                  "id": [
                                    {
                                      "root": "INNER_33"
                                    }
                                  ]
                                }
                              },
                              {
                                "section": {
                                  "id": [
                                    {
                                      "root": "INNER_34"
                                    }
                                  ]
                                }
                              }
                            ]
                          }
                        }
                      ]
                    }
                  }
                ]
              }
            }
          ]
        }
      }
    ]
  }
}

Expected Output:

{
  "document": {
    "outer_component": [
      {
        "outer_body": {
          "outer_component": [
            {
              "section": {
                "id": [
                  {
                    "root": "INNER_11"
                  }
                ]
              }
            },
            {
              "section": {
                "id": [
                  {
                    "root": "INNER_12"
                  }
                ]
              }
            },
            {
              "section": {
                "id": [
                  {
                    "root": "INNER_21"
                  }
                ]
              }
            },
            {
              "section": {
                "id": [
                  {
                    "root": "INNER_22"
                  }
                ]
              }
            }
          ]
        }
      },
      {
        "outer_body": {
          "outer_component": [
            {
              "section": {
                "id": [
                  {
                    "root": "INNER_31"
                  }
                ]
              }
            },
            {
              "section": {
                "id": [
                  {
                    "root": "INNER_32"
                  }
                ]
              }
            },
            {
              "section": {
                "id": [
                  {
                    "root": "INNER_33"
                  }
                ]
              }
            },
            {
              "section": {
                "id": [
                  {
                    "root": "INNER_34"
                  }
                ]
              }
            }
          ]
        }
      }
    ]
  }
}

Can I encode binary JS data – including uIntArrays and ArrayBuffers – to a string format in a single step?

Similar to Binary Data in JSON String. Something better than Base64 however I’m asking about JS datatypes specifically (like Uint8Array) and don’t have a requirement to use JSON or base64.

I have a JS Object with many nested values including values of type Uint8Array and ArrayBuffer that I need to send as an encoded string.

I know I can convert individual fields to strings and then manually decode each specific field on the other end.

That’s the approach I’m currently taking – though code like:


export const uInt8ArrayToString = (uInt8Array: Uint8Array) => {
  const string: string = utf8Decoder.decode(uInt8Array);
  return string;
};

export const arrayBufferToString = (buffer: ArrayBuffer): string => {
  return utf8Decoder.decode(new Uint8Array(buffer));
};

And for decoding:

export const stringToUint8Array = (string: string) => {
  const uint8Array: Uint8Array = utf8Encoder.encode(string);
  return uint8Array;
};

export const stringToArrayBuffer = (string: string) => {
  const uint8Array: Uint8Array = utf8Encoder.encode(string);
  const arrayBuffer: ArrayBuffer = uInt8ArrayToArrayBuffer(uint8Array);
  return arrayBuffer;
};

However this seems somewhat inefficient, as I have to note the data type used by each field and encode/decode specific fields on end/

Can I encode binary JS data – including uIntArrays and ArrayBuffers – to a string format in a single step?

How to capture all matched pattern that surround by another pattern?

For example:
I want to find all numbers from “aa12345aa” that surround by “aa”.

I tried:

"aa12345aa".matchAll(/aa(d)*?aa/ig)

However, this will result only 1 array that only capture last number, which is 5

['aa12345aa', '5', index: 0, input: 'aa12345aa', groups: undefined]

I want to capture all numbers, so result will be:

['aa12345aa', '1','2','3','4','5' index: 0, input: 'aa12345aa', groups: undefined]

Any suggestion will appreciate, Thanks!!

Checkbox cannot be unselected or selected

I would like to create a checkbox with basic checkbox functionality (ie. you click it, the checkbox is selected, you click it again, it is unchecked).

However, this action is not happening (the checkbox remains checked regardless of whether I click it or not).

Here is my code:

export const check: checkComponent = ({ id, checked = false, disabled, onChange }) => {
  ...
  return (
      ...
      <label
        className={classNames("inputCheckboxLabel", {
          "inputCheckboxLabel--checked": checked,
          "inputCheckboxLabel--disabled": disabled,
        })}
      />
      <input
        id={inputId}
        type="checkbox"
        className="inputCheckboxLabel--input"
        checked={checked}
        disabled={disabled}
        onChange={() => onChange(!checked)}
      />
    </div>
  )
}

Here is my css:

.inputCheckboxLabel--input {
  display: none;
}
.inputCheckboxLabel {
  border: 1px solid var(--color-light-shade);
  background-color: var(--color-lighter-shade);
  display: flex;
  justify-content: center;
  align-items: center;
  padding: 0.125rem;
  width: 1.25rem;
  height: 1.25rem;
  cursor: pointer;
}
.inputCheckboxLabel--checked:before {
  content: " ";
  width: 100%;
  height: 100%;
  border-color: var(--color-constructive);
  background-color: var(--color-constructive);
}
.inputCheckboxLabel--disabled {
  cursor: progress;
}

I am not getting any errors, here is my onChange function:

onChange={async (newValue) => {
  await consumerSetTransactionApproval({
    transactionId: transaction.id,
    newValue,
  })

  setApproved(newValue)
}}

How to add additional data to Vega lite tooltip?

I’m trying to add an additional value (in this case z) to the tooltip. How can I achieve this with the following schema I have so far? I can’t seem to figure it out from the documentations and not seeing any examples of this. Any help would be appreciated. Thanks.

Screenshot

{
    "$schema": "https://vega.github.io/schema/vega-lite/v5.json",
    "width": "container",
    "height": 300,
    "data": {
        "name": "table",
        "values": [
            {
                "x": "Sun - 1",
                "y": -0.01,
                "c": "This Month (02/26/23 - 03/07/23)",
                "z": "01/01/23"
            },
            {
                "x": "Sun - 1",
                "y": -0.01,
                "c": "Last Month (01/01/23 - 02/04/23)",
                "z": "03/01/23"
            },
            {
                "x": "Mon - 1",
                "y": 0.18,
                "c": "This Month (02/26/23 - 03/07/23)",
                "z": "01/01/23"
            },
            {
                "x": "Mon - 1",
                "y": 0.7,
                "c": "Last Month (01/01/23 - 02/04/23)",
                "z": "03/01/23"
            },
            {
                "x": "Tue - 1",
                "y": 0.23,
                "c": "This Month (02/26/23 - 03/07/23)",
                "z": "01/01/23"
            },
            {
                "x": "Tue - 1",
                "y": 0.45,
                "c": "Last Month (01/01/23 - 02/04/23)",
                "z": "03/01/23"
            },
            {
                "x": "Wed - 1",
                "y": 0.21,
                "c": "This Month (02/26/23 - 03/07/23)",
                "z": "01/01/23"
            },
            {
                "x": "Wed - 1",
                "y": 0.11,
                "c": "Last Month (01/01/23 - 02/04/23)",
                "z": "03/01/23"
            },
            {
                "x": "Thu - 1",
                "y": 0.79,
                "c": "This Month (02/26/23 - 03/07/23)",
                "z": "01/01/23"
            },
            {
                "x": "Thu - 1",
                "y": 0.35,
                "c": "Last Month (01/01/23 - 02/04/23)",
                "z": "03/01/23"
            },
            {
                "x": "Fri - 1",
                "y": 0.82,
                "c": "This Month (02/26/23 - 03/07/23)",
                "z": "01/01/23"
            },
            {
                "x": "Fri - 1",
                "y": 0.28,
                "c": "Last Month (01/01/23 - 02/04/23)",
                "z": "03/01/23"
            },
            {
                "x": "Sat - 1",
                "y": 0,
                "c": "This Month (02/26/23 - 03/07/23)",
                "z": "01/01/23"
            },
            {
                "x": "Sat - 1",
                "y": -0.01,
                "c": "Last Month (01/01/23 - 02/04/23)",
                "z": "03/01/23"
            },
            {
                "x": "Sun - 2",
                "y": 0,
                "c": "This Month (02/26/23 - 03/07/23)",
                "z": "01/01/23"
            },
            {
                "x": "Sun - 2",
                "y": -0.01,
                "c": "Last Month (01/01/23 - 02/04/23)",
                "z": "03/01/23"
            },
            {
                "x": "Mon - 2",
                "y": 0.21,
                "c": "This Month (02/26/23 - 03/07/23)",
                "z": "01/01/23"
            },
            {
                "x": "Mon - 2",
                "y": 0.11,
                "c": "Last Month (01/01/23 - 02/04/23)",
                "z": "03/01/23"
            },
            {
                "x": "Tue - 2",
                "y": 0.18,
                "c": "This Month (02/26/23 - 03/07/23)",
                "z": "01/01/23"
            },
            {
                "x": "Tue - 2",
                "y": 0.7,
                "c": "Last Month (01/01/23 - 02/04/23)",
                "z": "03/01/23"
            },
            {
                "x": "Wed - 2",
                "y": 0.1,
                "c": "This Month (02/26/23 - 03/07/23)",
                "z": "01/01/23"
            },
            {
                "x": "Wed - 2",
                "y": 0.5,
                "c": "Last Month (01/01/23 - 02/04/23)",
                "z": "03/01/23"
            },
            {
                "x": "Thu - 2",
                "y": 0.58,
                "c": "This Month (02/26/23 - 03/07/23)",
                "z": "01/01/23"
            },
            {
                "x": "Thu - 2",
                "y": 0.2,
                "c": "Last Month (01/01/23 - 02/04/23)",
                "z": "03/01/23"
            },
            {
                "x": "Fri - 2",
                "y": 0.23,
                "c": "This Month (02/26/23 - 03/07/23)",
                "z": "01/01/23"
            },
            {
                "x": "Fri - 2",
                "y": -0.01,
                "c": "Last Month (01/01/23 - 02/04/23)",
                "z": "03/01/23"
            },
            {
                "x": "Sat - 2",
                "y": -0.01,
                "c": "This Month (02/26/23 - 03/07/23)",
                "z": "01/01/23"
            },
            {
                "x": "Sat - 2",
                "y": -0.01,
                "c": "Last Month (01/01/23 - 02/04/23)",
                "z": "03/01/23"
            },
            {
                "x": "Sun - 3",
                "y": -0.01,
                "c": "This Month (02/26/23 - 03/07/23)",
                "z": "01/01/23"
            },
            {
                "x": "Sun - 3",
                "y": -0.01,
                "c": "Last Month (01/01/23 - 02/04/23)",
                "z": "03/01/23"
            },
            {
                "x": "Mon - 3",
                "y": 0.82,
                "c": "This Month (02/26/23 - 03/07/23)",
                "z": "01/01/23"
            },
            {
                "x": "Mon - 3",
                "y": -0.01,
                "c": "Last Month (01/01/23 - 02/04/23)",
                "z": "03/01/23"
            },
            {
                "x": "Tue - 3",
                "y": 0.82,
                "c": "This Month (02/26/23 - 03/07/23)",
                "z": "01/01/23"
            },
            {
                "x": "Tue - 3",
                "y": -0.01,
                "c": "Last Month (01/01/23 - 02/04/23)",
                "z": "03/01/23"
            },
            {
                "x": "Wed - 3",
                "y": 0.82,
                "c": "This Month (02/26/23 - 03/07/23)",
                "z": "01/01/23"
            },
            {
                "x": "Wed - 3",
                "y": -0.01,
                "c": "Last Month (01/01/23 - 02/04/23)",
                "z": "03/01/23"
            },
            {
                "x": "Thu - 3",
                "y": 0.21,
                "c": "This Month (02/26/23 - 03/07/23)",
                "z": "01/01/23"
            },
            {
                "x": "Thu - 3",
                "c": "Last Month (01/01/23 - 02/04/23)",
                "z": "03/01/23",
                "y": -0.01
            },
            {
                "x": "Fri - 3",
                "y": 0.18,
                "c": "This Month (02/26/23 - 03/07/23)",
                "z": "01/01/23"
            },
            {
                "x": "Fri - 3",
                "c": "Last Month (01/01/23 - 02/04/23)",
                "z": "03/01/23",
                "y": -0.01
            },
            {
                "x": "Sat - 3",
                "y": -0.01,
                "c": "This Month (02/26/23 - 03/07/23)",
                "z": "01/01/23"
            },
            {
                "x": "Sat - 3",
                "c": "Last Month (01/01/23 - 02/04/23)",
                "z": "03/01/23",
                "y": -0.01
            },
            {
                "x": "Sun - 4",
                "y": -0.01,
                "c": "This Month (02/26/23 - 03/07/23)",
                "z": "01/01/23"
            },
            {
                "x": "Sun - 4",
                "c": "Last Month (01/01/23 - 02/04/23)",
                "z": "03/01/23",
                "y": -0.01
            },
            {
                "x": "Mon - 4",
                "y": 0.23,
                "c": "This Month (02/26/23 - 03/07/23)",
                "z": "01/01/23"
            },
            {
                "x": "Mon - 4",
                "c": "Last Month (01/01/23 - 02/04/23)",
                "z": "03/01/23",
                "y": -0.01
            },
            {
                "x": "Tue - 4",
                "y": 0.21,
                "c": "This Month (02/26/23 - 03/07/23)",
                "z": "01/01/23"
            },
            {
                "x": "Tue - 4",
                "c": "Last Month (01/01/23 - 02/04/23)",
                "z": "03/01/23",
                "y": -0.01
            },
            {
                "x": "Wed - 4",
                "y": 0.79,
                "c": "This Month (02/26/23 - 03/07/23)",
                "z": "01/01/23"
            },
            {
                "x": "Wed - 4",
                "c": "Last Month (01/01/23 - 02/04/23)",
                "z": "03/01/23",
                "y": -0.01
            },
            {
                "x": "Thu - 4",
                "y": 0.82,
                "c": "This Month (02/26/23 - 03/07/23)",
                "z": "01/01/23"
            },
            {
                "x": "Thu - 4",
                "c": "Last Month (01/01/23 - 02/04/23)",
                "z": "03/01/23",
                "y": -0.01
            },
            {
                "x": "Fri - 4",
                "y": 0.82,
                "c": "This Month (02/26/23 - 03/07/23)",
                "z": "01/01/23"
            },
            {
                "x": "Fri - 4",
                "c": "Last Month (01/01/23 - 02/04/23)",
                "z": "03/01/23",
                "y": -0.01
            },
            {
                "x": "Sat - 4",
                "y": -0.01,
                "c": "This Month (02/26/23 - 03/07/23)",
                "z": "01/01/23"
            },
            {
                "x": "Sat - 4",
                "c": "Last Month (01/01/23 - 02/04/23)",
                "z": "03/01/23",
                "y": -0.01
            },
            {
                "x": "Sun - 5",
                "y": -0.01,
                "c": "This Month (02/26/23 - 03/07/23)",
                "z": "01/01/23"
            },
            {
                "x": "Sun - 5",
                "c": "Last Month (01/01/23 - 02/04/23)",
                "z": "03/01/23",
                "y": -0.01
            },
            {
                "x": "Mon - 5",
                "y": 0.18,
                "c": "This Month (02/26/23 - 03/07/23)",
                "z": "01/01/23"
            },
            {
                "x": "Mon - 5",
                "c": "Last Month (01/01/23 - 02/04/23)",
                "z": "03/01/23",
                "y": -0.01
            },
            {
                "x": "Tue - 5",
                "y": 0.18,
                "c": "This Month (02/26/23 - 03/07/23)",
                "z": "01/01/23"
            },
            {
                "x": "Tue - 5",
                "c": "Last Month (01/01/23 - 02/04/23)",
                "z": "03/01/23",
                "y": -0.01
            },
            {
                "x": "Wed - 5",
                "y": 0.18,
                "c": "This Month (02/26/23 - 03/07/23)",
                "z": "01/01/23"
            },
            {
                "x": "Wed - 5",
                "c": "Last Month (01/01/23 - 02/04/23)",
                "z": "03/01/23",
                "y": -0.01
            },
            {
                "x": "Thu - 5",
                "y": 0.18,
                "c": "This Month (02/26/23 - 03/07/23)",
                "z": "01/01/23"
            },
            {
                "x": "Thu - 5",
                "c": "Last Month (01/01/23 - 02/04/23)",
                "z": "03/01/23",
                "y": -0.01
            },
            {
                "x": "Fri - 5",
                "y": 0.18,
                "c": "This Month (02/26/23 - 03/07/23)",
                "z": "01/01/23"
            },
            {
                "x": "Fri - 5",
                "c": "Last Month (01/01/23 - 02/04/23)",
                "z": "03/01/23",
                "y": -0.01
            },
            {
                "x": "Sat - 5",
                "y": -0.01,
                "c": "This Month (02/26/23 - 03/07/23)",
                "z": "01/01/23"
            },
            {
                "x": "Sat - 5",
                "c": "Last Month (01/01/23 - 02/04/23)",
                "y": -0.01
            }
        ]
    },
    "encoding": {
        "x": {
            "field": "x",
            "axis": {
                "labelAngle": 270
            },
            "title": "",
            "sort": null
        },
        "opacity": {
            "value": 0.5
        }
    },
    "layer": [
        {
            "encoding": {
                "color": {
                    "field": "c",
                    "type": "nominal",
                    "title": "",
                    "scale": {
                        "range": [
                            "#CC3EBE",
                            "#5E5782"
                        ]
                    },
                    "legend": {
                        "orient": "top-left"
                    },
                    "sort": {
                        "field": "x",
                        "order": "ascending"
                    }
                },
                "y": {
                    "field": "y",
                    "type": "quantitative",
                    "title": "",
                    "scale": {
                        "domain": [
                            0,
                            1
                        ]
                    },
                    "axis": {
                        "format": ".0~%",
                        "values": [
                            0,
                            0.25,
                            0.5,
                            0.75,
                            1
                        ]
                    },
                    "stack": null
                },
                "xOffset": {
                    "field": "c"
                }
            },
            "layer": [
                {
                    "mark": {
                        "type": "bar",
                        "width": {
                            "band": 1
                        },
                        "align": "center"
                    }
                },
                {
                    "transform": [
                        {
                            "filter": {
                                "param": "hover",
                                "empty": false
                            }
                        }
                    ],
                    "mark": {
                        "type": "bar",
                        "width": {
                            "band": 1
                        },
                        "align": "center"
                    }
                }
            ]
        },
        {
            "transform": [
                {
                    "calculate": "datum.y >= 0 ? datum.y : -1",
                    "as": "y"
                },
                {
                    "pivot": "c",
                    "value": "y",
                    "groupby": [
                        "x"
                    ]
                }
            ],
            "mark": "rule",
            "encoding": {
                "opacity": {
                    "condition": {
                        "value": 0.3,
                        "param": "hover",
                        "empty": false
                    },
                    "value": 0
                },
                "tooltip": [
                    {
                        "field": "This Month (02/26/23 - 03/07/23)",
                        "type": "nominal",
                        
                        "title": "This Month"
                    },
                    {
                        "field": "Last Month (01/01/23 - 02/04/23)",
                        "type": "nominal",
                        
                        "title": "Last Month"
                    }
                ]
            },
            "params": [
                {
                    "name": "hover",
                    "select": {
                        "type": "point",
                        "fields": [
                            "x"
                        ],
                        "nearest": true,
                        "on": "mouseover",
                        "clear": "mouseout"
                    }
                }
            ]
        }
    ]
}

Link to the editor

I’ve tried various examples but just can’t figure out how to add the z value to the tooltip.

Live Graph Including live time and live population not working

I am in process of creating a live graph with javascript where the x axis is live British time zone and the y axis is data from personal firebase database which updates every 1000ms and the main issue is that the graph is not appearing.

I connected the js code to my database.

import firebase from 'firebase/app';
import "firebase/database";
const firebaseConfig={--
};
firebase.initializeApp(firebaseConfig);

Then began the chart

var dbRef = firebase.database().ref('population');


google.charts.load("current", {
  packages: ["corechart", "line"]
});

google.charts.setOnLoadCallback(drawChart);

var chart=document.getElementById("chart_div")
 
var data = new google.visualization.DataTable();
    data.addColumn('string', 'Time');
    data.addColumn('number', 'Value');

dbRef.on('value', function(snapshot) {
   data.removeRows(0, data.getNumberOfRows());

   snapshot.forEach(function(childSnapshot) {
    var childData = childSnapshot.val();
    var time = new Date(childData.time).toLocaleString('en-GB');
    var value = childData.value;
    data.addRow([time, value]);
  });

   chart.draw(data, options);
});

setInterval(function() {
  var data = chart.getDataTable();
  var x = new Date().toLocaleString('en-GB');
  var y = dbRef.value;
  data.addRow([x, y]);
  chart.draw(data, options);
}, 1000);

And in html i couldnt even get the chart to appear and I could not figure it out.

Calling python function from javascript with ajax and flask gives 404 GET error: GET http://127.0.0.1:5500/register 404 (Not Found)

I am trying to add a user account feature to my html page. To do this I have created a mysql server with xampp. I have successfully connected and added records to it via a python backend file. The next step was to link that to a javascript function which was, in turn, linked to an html button. Code:

index.html:

<!DOCTYPE html>
<html lang="en"> 
    <head>
      <script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
    </head>
    <body>

        <div id="login-container">
          <form id="login-form" class="login-form">
            <label for="email" class="email-label"><b>Email: </b></label>
            <input type="text" class="email" placeholder="Enter Email" name="email" required />
            <button type="submit" class="login-button" id="signupbutton">Sign Up</button>
          </form>
        </div>
        <script src="http://127.0.0.1:5500/react-integrated/script.js"></script>

    </body>
</html>

script.js:

function SignUp() {
    $.ajax({
        type: "GET",
        url: "/register",
      });
}

document.getElementById("signupbutton").onclick = function () {
  SignUp();
};

database.py:

import mysql.connector
import json
from flask import Flask, request
from flask_cors import CORS

app = Flask(__name__)
CORS(app)

mydb = mysql.connector.connect(
  host="127.0.0.1",
  user="root",
  database="Users"
)

@app.route('/register')
def register_user():
    print("Register requested")
    register("Samuel")

def register(username):
    print("Register requested")
    startToDoList = []
    mycursor = mydb.cursor()
    sql = "INSERT INTO users (username, todo_list) VALUES (%s, %s)"
    val = (username, json.dumps(startToDoList))
    print(f"{username}")
    mycursor.execute(sql,val)
    mydb.commit()

app.run()

All these are in the same folder. As for the database, it is called Users and has one table called users (poor name choice). The table has a primary key called id, a username field and a todo_list field. I can write into it if I call the register_user function from directly within the python file so that isn’t the issue (also neither of the “Register requested” statements are printed so there’s that evidence). When I run the html file though and then try clicking on the button, I get this error:

jquery-3.6.0.min.js:2 GET http://127.0.0.1:5500/register 404 (Not Found)

I have the database.py file running in vscode while this is happening (index.html is run on this address http://127.0.0.1:5500/react-integrated/index.html) as I think is correct. I’m pretty confused about how the index.html file, database and flask app can all be running on the same app too (I’m very new to ajax, flask and generally backend so any advice much appreciated).

I know this question is very similar: Calling python from Javascript 404 not found but the answer wasn’t accepted and I didn’t understand it very well so I hoped someone else could give guidance.

Dynamic Content (Not iframe or api)

I need your professional help with an interesting task for me. And so.. I use the Dynamicooo Remote Content plugin for Elementor pro (WP) with it, I pulled the dynamic data from the site and was able to change the CSS and it makes me happy. BUT! It does not work as an Iframe , that is, when I click on the content, I go to the site from which the excerpt was taken. And now the question.. How can I make it so that I would stay inside my site? At the same time, had all the dynamic content from another site? That is, it is such a replacement for API or Iframe .. as you like. I was thinking about some kind of JS code that will be able to dynamically create links and generate content from this plugin. And maybe I’m not thinking correctly .. I ask for your help

Remote Content plugin for Elementor pro (WP)

Flask – Using javascript and url_for to replace html

I am new to Flask (as well as whatever else is involved in what I’m trying to do, apparently) and I’m creating a small using M. Grinberg’s Mega-Tutorial as reference (Flask==2.2.3, jQuery==3.6.4).

I’m trying to incorporate a range html input element

<input id="slider" type="range" min="0" max="10" name="slider" value="1"/>

whose value I’m trying to take via jQuery and use to trigger an endpoint to create an image:

@main.route("/graph.png/order=<order>")

which I then want to display in another element in the page, without re-rendering the entire thing from scratch.

I’m incorporating a script in the template:

{% block base_script %}
<script src="{{ url_for('static', filename='js/client_render.js') }}"></script>
{% endblock %}

I would think that this would do the trick:

$(document).on('input', '#polyfit_order_slider', function () {
    slider_val = $('#polyfit_order_slider').get()[0]['value'];
    console.log(slider_val);

    $(document.getElementById('cur-input')).text('Current input: ' + slider_val)


    $(document.getElementById('graph_fit')).html(
        "<img src='{{ url_for('main.graph', order="+slider_val+") }}'></img>"
    )
});

but it so happens that every time I move the input slider I’m getting a yellow 404 in the terminal "GET /%7B%7B%20url_for( HTTP/1.1" and a GET http://localhost:8000/%7B%7B%20url_for( 404 (NOT FOUND) from the console.

What is the correct syntax to use for this scenario? I’ve implemented the functionality using entire page re-renders on the server side by having the user click submit on a flask wtf form but I feel a more dynamic client interaction would be better, if possible.

Notes:

  • I’m trying to follow Flask docs’ Generating URLs but when putting anything like const user_url = {{ url_for("user", id=current_user.id)|tojson }} in the tags I’m getting SyntaxErrors.

  • The reference I mentioned does something very similar here.