Match JSON values with a key and convert content inside in lower case

This is my JSON that I am in need to modify.

Source Json:

    "data": {
      "types": [
        {
          "name": "type1",
          "handler": {
            "graphql": {
              "domain": "https://<MY_DUMMY_DOMAIN>/graphql",
              "operationHeaders": {
                  "Authorization": "Bearer {context.headers['MyOperationHeader']}"
              },
              "schemaHeaders": {
                  "Authorization": "Bearer {context.headers['MySchemaHeader']}"
              }
            }
          }
        }
      ]
    }
  }

Expected Output:

    "data": {
      "types": [
        {
          "name": "type1",
          "handler": {
            "graphql": {
              "domain": "https://<MY_DUMMY_DOMAIN>/graphql",
              "operationHeaders": {
                  "Authorization": "Bearer {context.headers['myoperationheader']}"
              },
              "schemaHeaders": {
                  "Authorization": "Bearer {context.headers['myschemaheader']}"
              }
            }
          }
        }
      ]
    }
  }

I need to write this logic in a .ts file.

There can be multiple values inside operationHeaders and schemaHeaders. For simplicity I have taken only one value as “Authorization”.

There can be multiple values of types

I am thinking of approach that inside types if I can search context.headers and whatever comes inside the curly braces of context.headers, I convert it to lower case.

But not so sure how to do/proceed with that.

Any suggestions please.

Grab javascript data from html to Python server

I try to send data from an html page from javascript (function onto “onclick”) to server powered with python. I am no programmer but i vetted for ways to do it like file transfer, JSON, requests package, beautifulsoup library but i don’t know the best way to do it.

May you give me your opinion on this or even examples?

Regards

Trying to read JSON from a text file and send in post request. Unexpected token o in JSON at position 1

I have a file input element on a page. I select a JSON file and then use FileReader to read the contents. I want to then send the contents in a post request. I feel I have tried every possible combination of header parameters and parsing/stringifying the results from the filereader but I either get an empty body in my req.body or I get the error:

SyntaxError: Unexpected token o in JSON at position 1

I know there are many other posts about this and I have looked through them all but I don’t know what I’m doing wrong.

// This function is called when the user clicks the upload button after selecting a json file.
 // It reads the contents of the JSON file 
 const upload = async () => {

  var fileReader = new FileReader();
  const data = fileReader.onload = function(e){

    let data = JSON.parse(e.target.result);

    const URL = '/upload';

  fetch(URL, {method: 'POST', headers: {'Content-Type' : 'application/json'}, body: {data}}).then((response) => {
    if(!response.ok){
      throw new Error('Something went wrong')
    }     
  }
  )
  .catch((e) => {
    console.log(e)
  });
  }
  fileReader.readAsText(document.querySelector("#input").files[0], 'UTF-8');

 } 

And here is the server code

app.use(express.json());

// Empty the database and reupload new questions from a JSON file
app.post('/upload',  async (req, res) => {

    // Create client object and wait for connection
    const client = new MongoClient(URL);
    await client.connect();

    // Set database
    const db = client.db('trivia');

    // Remove all data from the database
    db.collection('questions').deleteMany();

    // Repopulate database with new questions
    console.log(req.body);
})

I’ve tried sending the data after parsing, after stringifying, after both. I’m not sure what form I should send it in. Right now based on the syntax error it’s being sent as JSON object? The data is an array of JSON objects:

[{}, {}, {}] (this format)

Vitest Assertion Error: expected “spy” to be called with arguments: […args]

