My First Post      My Facebook Profile      My MeOnShow Profile      W3LC Facebook Page      Learners Consortium Group      Job Portal      Shopping @Yeyhi.com

Pages










Friday, August 23, 2024

Python's F-String for String Interpolation and Formatting

Interpolating Values and Objects in F-Strings

In latest python, F-strings make the string interpolation process intuitive, quick, and concise. The syntax is similar to what you used with .format(), but it’s less verbose. You only need to start your string literal with a lowercase or uppercase f and then embed your values, objects, or expressions in curly brackets at specific places:

>>> name = "Jane"
>>> age = 25
>>> f"Hello, {name}! You're {age} years old."
'Hello, Jane! You're 25 years old.'

Earlier in Python 3.6 we had the Modulo Operator, % for thsi purpose

The modulo operator (%) was the first tool for string interpolation and formatting in Python and has been in the language since the beginning. Here’s what using this operator looks like in practice:

>>> name = "Jane"
>>> "Hello, %s!" % name
'Hello, Jane!'
Or, see the next example
>>> name = "Jane"
>>> age = 25

>>> "Hello, %s! You're %s years old." % (name, age)
'Hello, Jane! You're 25 years old.'
Or, see the next example for decimal point formatting
>>> "Balance: $%.2f" % 5425.9292
'Balance: $5425.93'

Thursday, August 22, 2024

How to fix rearrangement of display screen/spaces on Mac?

Sometimes i get irritated when i see the arrangement of spaces or screen changes when i want to switch between screens on Mac. I always try to ask how do you prevent the macos from occasionally changing or resetting the display arrangement on its own upon waking up or a reboot?

The solution is simple:


Go to Apple > System Preferences > 

Mission Control > un-check "Automatically rearrange spaces" 

and "Displays have separate spaces" 

Cheers :)

If you also want to understand How to fix Mission Control Not working on MAC OS then you can refer my earlier post from 2021 - https://www.w3lc.com/2021/08/how-to-fix-mission-control-not-working.html



Tuesday, August 20, 2024

Resolving 'Failed to Fetch' Errors in JavaScript

The "TypeError: Failed to fetch" error is a common and often frustrating issue encountered when working with web applications. This error usually arises from problems with the Fetch API and can be caused by a variety of factors.




Common Reasons for "Failed to Fetch" Errors

