teleren/devto huggingface dataset:
UPDATE > MariaDB
Tags: database, mariadb, sql, opensource
Published: 2022-04-17 17:19:12

The UPDATE command helps us to change or modify the records that have already been inserted into a table. You can combine it with the WHERE clause to specify the record that is to be updated. Here is the syntax:

```
UPDATE tableName SET field=newValue, field2=newValue2,...  
[WHERE ...]  
```

The UPDATE command can also be combined with clauses such as SET, WHERE, LIMIT, and ORDER BY. You will see this shortly:

Let’s change the price of the book with an id of 1 from 200 to 250:

```
UPDATE price 
SET price = 250
WHERE id = 1;
```
The Weekly Dev - 202216
Published: 2022-04-17 17:09:28

---
title: The Weekly Dev - 202216
published: true
description: 
tags: 
//cover_image: https://direct_url_to_image.jpg
canonical_url: 'https://kevwe.com/weekly/202216'
---
The Weekly Dev - 202216

It is always DNSSEC

Or maybe not!

The debate is quite hot about the need to secure DNS infrastructure.

The stakes are high at some levels, and of course migrating all the existing infrastructures to a secure DNS has high costs, no wonder it is taking time, and pain, and suffer, and breaches.

But as I came to understand, apart from the big corporates, who have to manage their own DNS infrastructure, and have to put in place some crazy key-signing fool-proof workflow, if you use a decent registrar for your domains management, the transition from DNS to DNSSEC should be a matter of: "click ENABLE DNSSEC".

And if that's the case for you, you have to just do it, enable DNSSEC for all of your domains.

https://kevwe.com/weekly/202216
Is time travel possible?
Tags: story, discuss, welcome, think
Published: 2022-04-17 17:07:47

But what if you could time travel without all the drama? What if all you wanted was to hop ahead a few years or take a quick trip to the past for some fun? 

That's where things get more complicated. Philosophers and scientists have been grappling with the implications of time travel for centuries, and there's still no consensus about whether it's even possible. 

Some argue that time travel is logically impossible because it would create paradoxes: If you traveled back in time and killed your own grandfather, how would you be born to go back in time and kill him? But others say that such paradoxes can be resolved through something called "the grandfather paradox." This theory suggests that traveling back in time wouldn't actually change anything because the traveler would simply exist in a parallel timeline where those events already happened. 

There are also questions about causality: If you went back in time and changed something, what would happen to the present as we know it? And could you really just zip around through different points on the timeline without creating chaos? Some scientists believe that our understanding of physics doesn't allow for actualtime travel – but they admit that they don't know everything about quantum mechanics, so who knows?"
Matrix class implementation
Tags: cpp, tutorial, oop
Published: 2022-04-17 17:02:13

