teleren/devto huggingface dataset:
How to add an object to localStorage?
Tags: javascript, localstorage, object, beginners
Published: 2022-07-04 16:02:12

In this note I will show you how to insert an object to localStorage 

In some situations you may want to store data in local storage or session storage as an object. So how can you achieve this?

Assume that we have an object and this object stores some tokens.
```JavaScript
const tokens = {
token: "meowmeow",
anotherToken: "woofwoof"
}
```
<hr>

### Writing to localStorage
To set a localStorage item we have to use `localStorage.setItem( )` method. This method takes two parameters, `key` and `value`. `key` is the name of our local storage item and the value is basically its value.

We cannot directly store objects in localStorage or session storage. Therefore we have to convert them into JSON string. To do that we have very handy method called `JSON.stringify(value)`. `value` parameter is going to be object that we want to convert into JSON string. In this example **value** is **tokens**

```JavaScript
JSON.stringify(tokens)
```

We learned how to convert object into JSON string. Now, let's add this JSON string to our localStorage

```JavaScript
const tokens = {
token: "meowmeow",
anotherToken: "woofwoof"
}

localStorage.setItem("tokens", JSON.stringify(tokens))

```

If you check your local storage, you can see that your object has been successfully added.

![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/fbp2wogawps94oa265y0.png)

<hr>

### Reading from localStorage
To read an object from localStorage, we have another handy method called `JSON.parse( )`. This method helps us to convert JSON string into JavaScript object. But first, we have to get the object from local storage.

```JavaScript
const localStorageItem = localStorage.getItem("tokens")
const tokenObject  = JSON.parse(localStorageItem)


console.log(tokenObject)

/*
{
token: "meowmeow",
anotherToken: "woofwoof"
}
*/

```
Using NPM VS Yarn in React
Tags: javascript, react
Published: 2022-07-04 16:00:45

While most junior Software Engineers tend to gravitate to NPM (Node Package manager) like myself. Most experienced React Engineers gravitate to yarn. Yea! boring right?

Both have similarities and differences but at the end of the day both get the job done. 

NPM tends to be on the slow side of things when installing dependencies. However, yarn seems to be a bit slower when starting an application.

The reason behind the slowness of yarn is due to it's validation checks. In all honesty, I really don't mind. I feel a bit safer and confident using yarn over NPM now that I have given it a shot. 

Lets briefly compare yarn and npm.

```
Command	                     npm	yarn
Install dependencies:	npm install	yarn
Install package: npm install [package]	yarn add [package]
Update:         	npm update	yarn upgrade

```
To learn more about yarn you can visit the official site here: https://classic.yarnpkg.com/en/docs/getting-started

You can also visit Digital Ocean's cheat sheet here: https://www.digitalocean.com/community/tutorials/nodejs-npm-yarn-cheatsheet.

I hope whichever path you choose will lead you to a speedy development process....minus the bugs.
Quick tutorial: JavaScript Form Validation
Published: 2022-07-04 15:55:42

[JavaScript Form Validation
](https://getbutterfly.com/javascript-form-validation/)

This JavaScript code snippet adds inline validation to any form field (input, select and textarea).

**Match an element against a given pattern and add a visual hint:**

```
function cgPatternMatch(element, pattern) {
    if ((element.value).match(pattern)) {
        cgToggleError(element, 'valid');
    } else {
        cgToggleError(element, 'invalid');
    }
}
```

**Match an element against a given value:**

```
function cgValueMatch(e) {
    return (e.value !== '') ? true : false;
}
```

**Check if email and email confirmation elements match and add a visual hint:**

```
function cgEmailValidate(e1, e2) {
    let pattern = /^([\w-\.]+)@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.)|(([\w-]+\.)+))([a-zA-Z]{2,4}|[0-9]{1,3})(\]?)$/;

    if (
        e1.value === e2.value &&
        pattern.test(e1.value) &&
        pattern.test(e2.value)
    ) {
        cgToggleError(e2, 'valid');
    } else {
        cgToggleError(e2, 'invalid');
    }
}
```

**Match an element against a given pattern (based on validation type) and add a visual hint:**

```
function cgFormValidate(element, type) {
    if (type === 'alpha') {
        let pattern = /^[a-zA-Z\-'.\s]+$/;

        cgPatternMatch(element, pattern);
    } else if (type === 'numeric') {
        let pattern = /^[0-9]{1,10}$/;

        cgPatternMatch(element, pattern);
    } else if (type === 'alphanumeric') {
        let pattern = /^[,'a-zA-Z0-9\-\s]+$/;

        cgPatternMatch(element, pattern);
    } else if (type === 'date') {
        let pattern = /^[,'0-9\/\s]+$/;

        cgPatternMatch(element, pattern);
    } else if (type === 'email') {
        let pattern = /^([\w-\.]+)@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.)|(([\w-]+\.)+))([a-zA-Z]{2,4}|[0-9]{1,3})(\]?)$/;

        cgPatternMatch(element, pattern);
    } else if (type === 'dropdown') {
        if (element.value === '') {
            cgToggleError(element, 'invalid');
        } else {
            cgToggleError(element, 'valid');
        }
    }
}
```

Next, custom data validation needs some additional HTML parameters and an `onload()` event.

Read more about [custom JavaScript form validation](https://getbutterfly.com/javascript-form-validation/) and implementation on my development blog.
What are cyber-physical systems?
Tags: opensource, microservices, embedded, luos
Published: 2022-07-04 15:52:25

A few days ago, we talked about a specific term: Cyber-physical systems (CPS).

▶️ https://www.luos.io/blog/cyber-physical-systems

With this blog post, let's take a look at what CPS is, some examples, how it differs from IoT and the impacts/benefits of these systems in your daily life.
Learn how to create mini online apps from a LiveChat expert during our Live Coding Session 👀
Tags: webdev, beginners, tutorial, react
Published: 2022-07-04 15:30:55

Hello, DEV community! 👋 

I’d like to invite you to a special event where you will be able to learn how to build an actual online app that you will be able to effectively sell in our [Marketplace](https://www.livechat.com/marketplace/?utm_source=dev.to&utm_medium=referral&utm_campaign=lcs-july).

In the [LiveChat Developer Platform](https://developers.livechat.com/?utm_source=dev.to&utm_medium=referral&utm_campaign=lcs-july), we encourage external developers to create extensions to our product – [LiveChat](https://www.livechat.com/?utm_source=dev.to&utm_medium=referral&utm_campaign=lcs-july), which allow our clients (35K+ of them!) to communicate with their customers via new channels. Many of our integrations were built this way, such as the integration with WhatsApp. 
Our customers can buy them in our Marketplace to further adjust LiveChat to their business needs.

This time, we will be introducing building blocks. Using their intuitive user interfaces, you will be able to configure API core functions in just a moment. During our event, you will have the opportunity to learn how to add the property building blocks by building a simple application in our Console.

As you will be creating apps for active users, you will also learn about [LiveChat properties](https://developers.livechat.com/updates/livechat-properties/?utm_source=dev.to&utm_medium=referral&utm_campaign=lcs-july) – they allow you to store pieces of data about user licenses. They were designed to be easy to implement, so you could use them when creating a complex backend setup for your app.

You’ll also have the opportunity to see an example of an already-published app! We’ll be analyzing the code of [Quick Notes](https://www.livechat.com/marketplace/apps/quick-notes/) – one of the most popular LiveChat extensions which relies heavily on LC properties.

Join us on **July 6th at 5pm CET** and see how easy it is to create useful apps for LiveChat users 👌 

[[[SAVE YOUR SEAT]]](https://developers.livechat.com/updates/live-coding-livechat-properties?utm_source=dev.to&utm_medium=referral&utm_campaign=lcs-july)
Types🗂️ of errors💔 in programming
Tags: beginners
Published: 2022-07-04 15:30:30



**1) Syntax❓ error :**

   A syntax error is an error in the syntax of a sequence🔢 of characters 🧑‍🎨or tokens 🎟that are intended 🥅to be written📝 in compile-time⏳.

> Print(“hello”);
> Here if we miss ‘ ; ‘ then it’s a syntax error


**2) Logical ✳error :**

   Logical error occurs🍂 when there is a fault 🍂in the logical or structure🧱 of the problem.

> Int array[10]
>  Is given and one takes array as
> Array[10]=[1,2,3,4,5,6,7,8,9,10,11]

Here a logical error takes place
 

**3) Compilation error⚠**

Compilation error refers to a state🗽 when a compiler fails💣 to compile a piece 🧩of a computer program source📤 code, either due to errors in the code👨‍💻, or more unusually, due to errors in the compiler itself🧑.

> Print(“hallo”
>  
> Here ‘)’ is excepted


**4) Runtime🧑 error**

A runtime🏃‍♀️ 🕒error is a program error that occurs while the program is running🏁


> Int a;
> a=”hallo”;


here you are giving𓁉 character value for ‘a’ variable containing🚮 the integer datatype.
Fixed Width Text in React Native
Tags: reactnative
Published: 2022-07-04 15:18:59

---
title: Fixed Width Text in React Native
published: true
description: In this quick post we'll explore the font-variant property to improve your layout when text is rapidly changing.
tags: reactnative
cover_image: https://dev-to-uploads.s3.amazonaws.com/uploads/articles/chms7gy0p6a7gmywit0q.jpg
canonical_url: https://www.reactnativeschool.com/fixed-width-text-in-react-native
---

Despite working on React Native daily for 7 years, I'm still constantly learning new things about it. Recently it was the [`fontVariant` style prop](https://reactnative.dev/docs/text-style-props#fontvariant) on a `Text` component.

> This post was [published a week ago on React Native School](https://www.reactnativeschool.com/fixed-width-text-in-react-native). Be sure to visit for the latest tips, tricks and tutorials on React Native!

I was working a multi-theme stop watch app in React Native (it's [open source](https://github.com/ReactNativeSchool/expo-clock-app)!) and ran into an issue where the width of each number was different.

Normally this is not a problem but when you are changing the numbers every millisecond it looks quite hectic.

![Demo of Problem](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/ld5lua8vw2483o34xoae.gif)
 
To fix this is a simple one liner:

When styling the text, add `fontVariant: ["tabular-nums"]`. This will make the text a fixed width so your layout stays fixed.

Code from the [example app](https://github.com/ReactNativeSchool/expo-clock-app/blob/main/src/screens/StopWatch.tsx#L65):

```tsx
// ...

const styles = StyleSheet.create({
  // ...
  timeText: {
    fontSize: 60,
    fontWeight: "300",
    marginTop: 100,
    fontVariant: ["tabular-nums"], // fixed width character
  },
})

export default StopWatch
```

![Demo of Solution](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/iy53c2f07ylapop4avsb.gif)
 

[MDN has a good resource](https://developer.mozilla.org/en-US/docs/Web/CSS/font-variant) through which you can learn more about the `font-variant` CSS property.
[Unity WebGL] How to make it not load content from cache
Tags: unity3d, webgl, cache
Published: 2022-07-04 15:18:21

How to do it is like when you are going to force it to refresh style or javascript content by add GET parameter follow the files URL for example: version=007, script.js?v=1150. Then we may change parameters after files changed like this: script?v=1151

We can do the same thing with Unity build, in `index.html` file we can add GET parameter to file URL like following example which I've added `id=20220704001`

```
var buildUrl = "Build";
var loaderUrl = buildUrl + "/unity-build.loader.js?id=20220704001";
var config = {
  dataUrl: buildUrl + "/unity-build.data?id=20220704001",
  frameworkUrl: buildUrl + "/unity-build.framework.js?id=20220704001",
  codeUrl: buildUrl + "/unity-build.wasm?id=20220704001",
  streamingAssetsUrl: "StreamingAssets",
  companyName: "Insthync",
  productName: "Unity WebGL",
  productVersion: "0.1",
  showBanner: unityShowBanner,
};
```

We also able to make Unity add GET parameter when builds with WebGL template macro like this:

```
var buildUrl = "Build";
var loaderUrl = buildUrl + "/{{{LOADER_FILENAME}}}?id={{{PRODUCT_VERSION}}}";
var config = {
  dataUrl: buildUrl + "/{{{DATA_FILENAME}}}?id={{{PRODUCT_VERSION}}}",
  frameworkUrl: buildUrl + "/{{{FRAMEWORK_FILENAME}}}?id={{{PRODUCT_VERSION}}}",
  codeUrl: buildUrl + "/{{{CODE_FILENAME}}}?id={{{PRODUCT_VERSION}}}",
  streamingAssetsUrl: "StreamingAssets",
  companyName: "{{{COMPANY_NAME}}}",
  productName: "{{{PRODUCT_NAME}}}",
  productVersion: "{{{PRODUCT_VERSION}}}",
  showBanner: unityShowBanner,
};
```

If we set `Version` (in Build Settings) to `1.0` then when it built, codes in `index.html` will be like:

```
var buildUrl = "Build";
var loaderUrl = buildUrl + "/unity-build.loader.js?id=1.0";
var config = {
  dataUrl: buildUrl + "/unity-build.data?id=1.0",
  frameworkUrl: buildUrl + "/unity-build.framework.js?id=1.0",
  codeUrl: buildUrl + "/unity-build.wasm?id=1.0",
  streamingAssetsUrl: "StreamingAssets",
  companyName: "Insthync",
  productName: "Unity WebGL",
  productVersion: "1.0",
  showBanner: unityShowBanner,
};
```

You can find more information about template macro from [this link](https://docs.unity3d.com/Manual/webgl-templates.html).

* * *

## Addressable Asset not being refreshed?

We can do the same thing by make changes to `StreamingAssets\aa\settings.json` file.

Find `{"m_Keys":["AddressablesMainContentCatalogRemoteHash"],"m_InternalId":` in `settings.json`.

It will have codes like this `"m_InternalId":"https://yourgameassets.com/addressable/WebGL/catalog_2022.07.04.00.00.00.hash"`

Then just add GET parameter like this

`"m_InternalId":"https://yourgameassets.com/addressable/WebGL/catalog_2022.07.04.00.00.00.hash?version=001"`
Fullstack? Why not (Django + Vue-js) - episode 0
Tags: django, vue, aderayevans, tutorial
Published: 2022-07-04 15:15:20

<!-- <style>
    r { color: Red }
    g { color: Green }
    b { color: Blue }
    Orange { color: Orange }
    LightGreen { color: LightGreen }
    Cyan { color: Cyan }
    LightPink { color: LightPink }
</style> -->

## Table of Contents
1. [Django for backend](#django)
2. [Vue.js for frontend](#vuejs)

## <Cyan>Settings essentials</Cyan> 
<hr>
<h2 id="django"><LightGreen>Django for backend</LightGreen></h2>
<hr>
- Anaconda for virtual environment 4.12.0

```python
conda create --name django-env

activate django-env #activate the environment
```

*_Remember to install all commands below inside conda env_ (`django_env`)*

- \>= Python 3.10.4
- Django 4.0.5
> python -m pip install Django

- Django CORS : <Orange>*Cross-Origin-Resource-Policy*</Orange>
> python -m pip install django-cors-headers



<hr>
<h2 id="vuejs"><LightPink>Vue.js for frontend</LightPink></h2>
<hr>
- Install Nodejs 16.15.1 and npm 8.11.0 at https://nodejs.org/en/download/
- vue-cli 5.0.6
> npm install -g vue-cli

- axios 0.27.2
> npm i axios

- typescript 4.7.4 (when cannot find `{frontend_project_dir}/node_modules/typescript`)
> npm install typescript

or
> npm install -g typescript

## Additional settings:

add this line to `{frontend_project_dir}/jsconfig.json`
```js
    "jsx": "preserve",
```
```js
    {
  "compilerOptions": {
    "target": "es5",
    "jsx": "preserve",
    "module": "esnext",
    "baseUrl": "./",
    "moduleResolution": "node",
    "paths": {
      "@/*": [
        "src/*"
        // "./src/**/*.ts"
      ]
    },
    "lib": [
      "esnext",
      "dom",
      "dom.iterable",
      "scripthost"
    ]
  }
}
```
Zink Tips | Made with Next JS
Published: 2022-07-04 15:11:11

![Zink Tips | Made with Javascript | Next JS](https://res.cloudinary.com/madewithjavascript/image/upload/v1656338843/large_zink_tips_made_with_next_js_f9b03bd147.png "Zink Tips | Made with Javascript | Next JS")


### Zink is an easy way to receive micro-donations (from $0.05) for what you create or share on the internet.

> Get more than likes
> Receive micro-tips for what you create on the Internet.
> 
> Your online tip jar
> Whether you publish on a web platform or your own website, tipping you takes a click.
> 
> Get more from smaller tips
> With micro-tips from $0.05, it's so easy to give after enjoying your content. For more people, more often.
> 
> How it works?
> 1. Sign up and create your tip jar
> 2. Share your jar link or add the widget to your site
> 3. Start collecting tips from your audience
> 
> 


Read More here about Zink Tips and find the link to view the showcased website

[Zink Tips | Made with Javascript | Next JS](https://madewithjavascript.club/posts/zink-tips-made-with-next-js)

## Check out more such amazing projects on our website

[Made with Javascript](https://madewithjavascript.club)

## Want us to feature your project

[Submit your Project to Made with Javascript](https://madewithjavascript.club/submit-project)


You can also write to us for any of your queries at:

[Email Made with Javascript](mailto:madewithjavascript@gmail.com)

## Project already shared on our social media handles.

| SocialMedia | SharedLink |
| ----------- | ---------- |
| Twitter | [Zink Tips on Twitter](https://twitter.com/withjavascript/status/1543974220933332992?s=20&t=Wxe_E0HEqNiCych27oWMug)
 |
| Medium | [Zink Tips on Medium](https://medium.com/@madewithjavascript/zink-tips-made-with-next-js-4fbf768e9add)
 |
| Facebook | [Zink Tips on Facebook](https://www.facebook.com/madewithjavascript/posts/pfbid0bWuSmPYRhGuxXTbsAe3eedLo97WCUGfy1J7Ntf3oG63ZGQKxZ2GEAwL6FkpiR8oHl)
 |
| Tumblr | [Zink Tips on Tumblr](https://www.tumblr.com/blog/view/madewithjavascript/688859248457859072?source=share)
 |
| LinkedIn | [Zink Tips on LinkedIn](https://www.linkedin.com/feed/update/urn:li:activity:6949740075316379648)
 |
| Pinterest | [Zink Tips on Pinterest](https://pin.it/79iDeAx)
 |


Filled Under:


 - [Made with Javascript](https://madewithjavascript.club)
 - [Made with Next JS](https://madewithjavascript.club/categories/next-js)

Make sure to give this post ❤ 50 ❤ hearts, click the 🦄 unicorns 🦄 and follow 👉 @madewithjavascript 👈 for more such awesome showcases. Show you love for the people who have worked so hard!
Factorial Program in Java
Tags: factorialprograminjava, java
Published: 2022-07-04 15:07:43

Hey folks, today in this blog you’ll see [Factorial Program in Java](https://codewithnepal.com/factorial-program-in-java/). I have created blogs on making a Group Chat APP Using JAVA and in this fantastic blog, you will learn how to create a Factorial Program in Java. So, Factorial Program in Java: Factorial of n is the product of all positive descending integers. Factorial of n is denoted by n!.For example:
`6! = 720
7! = 5040`


![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/bn7mv9sot2wv91dh23me.jpg)

Here, 6! is pronounced as “6 factorial”, it is also called “6 bang” or “6 shrieks”.

The factorial is normally used in Combinations and Permutations (mathematics).

**The factorial of a positive number n is given by:**
`factorial of n (n!) = 1 * 2 * 3 * 4 * ... * n`

There are many ways to write the [factorial program in java ](https://codewithnepal.com/factorial-program-in-java/)language. Let’s see the 3 ways to write the factorial program in java.

You might like this:

[JavaScript Projects For Beginners](https://codewithnepal.com/javascript-projects-for-beginners/)
[Automatic Image Slider](https://codewithnepal.com/how-to-make-an-automatic-image-sider-in-html-css/)
[Sidebar Menu using HTML and CSS](https://codewithnepal.com/how-to-make-a-sidebar-menu-using-html-and-css/)
[Cool Glowing Effect on Buttons](https://codewithnepal.com/cool-glowing-effect-on-buttons-using-html-css/)

**Example 1: Find the Factorial of a number using BigInteger**
`import java.math.BigInteger;

public class Factorial {

    public static void main(String[] args) {

        int num = 30;
        BigInteger factorial = BigInteger.ONE;
        for(int i = 1; i <= num; ++i)
        {
            // factorial = factorial * i;
            factorial = factorial.multiply(BigInteger.valueOf(i));
        }
        System.out.printf("Factorial of %d = %d", num, factorial);
    }
}`

Here, instead of long, we use BigInteger variable factorial.

Since * cannot be used with BigInteger, we instead use multiply() for the product. Also, num should be cast to BigInteger not long for multiplication.
Changing an Existing Kubernetes Operator to cluster scoped
Tags: kubernetes, openshift, operatorsdk, opensource
Published: 2022-07-04 14:58:29

---
title: Changing an Existing Kubernetes Operator to cluster scoped 
published: true
description: Changing an Existing Kubernetes Operator to cluster scoped 
tags: kubernetes, openshift, operatorsdk, opensource
cover_image: https://dev-to-uploads.s3.amazonaws.com/uploads/articles/3b6ugw1ncsjj85sfsm3m.png
---


Operator scope is what namespaces you operator will watch for Custom Resources(CR's) to be acted upon. 
- Namespaced scoped (watch a single namespace)
- Cluster scoped (watch all namespaces) 

The operator-sdk documentation talks about setting the watchNamespace to an empty string in the operator-sdk `main.go` may look something like the following.  
```golang
    // check the WATCH_NAMESPACE env var to see if populated
    var watchNamespaceEnvVar = "WATCH_NAMESPACE"

    ns, found := os.LookupEnv(watchNamespaceEnvVar)
    if !found {
        return "", fmt.Errorf("%s must be set", watchNamespaceEnvVar)
    }
mgr, err := ctrl.NewManager(ctrl.GetConfigOrDie(), ctrl.Options{
    Scheme:             scheme,
    MetricsBindAddress: metricsAddr,
    Port:               9443,
    LeaderElection:     enableLeaderElection,
    LeaderElectionID:   "f1c5ece8.example.com",
    Namespace:          watchNamespace, // namespaced-scope when the value is not an empty string
})
```
If `Namespace` is not set or set to an empty string your operator will already be cluster scoped. 

If like me you are using OLM ([Operator Lifecycle Mananger](https://olm.operatorframework.io)) to handle install and upgrades of your operator,you don't need change the code in main.go, OLM now handles all scoping changes for you. You only need to change the CSV and the operator group on cluster.

> **NOTE:** v1.0.0 the Operator-sdk or greater 

First you set the install `installModes` for `AllNamespaces` to `true` in your CSV(ClusterServiceVersion)
```yaml
 installModes:
  - supported: true
    type: OwnNamespace
  - supported: true
    type: SingleNamespace
  - supported: false
    type: MultiNamespace
  - supported: true
    type: AllNamespaces 
```
Once this is set and deployed with OLM on cluster the only change we need is to the OperatorGroup spec. A namespaced operatorGroup spec will look like 
```yaml
spec:
  targetNamespaces:
  - whatever_WATCH_NAMESPACES_is
```
To set to Cluster scoped change the spec
```yaml
spec: {}
```
As `AllNamespaces` is set in CSV you don't have to do anything else the operator will change to cluster scoped and watch all namespaces. If you don't update the operatorGroup the operator will remain namespaces scoped. So we go from namespaces scoped

![Example NameSpaced Scoped](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/uxhjs27f6xvmhgly3yk7.png)

To cluster scoped

![Example Cluster-scoped](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/le2m9dls0d2gz2g1goz1.png)

Things to note the resources footprint is a little higher for the cluster scoped operator and CSV for the Operator are created in all namespaces on the cluster.