I have this login form in react:
`


const LoginPage = () => {
    const [error, setError] = useState<string | null>(null);
    const router = useRouter()
    const {
        handleSubmit,
        register,
        reset
    } = useForm<LoginFormData>()

    const onSubmit: SubmitHandler<LoginFormData> = async (data) => {
        const response = await signIn('credentials', {
            ...data,
            redirect: false,
        })

        if (response && response.ok) {
            setError(null)
            reset()
            router.replace('/billboard')
            return
        }


        if (response && response.error) setError(response.error)
    }

    return (
        <div>
            <Image
                src='/images/logo.png'
                alt="hero"
                width={160} height={160}
                className='absolute z-20 top-5 left-5'
            />
            {!!error && <p>
                <AiOutlineFire /> {error}
            </p>}
            <form
                onSubmit={handleSubmit(onSubmit)}>
                <h2 className="text-2xl font-semibold">Login</h2>
                <div>
                    <input
                        type="text" {...register('email')}
                        aria-label='email'
                        placeholder="Email address or phone number"
                    />
                    <input
                        type="password" {...register('password')}
                        aria-label='password'
                        placeholder="Password"
                    />
                </div>
                <div>
                    <button
                        type="submit" aria-label='submit'>
                        Login
                    </button>
                    <div>
                        <FcGoogle
                            size={35}
                        />
                        <VscGithub
                            size={35}
                        />
                    </div>
                    <p>
                        <span>First time using Netflix? </span>
                        <Link href='/auth/signup' className="font-bold">
                            Create a Netflix account.
                        </Link>
                    </p>
                </div>
            </form>
        </div>
    );
}

export default LoginPage;

And I want to test login authentication in my fron-end testing. Here is the test code:

import { render, screen } from '@testing-library/react'
import LoginPage from './LoginPage'
import userEvent from '@testing-library/user-event'

vi.mock('next/router', () => require('next-router-mock'))

vi.mock('next-auth/react', () => ({
    signIn: vi.fn()
}))

vi.spyOn(require('next-auth/react'), 'signIn')

describe('LoginPage', async () => {
    beforeEach(() => vi.clearAllMocks())
    
    it('should submit a non existing email', async () => {
        const signIn = vi.fn()

        render(<LoginPage />)

        const emailInput = screen.getByLabelText('email')
        const passwordInput = screen.getByLabelText('password')
        const submitButton = screen.getByLabelText('submit')

        const email = 'anderson@gmail'
        const password = 'password123'

        await userEvent.type(emailInput, email)
        await userEvent.type(passwordInput, password)
        await userEvent.click(submitButton)

        expect(signIn).toHaveBeenCalledWith('credentials', {
            email, password,
            redirect: false,
        })
    })
})

Here is the output:

src/common/components/pages/LoginPage/LoginPage.test.tsx > LoginPage > should submit a non existing email
AssertionError: expected "spy" to be called with arguments: [ 'credentials', …(1) ]

Received:


Number of calls: 0

 ❯ src/common/components/pages/LoginPage/LoginPage.test.tsx:32:24      
     30|         await userEvent.click(submitButton)
     31| 
     32|         expect(signIn).toHaveBeenCalledWith('credentials', {  
       |                        ^
     33|             email, password,
     34|             redirect: false,

I want to check if the signIn function from next-auth was called, so I can keep wring the rest of the test script. I have searched throughout the internet for a problem like this, but it seems that no solution works. Most of the solutions out there are all about Jest, and I’m using vitest, altough vitest and jest are pretty much the same.

Is it possible to render TS types or values of variables inside markdown files using VitePress or Nextra?

I want to create a documentation using Vitepress ( or similiar, e.g. Nextra ). This app uses a package which contains types and Zod schemas. The root library index.ts could be

import { z } from 'zod';

const userSchema = z
  .object({
    username: z.string().min(1),
  })
  .strict();

type User = z.infer<typeof userSchema>;

export { userSchema, type User }

Is there a way to either render the schema or the type inside the markdown file?

Maybe with the help of Vue files ( VitePress ) or MDX/NextJs ( Nextra )

I just want to describe the schema or type but don’t want to copy paste all the fields from it because then I have to take care that everything is in sync.

How to pass Base64String from File Upload to image property in FormGroup using PatchValue in Angular Reactive Form

Good day All,
Please have code where uploaded image will be converted to base64String and send to an API. I am using reactive Form, the issue is that I keep having an ERROR when patching the base64String result to the FormGroup Image Property. Below is the code.

 onFileChange(event) {
      let reader = new FileReader();
     
      if(event.target.files && event.target.files.length) {
        const [file] = event.target.files;
        reader.readAsDataURL(file);
      
        reader.onload = () => {
          this.formGroup.patchValue({
            file: reader.result as string
          });
          
         
        };
      }
    }

But I keep getting occurs when it is trying to patch Value to the Form Group, this ERRORS.
ERROR DOMException: An attempt was made to use an object that is not, or is no longer, usable

Please I need help from any one.

How to select the active slide and a table element using JS React?

I am a beginner in web development. As part of an exercise I would like to modify the javascript code of the link below.
I would like to make the button elements clickable.

https://codepen.io/hexagoncircle/pen/jgGxKR?editors=0010


  const slide1Button = document.querySelector('.btn'); 
  slide1Button.addEventListener('click', function() {
  window.open(slideData[0].url);
  }); 


  const slide2Button = document.querySelector('.btn'); 
  slide2Button.addEventListener('click', function() {
  window.open(slideData[1].url);
  }); 


const slideData = [
{
  index: 0,
 
  button: 'VISITER',
  url: 'https://www.interflora.fr/',
  src: 'https://lecoqetlecerisier.files.wordpress.com/2011/05/dsc037411.jpg' },
 

{
  index: 1,

  button: 'VISITER',
  url: 'https://www.123fleurs.com/',
  src: 'http://idata.over-blog.com/1/39/34/32/Poitiers-Ici-et-La/Macro-fleur-rose.JPG' },

{
  index: 2,

  button: 'VISITER',
  url: 'https://www.aquarelle.com/',
  src: 'http://monmondevirtuel.m.o.pic.centerblog.net/o/91d323e8.jpg' },

{
  index: 3,

  button: 'VISITER',
  url: 'https://www.florajet.com/',
  src: 'http://www.juille.com/images/006_3.JPG' }
];

I have added the code

It works halfway, because I can’t determine that for slide current it selects the button and on click redirects according to the url written in the slideData table.

this only selects the first url of the table i want to make the element interactive and have it follow the current slide.

If anyone can help me or advise me in my approach.

Is it not possible with Manifest V3 chrome extensions to seamlessly “hot swap” requests?

I want to intercept certain fetch API calls from a web page via Chrome extension (Manifest V3), cancel them, and seamlessly replace their responses (as if the request had been successful) with a different response. I think this isn’t possible seamless with the chrome.webRequest API.

I think GPT-4 actually provides an accurate answer here:

In Manifest V3, you cannot directly cancel a request and make another
one with the response being sent to the listener handling the original
request using the chrome.webRequest API, as blocking listeners are
no longer supported.

However, you can achieve this functionality indirectly by using a
combination of chrome.webRequest API and background scripts.

Here’s a high-level overview of how you can do this:

  1. Use the chrome.webRequest.onBeforeRequest listener to listen for requests.
  2. When the listener is triggered, cancel the original request by returning {cancel: true}.
  3. In the background script, make a new request using the fetch API or XMLHttpRequest with the modified URL or parameters.
  4. When the new request’s response is received, use the chrome.tabs.sendMessage API to send the response to the content
    script.
  5. In the content script, listen for messages using the chrome.runtime.onMessage API and handle the response accordingly.

Keep in mind that this approach will not be as seamless as directly
replacing the request, as it involves communication between background
and content scripts, and you’ll need to handle inserting the response
into the page or processing it in the content script.

But I don’t want to have to reverse engineer the page. And I tried overriding the native fetch function, but this doesn’t work because the web page is loading its own fresh version somewhere. Is there any clever solution here or are my options basically to RE the web app I want to intercept requests for or kick rocks?

For context, ChatGPT is causing data leakage problems with employees feeding source code into ChatGPT, but OpenAI’s privacy policy on the API version of GPT is much, much better for these scenarios (30 day retention without training versus indefinite retention and training against the data). So I want to make a browser extension to replace the normal ChatGPT web app API calls and replace it with an API using the org’s API account. A Data Loss Mitigation of sorts.

Add click events to newly added elements in pure JS [duplicate]

I want to add a click event to elements with class item. Work fine:

const enlargables = document.querySelectorAll('.item');
enlargables.forEach(function(el) {
    el.addEventListener('click', function(e) {
        alert('hello');
    })
});
<div class="item">test 1</div>
<div class="item">test 2</div>

But if the element is added dynamically after pageload, the event will not be added to the element.

How can I add the event to newly added elements with class item using pure JS? Similar to how document ready works in jQuery.

How to display a specific Local Distribution Zone (LDZ) and hover/click to have the targetted region information using OpenLayers extension?

There are several regions over UK:
North East, North West, Yorkshire and The Humber, East Midlands, West Midlands, East of England, London, South East, and South West.

A user will focus a region and see pre-defined information for it as shown below:

enter image description here

What is the best OpenLayers extension to achieve that, using OpenLayers?

There are several other examples over OpenLayers examples catalog

CartoDB colors entire countries, I am looking for color fill, but for smaller regions and filtering by regions from UK.

Sentiment Analysis Using the LSTM Algorithm

how to solve this problem?
ValueError: in user code:

File "/usr/local/lib/python3.9/dist-packages/keras/engine/training.py", line 1284, in train_function  *
    return step_function(self, iterator)
File "/usr/local/lib/python3.9/dist-packages/keras/engine/training.py", line 1268, in step_function  **
    outputs = model.distribute_strategy.run(run_step, args=(data,))
File "/usr/local/lib/python3.9/dist-packages/keras/engine/training.py", line 1249, in run_step  **
    outputs = model.train_step(data)
File "/usr/local/lib/python3.9/dist-packages/keras/engine/training.py", line 1051, in train_step
    loss = self.compute_loss(x, y, y_pred, sample_weight)
File "/usr/local/lib/python3.9/dist-packages/keras/engine/training.py", line 1109, in compute_loss
    return self.compiled_loss(
File "/usr/local/lib/python3.9/dist-packages/keras/engine/compile_utils.py", line 240, in __call__
    self.build(y_pred)
File "/usr/local/lib/python3.9/dist-packages/keras/engine/compile_utils.py", line 182, in build
    self._losses = tf.nest.map_structure(
File "/usr/local/lib/python3.9/dist-packages/keras/engine/compile_utils.py", line 353, in _get_loss_object
    loss = losses_mod.get(loss)
File "/usr/local/lib/python3.9/dist-packages/keras/losses.py", line 2653, in get
    return deserialize(identifier, use_legacy_format=use_legacy_format)
File "/usr/local/lib/python3.9/dist-packages/keras/losses.py", line 2600, in deserialize
    return legacy_serialization.deserialize_keras_object(
File "/usr/local/lib/python3.9/dist-packages/keras/saving/legacy/serialization.py", line 543, in deserialize_keras_object
    raise ValueError(

ValueError: Unknown loss function: 'binary)crossentropy'. Please ensure you are using a `keras.utils.custom_object_scope` and that this object is included in the scope. See https://www.tensorflow.org/guide/keras/save_and_serialize#registering_the_custom_object for details.

someone can help to solve this problem?
Binary)crossentropy’. Please ensure you are using a keras.utils.custom_object_scope and that this object is included in the scope

Highcharts: Conditional tooltip based on multiple checking chart is drilldown or not

 formatter: function() {
                           return (this.hasOwnProperty("drilldown") ? 'Count of user' : 'count of number' + this.point.y);
                         }
                   },

I just want to change tooltip text based on drilldown condition.

I have set Xaxis name by add event in chart and it’s working So what should i do for tooltip ??

events: {drilldown: function(e) {
                              this.xAxis[0].setTitle({
                                text: 'Accounts'
                              });
                            },
                            drillup: function(e) {
                              this.xAxis[0].setTitle({
                                text: 'Source'
                              });
                            }
                          }

HTML – Magento Add multiple products in cart

i need to add 2 or more products in the same to the cart in magento.

<div class="actions-primary"> 
    <form data-role="tocart-form" data-product-sku="CODE12345" action="https://blahblah.com/checkout/cart/add/product/12345" method="post">
<input type="hidden" name="product" value="12345">
<input type="hidden" name="uenc" value="gfdskjhgd">
<input name="form_key" type="hidden" value="hfgghfg"/> 
<button type="submit" title="Add to Cart" class="action tocart primary">
<i class="icon-cart icon-span mr-3"></i> 
<span>Add to Cart</span>
</button>
</form>
</div>
</div> 
<script type="text/x-magento-init">
            {
                "[data-role=tocart-form], .form.map.checkout": {
                    "catalogAddToCart": {
                        "product_sku": "CODE12345"
                    }
                }
            }
</script>
    </div> 

how can i add in the same time more products in the cart?

thanks in advance

I have no access to php