The concept of matrix and multidimensional array had always been an intriguing topic for me when I was in programming classes. Since computer memory isn’t organized in tabular form, there should be a way to represent it. Today, I am going to show you how to implement a matrix class with a component of [an array](https://blogbybao.wordpress.com/2022/03/18/introduction-to-oop-and-array-class-implementation-part-1/). It will simply has some basic operations of matrix such as addition, subtraction, and multiplication.

```
class Matrix
{
private:
    Array *A;
    int rows = 0, cols = 0;

    void deepcopy(const Matrix &other);

public:
    Matrix();
    Matrix(int x, int y);
    void input();
    void output();

    void insert(int, int, int);
    int findCelebrity();

    // ~Matrix();

    Matrix(const Matrix &other);
    Matrix &operator=(const Matrix &other);
    void create_identity(int);
    void create_celeb_test(int);

    // Matrix &operator+(const Matrix &other);
    Matrix &operator-(const Matrix &other);

    int view_rows();
    int view_cols();
    int getElement(int, int);
    void setElement(int, int, int);
    bool knows(int, int);

    friend istream &operator>>(istream &in, Matrix &a);
    friend ostream &operator<<(ostream &out, Matrix a);
};
```

Read more [here](https://blogbybao.wordpress.com/2022/04/17/1121/)!
Configuring eslint and prettier in LunarVim 🌙. Bonus: Tailwindcss 🌊
Tags: vim, tailwindcss, webdev, javascript
Published: 2022-04-17 17:01:58

Congratulations, you decided to move your web-dev activities to neovim. Specifically [LunarVim](https://www.lunarvim.org). Great choice!

LunarVim does most of everything you would expect automatically 🤖 but it does not decide a formatter or linter for you.

lets keep it short and simple:

## eslint

to add `eslint` as a linter for your project. Make sure it is installed as a `devDependency` or is installed globally if you're about that life.

next, while inside `LunarVim`, enter `<leader> L c` (`<leader>` is usually the spacebar unless you changed it) to reach the `config.lua` where you config, using lua, your editor 😃

now at the bottom, add the following lines
```lua
local linters = require "lvim.lsp.null-ls.linters"
linters.setup {
  { command = "eslint", filetypes = { "typescript", "typescriptreact" } }
}
```

just make sure that you didn't declare a local variable `linters` before, save, and voila! You're back in the abusive relationship that is working with eslint!

## prettier

to add `prettier` as a formatter for your project, similar to `eslint` you need to have it installed somewhere reachable, and in the `config.lua` (`<leader> L c`), similar to the linters, add formatters as so:

```lua
local formatters = require "lvim.lsp.null-ls.formatters"
formatters.setup {
  {
    command = "prettier",
    filetypes = { "typescript", "typescriptreact" },
  },
}
```

for the keen-eyed, you can see that the config comes with an example for using `prettier`, so thats cool!

## Bonus: TailwindCSS 🌊

Man I love me some tailwind. I love the intellisense of it and I don't like compromising. So if you're like me, and happened to use tailwind in your project. The setup is rather simple if undocumented.

first install the tailwind lsp using `:LspInstall tailwindcss`. Usually that is enough, but not in this case. lvim comes with configurations for tailwind, but you gotta tell him to actually set tailwind up!

the easiest way is to first install the tailwind language server **globally** like `yarn global add @tailwindcss/language-server`

then go back to your `config.lua` (using `<leader> L c`) and adding the line

```lua
require("lvim.lsp.manager").setup "tailwindcss"
```

Note: there is a way to use a local (read: devDeps) version of the language-server, but it's a tad convoluted and needs to be set up per-project. So Yeah 🤠

Hope that helps anybody


P.S **Try to close and open your LunaVim if either of these don't immediately start up**
Get country code from request proxied by Cloudflare
Tags: cloudflare
Published: 2022-04-17 16:49:33

If your web server is proxied via cloudflare, you can get request's country code:

## Python Flask

```python
country_code = request.headers.get('cf-ipcountry')
```

## Golang Fiber
```golang
countryCode := c.Get("cf-ipcountry")
```

Print out examples:
* US (united states)
* JP (Japan)
* NL (Netherland)

## Reference
* [Cloudflare IP Location](https://support.cloudflare.com/hc/en-us/articles/200168236-Configuring-Cloudflare-IP-Geolocation)
Swift vs React Native
Tags: beginners, mobile, discuss, reactnative
Published: 2022-04-17 16:43:55

Having used SwiftUi for awhile now and having just dabbled here and there with React native, Swift has been my go to as such. Recently I’ve found myself using React native a lot more and chosen to use that to build my new app.

What’s your go to and why? Feel free to link any apps that you have released on the App Store :)
Solidity Gas Optimizations pt.4 - Efficient Strings
Tags: solidity, smartcontracts, ethereum, assembly
Published: 2022-04-17 16:35:09

In the previous lesson, we saw a bit about how the solidty compiler and the EVM stores data in 32 byte 'buckets' or 'slots'. This applies to every operation that deals with storage. This can come in handy when dealing with strings, specially when using `revert()` or `require()`.

## What is a String?
In the Solidity Documentation we can see that:
> Variables of type bytes and string are special arrays. The bytes type is similar to bytes1[], but it is packed tightly in calldata and memory. string is equal to bytes but does not allow length or index access.

Basically, strings are arrays of UTF-8 characters, and arrays are basically a fixed length sequence of storage slots located next to each other. Therefore, like everything else we need to think in terms of storage buckets

## How to use this to our advantage
This means that when we compile our contracts, we would prefer to use a single slot for the strings we use.

Each character in a string is a UTF-8 Encoded byte, meaning that your strings can be up to 32 characters in length if you do not use specially encoded characters like emojis to be contained in a single storage slot.

> **A Note About UTF-8**
UTF encoding is a standard for how computers represent each character in a language. All the standard English characters take up one byte, but things get a bit more difficult when we start with characters like 💩 which takes up 4 bytes (64 bits). 
Here's a great resource to look up how many bytes a string takes up under UTF-8 Encoding. https://mothereff.in/byte-counter

So basically, when we can use this everywhere for example in `revert` statements, we can think of how to make these messages fit in multiples of 32 bytes. 

So instead of having this:
```ts
// 40 bytes or two slots
revert(condition, "User has insufficient funds for transfer")
```
Consider having this:
```ts
//32 bytes or one slot
revert(condition, "Insufficient funds for transfer.")
```

Again, sometimes being verbose is better for everyone to know what is happening, so consider the tradeoffs. This works best when an extra character can add a considerable expense of a function call.

Some further reading on UTF-8 characters: https://blog.hubspot.com/website/what-is-utf-8
Facing Problem in terraform
Tags: terraform, aws, automation, ec2
Published: 2022-04-17 16:18:54

**Scenario** :- I have successfully launch the instance using  terraform but I want that instance to be terminated automatically after specific time/period. Using aws console of EventBridge I can directly add cronjob and link it with an ec2 instance but I need to do it using terraform. Help me to solve this issue. Thank you.
Should documentation be in included in the definition of done?
Tags: productivity, documentation, webdev, programming
Published: 2022-04-17 14:36:14

The Definition of Done (DoD) is a shared understanding of what work must be completed for a work unit (think: user story, sprint, feature) to be released. 

## Why does the Definition of Done matter?

[There are 3 main reasons IMO
](https://swimm.io/blog/documentation-dev-teams-and-the-definition-of-done/)
1. It provides a baseline for sprint planning. If you know ahead of time what is expected in terms of testing, documenting, and deploying then you can more accurately size backlog items and thus, plan accordingly. 
2. Avoiding repetitive conversation and redefinition. A clear DoD provides a framework for defining the tasks required for each work unit. Therefore, you can focus on execution rather than be stuck in a constant loop of defining. 
3. Reducing the need for rework. A clear DoD limits the risk of misunderstanding and conflict among the dev team and product owners. Once a backlog item is accepted as “done”, the chance that it will need to be reworked is reduced, and required (non-critical) updates can be moved into the backlog.

## The DoD doesn't happen in a vacuum

It can't focus on just building usable software. It must be aligned with the overall organization’s needs, goals, and core values. And that's why a DoD should be a collaborative process among all those involved. 

## Should the Definition of Done include developer documentation?

I believe this question is key. And I say yes, the DoD **should** include documentation. 

I think it's useful to go back in time here and remember the conversations we used to have about e2d testing and whether it should be included in the DOD. And guess what. The exact same concerns were raised then. 

It hasn’t taken long, though, for us to recognize that writing tests sooner rather than later has provided great value and allowed us to make significant quality advances. And as a result, end-to-end testing has become part of the DoD for a lot of developers I've spoken with.

So, what do you think? Should it become the new standard?
Django Tutorial Part 9 -- detail で question の子供テーブルの中身も出す。
Tags: django
Published: 2022-04-17 15:50:20


## 何をするのか

https://docs.djangoproject.com/en/4.0/intro/tutorial03/#use-the-template-system

## shell モードを起動して Question1 の Children を確認

```php
docker-compose run web \
python manage.py shell

```

shell モードを起動し

```py

>>> 
from polls.models import Choice, Question
Question.objects.get(pk=1)
<Question: What's up?>

q = Question.objects.get(pk=1)
q.choice_set.all()
<QuerySet []>
```

pk=1 の子供の選択肢がないのを確認する

---

## choise テーブルの中身を入れる

質問の選択肢と投票数がないので作る。

```py
>>> 
q.choice_set.create(choice_text='I got a raise', votes=0)

q.choice_set.create(choice_text='I made a company', votes=1)

q.choice_set.create(choice_text='My Wife is beatuful', votes=10)

q.choice_set.all()
<QuerySet [<Choice: I got a raise>, <Choice: I made a company>, <Choice: My Wife is beatuful>]>
```

回答を 3 つ作った。

---

## Django Admin で確認

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

残念ながらここでは今の所子供テーブルまでは見れないようだ

---

## detail で確認

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

```
{{ question }}
```

question しかないので中は見えない。

これを書き換える。

---

```html
<h1>{{ question }}, {{ question.question_text }}</h1>
{{  question.choice_set.all }}
<ul>
{% for choice in question.choice_set.all %}
    <li>{{ choice }},  {{ choice.choice_text }}</li>
{% endfor %}
</ul>
```


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

question でも question.question_text でも 
question テーブルの question_text の内容が表示される。

自動的にテキストが読み込まれることになるのか？テーブルの最初のカラムだからか？

また、question.choice_set.all でシェルモードと同じように QuerySet で子供テーブルの中身が表示できた。

for で中身を回して question と同様に
choice でも choice.choice_text で　choice テーブルの choice_text が表示されている

これで question の子供テーブルの choise の中身も表示できた。

---

## まとめ

question.choice_set.all で子供テーブルの中身が出せて

```py
{% for choice in question.choice_set.all %}
    <li>{{ choice }}
{% endfor %}
```

for/endfor で回すことで 中身が展開できる。

## 今後

https://docs.djangoproject.com/en/4.0/intro/tutorial04/

次は form の章だが、Django の Template で Form　を書くのはないと思うので、REST FRAMEWORK に戻ろうかと思っている

https://dev.to/kaede_io/django-rest-framework-tutorial-dezuo-tutaapurinosiriaraizazhou-riwoque-ren-suru-316b

シリアライザを短く書いて、リクエスト叩いて登録できる形に持っていくところが残っているので。
How to find if two strings are isomorphic to each other in Javascript
Tags: javascript, webdev, algorithms, tutorial
Published: 2022-04-17 15:43:00

Two strings str1 and str2 are called isomorphic if there is a one-to-one mapping possible for every character of str1 to every character of str2. And all occurrences of every character in ‘str1’ map to the same character in ‘str2’.

```
Input:  str1 = "aab", str2 = "xxy"
Output: True
'a' is mapped to 'x' and 'b' is mapped to 'y'.

Input:  str1 = "aab", str2 = "xyz"
Output: False
One occurrence of 'a' in str1 has 'x' in str2 and 
other occurrence of 'a' has 'y'.
```
 Solution is very simple , we will consider every character of ‘str1’ and check if all occurrences of it map to the same character in ‘str2’.

We keep a hash map,We store each character in str1 as key and character in str2 for the same index as value,

``` javascript
<script>
    function isIsomorphic(str1, str2) {
        var obj = {};
        for (let i = 0; i < str1.length; i++) {
            if (!obj[str1[i]]) {
                obj[str1[i]] = str2[i];
            } else {
                if (obj[str1[i]] !== str2[i]) {
                    return false;
                }
            }
        }
        return true;
    }
    console.log(isIsomorphic("abc", "xyz"));
</script>
```
Hope this helps someone, Please comment if you need more such algorithm question in Javascript
Spring - Circular Dependency
Tags: spring, java, programming
Published: 2022-04-17 14:24:43

---
series: [Spring]
---

Circular dependencies are the scenarios when two or more beans try to inject each other via constructor. 

**Bean A** → Bean B → Bean C → Bean D → Bean E → **Bean A**

or in a simpler way

**Bean A** → Bean B → **Bean A**

## What if everything is 👌 

We instead have something like this:

Bean A → Bean B → Bean C

Spring will create bean C, then create bean B (and inject bean C into it), then create bean A (and inject bean B into it).

With a circular dependency, however, Spring is unable to determine which of the beans should be produced first because they are interdependent. Spring will throw a BeanCurrentlyInCreationException while loading context in these circumstances.

> When implementing constructor injection in Spring, this can happen. We shouldn't have this problem if we utilize other sorts of injections because dependencies will be injected only when they're needed, not when the context is loaded. ❗

## Is there way to fix it? 🤔

- **Redesign** (LOL)
- **Use @Lazy**
  Telling Spring to lazy initialize one of the beans is a straightforward method to stop the cycle. As a result, rather than fully initializing the bean, it will generate a proxy that will be injected into the other bean. When the injected bean is first required, it will be fully created.

```java
@Component
public class CircularDependencyA {

    private CircularDependencyB circB;

    @Autowired
    public CircularDependencyA(@Lazy CircularDependencyB circB) {
        this.circB = circB;
    }
}
```
- **Use Setter/Field Injection**
Spring creates the beans, but the dependencies are not injected until they are needed in this way
Changing the default testing container
Tags: testing
Published: 2022-04-17 14:16:50

By default testing, the library will append your render to the body, for which it first will apply a div.

The format will result in something like this:

```html
<body>
  <div>
    <YourComponent />
  </div>
</body>
```

However, you might want to test for other scenarios in some cases.

I'll write two down that I have dealt with so far:

- Custom component wrappers (custom elements)
- HTML based emails (wrapped in table layout)

In those cases, we want to define another type of wrapper.

## Defining a new wrapping container

For example, let's take the [previous article](https://daily-dev-tips.com/posts/testing-library-and-react-context/). What if we want to render the `App` in a table?

This is the current test setup:

```js
const renderComponent = ({ username }) => {
  return render(
    <UserContextProvider user={username}>
      <App />
    </UserContextProvider>
  );
};

it('should show the login option', async () => {
  renderComponent('');
  expect(screen.queryByText('Please login')).toBeInTheDocument();
});
```

Nothing strange so far, when debugging this code it would give us a HTML output like:

```html
<body>
  <div>Please login</div>
</body>
```

Now let's see how we can add a `Table`.
For this to work, we have to pass an optional parameter to the render function called `container`.

```js
const renderComponent = ({ username }) => {
  const table = document.createElement('table');
  return render(
    <UserContextProvider user={username}>
      <App />
    </UserContextProvider>,
    {
      container: document.body.appendChild(table),
    }
  );
};
```

Running the above code would throw us an error, as we cannot directly append text nodes to a `table`.

But now, imagine the component we are testing is a `TableBody` component. It would make sense to test that inside a table.

The output would become:

```html
<table>
  <TableBodyComponent />
</table>
```

## Testing custom elements

In my case, I recently had to test a custom component wrapper. This was mainly due to injecting something specifically in the shadow DOM.

The process for this is very similar. However, we define our custom element as the new tag.

```js
const renderComponent = ({ username }) => {
  const customTag = document.createElement('custom-tag');

  return render(
    <UserContextProvider user={username}>
      <App />
    </UserContextProvider>,
    {
      container: document.body.appendChild(customTag),
    }
  );
};
```

The output will now be:

```html
<custom-tag> Please login </custom-tag>
```

Be aware most components won't need a different container, but there are these exceptions where this can make your life easier to define one.

### Thank you for reading, and let's connect!

Thank you for reading my blog. Feel free to subscribe to my email newsletter and connect on [Facebook](https://www.facebook.com/DailyDevTipsBlog) or [Twitter](https://twitter.com/DailyDevTips1)
React Native Shadow View. Write once, run anywhere.
Tags: reactnative, shadow, library
Published: 2022-04-17 14:06:17

I love React Native. There is possible to write code without thinking about which platform it will be run on. But it's not always possible to overcome OS-specific things. One of those things is Android shadows styling. Over 4 years working with React Native I've never received a design that takes into account the Android way to deal with shadows. It is always easy to apply those styles with iOS API, but not clear what to do on the Android side. 

I decided to take a look if there are any solutions done by the Android native developers community and found out [ShadowLayout](https://github.com/L-Briand/ShadowLayout). The nice simple library is written in Kotlin. 

![Screenshot of ShadowLayout library example](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/byqkwk0cno11pxk3gn0y.png)

I immediately thought, what if I can use the power of native modules and achieve the same shadow styles with one API for both iOS and Android. I tried and it works.

![Screenshots of my react native shadow view library with shadows example for android and ios](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/4vy66ew1do6b9c25xg2r.png)

Happy to share my [@dimaportenko/react-native-shadow-view](https://github.com/dimaportenko/react-native-shadow-view) library. Please let me know in the comments what you think about it.