1. Incorrect or Incomplete URL

   - The URL used in the `fetch()` method might be incorrect or incomplete.

   - Make sure the URL includes the correct protocol (https:// or http://) and that the path is accurate.

2. CORS (Cross-Origin Resource Sharing) Issues

   - The server might not be returning the correct CORS headers. If you're unfamiliar with CORS, you can refer to the MDN documentation.

   - Ensure the server is configured with the appropriate `Access-Control-Allow-*` headers.

3. Incorrect Fetch Configuration

   - There could be errors in the HTTP method or headers passed to the `fetch()` method.

   - Double-check that the configuration, including the URL, HTTP method, and headers, is correct.

4. Browser Extensions

Occasionally, browser extensions can trigger these errors by interfering with API calls or altering the responses.


Steps to Debug


1. Verify the URL

   - Ensure the URL in the `fetch()` method is correct and complete.

   - Check that the protocol, path, and HTTP method are accurate.

2. Inspect the Browser Console

   - The browser console can provide valuable insights into failed API calls.

   - Look for errors related to CORS or other network issues.

3. Check CORS Headers

   - Confirm that the server is sending the correct CORS headers.

   - Use the browser’s Network tab to review the headers of the failed requests.

4. Experiment with Different Configurations

   - Try different `fetch()` configurations to pinpoint the issue.

   - Adjust methods, headers, and URL formats as needed.

5. Consider Using a Proxy

   - If modifying server headers isn’t possible, consider using a proxy to bypass CORS restrictions.

   - Implement proxies with tools like Express or `cors-anywhere` in Node.js.




Friday, August 16, 2024

Enable CORS on a resource using the AWS API Gateway console

 Sometimes while hitting an API gateway you get error suggesting No 'Access-Control-Allow-Origin' header is present on the requested resource. If an opaque response serves your needs, set the request's mode to 'no-cors' to fetch the resource with CORS disabled.


In such a case, sometimes people suggest to set the request mode to 'no-cors' like so:

fetch(url, {

    mode: "no-cors",

    ...

})

But if you're getting CORS issues this is not the solution. If the API endpoint is something that you control, then you have to fix those CORS issue there. If the API endpoint is not something that you control, then you have to proxy your request through a server that does have CORS enabled.

You need to remove the mode: 'no-cors' setting from your request. Setting no-cors mode is exactly the cause of the problem you’re having. A no-cors request makes the response type opaque. The log snippet in the question shows that. Opaque means your frontend JavaScript code can’t see the response body or headers.

With no-cors — JavaScript may not access any properties of the resulting Response

So the effect of setting no-cors mode is essentially to tell browsers, “Don’t let frontend JavaScript code access the response body or headers under any circumstances.”

People sometimes try setting no-cors mode when a response doesn’t include the Access-Control-Allow-Origin response header or else because the request is one that triggers a CORS preflight, and so your browser does an OPTIONS preflight. But using no-cors mode isn’t a solution to those problems. The solution is either to:

  1. configure the server to which you’re making the request such that it sends the Access-Control-Allow-Origin response header, and such that it handles OPTIONS requests
  2. or set up a CORS proxy using code from https://github.com/Rob--W/cors-anywhere/ or such; see the How to use a CORS proxy to get around “No Access-Control-Allow-Origin header” problems section of the answer at No 'Access-Control-Allow-Origin' header is present on the requested resource—when trying to get data from a REST API 
  3. Temporarily you can also use Chrome extension of Enabling CORS. But it is for debugging phase only.

However, it is evident that sometimes you clearly need to Enable CORS on a resource. You can do this using the API Gateway console.


To enable CORS support on a REST API resource
  1. Sign in to the API Gateway console at https://console.aws.amazon.com/apigateway

  2. Choose an API.

  3. Choose a resource under Resources.

  4. In the Resource details section, choose Enable CORS.



Next Steps/settings In the Enable CORS box:
  • (Optional) If you created a custom gateway response and want to enable CORS support for a response, select a gateway response.
  • Select each method to enable CORS support. The OPTION method must have CORS enabled.
  • If you enable CORS support for an ANY method, CORS is enabled for all methods.
  • In the Access-Control-Allow-Headers input field, enter a static string of a comma-separated list of headers that the client must submit in the actual request of the resource. Use the console-provided header list of 'Content-Type,X-Amz-Date,Authorization,X-Api-Key,X-Amz-Security-Token' or specify your own headers.
  • Use the console-provided value of '*' as the Access-Control-Allow-Origin header value to allow access requests from all origins, or specify origins to be permitted to access the resource.
  • Choose Save.



After this, deploy the API again and see the fun in next call!


Thursday, August 15, 2024

Some simple dev setups on Mac developer machine

 Install HomeBrew on Mac:

/bin/bash -c "$(curl -fsSL https://raw.githubusercontent.com/Homebrew/install/HEAD/install.sh)"


==> Next steps:

- Run these two commands in your terminal to add Homebrew to your PATH:

    (echo; echo 'eval "$(/opt/homebrew/bin/brew shellenv)"') >> /Users/mfaiz/.zprofile

    eval "$(/opt/homebrew/bin/brew shellenv)"

- Run brew help to get started

- Further documentation:


Install NodeJs:

brew install node@20



If you need to have node@20 first in your PATH, run:

  echo 'export PATH="/opt/homebrew/opt/node@20/bin:$PATH"' >> ~/.zshrc


For compilers to find node@20 you may need to set:

  export LDFLAGS="-L/opt/homebrew/opt/node@20/lib"

  export CPPFLAGS="-I/opt/homebrew/opt/node@20/include"


# verifies the right Node.js version is in the environment

node -v 

# verifies the right npm version is in the environment

npm -v 


In case node command etc not working then link it using following command:

% brew link node@20



Create React App:


npx create-react-app little-billi

cd my-app

npm start


If you've previously installed create-react-app globally via npm install -g create-react-app, we recommend you uninstall the package using npm uninstall -g create-react-app or yarn global remove create-react-app to ensure that npx always uses the latest version.



When npm starts the server, Then open http://localhost:3000/ to see your app.

When you’re ready to deploy to production, create a minified bundle with npm run build.

Meanwhile in browser you could see: