teleren/devto huggingface dataset:
SQL 基礎 Part 04 -- docker-compose で立てたコンテナで DB サーバー立ち上げ時にテーブルを作る
Tags: sql, docker
Published: 2022-12-22 06:13:52


## why

前回の記事で、DB を Docker Compose で立ち上げて、ローカルから接続することができた。

しかし、それでは Database を作っただけで、中身のテーブルがない

なのでそれを作る処理をする

---

## docker-compose.yml で PSQL DB と USER を作って SQL を読み込めるようにする

Docker Compose のファイル

```yml
version: '3.2'                                                                                                                                                

services:
  #
  # PostgreSQL
  #
  person-db:
    image: postgres:14-bullseye
    container_name: person-db
    ports:
      - 5444:5432
    volumes:
      - ./postgresql/init:/docker-entrypoint-initdb.d
    environment:
      POSTGRES_USER: kaede
      POSTGRES_PASSWORD: pass
      POSTGRES_DB: person
      POSTGRES_INIT_DB_ARGS: --encoding=UTF-8
    restart: always

```

* 最初に読み込む SQL ファイルの場所を指定
* ルートユーザーとルートユーザーのパスワードを作成
* DB を作成

ここまで動く。

```php
docker-compose up

person-db    | server started
person-db    | CREATE DATABASE
person-db    | 
person-db    | 
person-db    | /usr/local/bin/docker-entrypoint.sh: running /docker-entrypoint-initdb.d/00-init.sql
```

これで 

```yml
    volumes:
      - ./postgresql/init:/docker-entrypoint-initdb.d
```

これは volumes で
ローカルの `./postgresql/init/` の中身を
Docker の /docker-entrypoint-initdb.d が実行されるときの読み込み先に指定している。

これによって `./postgresql/init/` の .sql ファイルが
Docker Compose up 時にファイル名順に実行されるようになる。

---

## 00-init.sql で USER に権限をつけて、person DB に行って、person テーブルを作ってレコードを追加する。

SQL で CREATE DB とか CREATE USER は書く必要はない。
docker-compose.yml の environment の
POSTGRES_{ DB, USER, PASS } で作成できるから。

ルートユーザー以外も作りたい場合は必要。

```SQL
GRANT ALL PRIVILEGES ON DATABASE person TO kaede;

\c person

create table person(
  id int not null,
  name text,
  age int 
);
insert into person values (1,'Taro', 5); 
insert into person values (2,'Hana', 3); 
```

* kaede というユーザーに personDB の全権を渡す
* person DB に移動
* テーブル作成
* テーブルの初期データ挿入 (SQL では string を "" で書くとエラーになるので注意)

こうして、docker compose 起動後に読み込まれる SQL にこれを書くことで

```php
person-db    | /usr/local/bin/docker-entrypoint.sh: running /docker-entrypoint-initdb.d/00-init.sql
person-db    | GRANT
person-db    | You are now connected to database "person" as user "kaede".
person-db    | CREATE TABLE
person-db    | INSERT 0 1
person-db    | INSERT 0 1
```

こうやって docker で動いてログがでて

```sql
person=# \dt
        List of relations
 Schema |  Name  | Type  | Owner 
--------+--------+-------+-------
 public | person | table | kaede
```

テーブルが作成されて


```sql
person=# select * from person;
 id | name | age 
----+------+-----
  1 | Taro |   5
  2 | Hana |   3
(2 rows)
```

データが入る。

---

## 初期実行 SQL 変更時の注意点

docker-compose up
のあと、初期実行 SQL を変更したら
docker-compose down -v する必要が有る。

Docker コンテナを止めても Docker 内部の Volumes に DB は残るので
SQL ファイルを書き直しても DB は更新されない。
なので Volumes を破棄する必要が有る。

docker-compose kill containerName で
毎回コンテナごと破棄するのも有り。

だが、なかのボリュームだけ破棄するのがベターなので
--volumes でボリュームを落とす。
Flutter MCQ Questions
Tags: flutter, fluttermcq, flutterinterview, interivewquestions
Published: 2022-12-22 05:49:23

Practice here the most popular [Flutter MCQ Questions](https://www.onlineinterviewquestions.com/flutter-mcq/), are very popular and written by Industry Experts. 

![Flutter MCQ Questions](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/39ko4yafobu958quxm93.png)

What is Flutter?
 

-  It is DBMS toolkit
-  **It is an Open-source UI toolkit**
-  It is an Open-source web development framework
-  None of the above

Does flutter support desktop application development?

-  **Yes**
-  No

Which of the following widget is used for repeating content in Flutter?
 

-  **ListView**
-  ArrayView
-  ExpandedView
-  None of the above

Flutter's rendering engine is primarily written in which programming language?
 

-  Java
-  **C++**
-  Google Dart
-  C#
 
Flutter is developed by ....................
 **Google**
 Meta
 Microsoft
 Twitter

Which of the following language is used to build flutter app?
 

-  Go
-  Java
-  **Dart**
-  React

Flutter have mainly ........ 2 types of widgets.
 

-  **Two**
-  Three
-  Four
-  Five

A sequence of asynchronous events is often referred to as a stream.
 

-  **True**
-  False

Which element is used as an identifier in Flutter?
 

-  Serial
-  Widgets
-  **Keys**
-  All of the above

.............. component allow us to specify the distance between widgets on the screen.
 

-  Table
-  AppBar
-  **SizedBox**
-  safe area

What are the features of Flutter?
 

-  Fast development
-  Huge widget catalog
-  High-performance application
-  **All of the above**

Everything is a widget in Flutter. True or False?
 

-  **True**
-  False

Unlike other programming languages Dart doesn’t support ...............
 

-  classes
-  **interfaces**
-  arrays
-  object-oriented

Which of the following option is used to represent a collection of objects in Dart?
 

- String
-  Numbers
-  Booleans
-  **Lists and Maps**

Which of the following is used to load images from the flutter project’s assets?
 

-  Image
-  Image.file
-  **Image.asset**
-  Image.memory

The most important properties of the Image widget are ...........
 

-  width, double
-  height, double
-  image, ImageProvider
-  **all of the above**

What does SDK stands for?
 

- Software Data Kit
-  Software Database Kit
-  **Software Development Kit**
-  None of the above

Choose the best editors for Flutter app development.
 

-  VS Code
-  Sublime Text
-  Android Studio
-  **All of the above**

What are the type of tests, that we can perform in flutter?
 
-  Unit test
-  Widget test
-  Integration test
-  **All of the above**

Which of the following animation allows us to represent real-world behavior in Flutter?
 

-  Math-based
-  Graph-based
-  **Physics-based**
-  None of these

Thanks for Reading here. also practice [Flutter Interview Questions and Answers](https://www.onlineinterviewquestions.com/flutter-interview-questions/).
I wrote 1000 articles, what’s next?
Tags: webdev, beginners, watercooler
Published: 2022-12-22 05:46:40

Most of you know me for my consistency, a golden arrow in my blog series.

I've written 1000 articles in 1008 days!
Almost an article a day, and my honeymoon was the only holiday I ever took.

I'm super proud of this achievement; it has been a fantastic journey.

But what's next?

And it took me a while to think about that.
Do I want to continue writing daily? Do I want to try out other things? What is the next big thing?

And before answering that, I need to open up about the fact that writing daily is super unique, and I loved it, but it was also quite draining towards the 1000th article.

And then something magical and exciting changed my whole thinking about everything.

We got pregnant!
So amazing, and I'm ready to become a dad.

![Baby Bongers on the way](https://cdn.hashnode.com/res/hashnode/image/upload/v1671605496310/oFFC1-_o9.jpg)

## What to expect

So alright, what to expect from me in the future?
I will never stop creating content as I enjoy it so much, but I decided to move away from daily content.

There are a couple of aspects I want to try to find the next best thing:

- Youtube videos
- Long-form articles
- Ebooks

Between those, I'll dedicate more time per content piece and might even go deeper into some of the ones I already created.

Besides that, I have a few hobby projects and ideas I want to execute, so keep an eye out for those.

## What about the site?

Well, I might drop an article irregularly as I see fit, but the truth is, I'm planning on selling the website.

It's been my baby for almost three years, and it has matured a lot to a point where I'd love to see someone take it over and keep providing unique content for new developers.

If that person is you, please do get in touch 🙏.

## Some numbers

Many of you probably came here to see some numbers, right?
What do 1000 articles represent?

And here are some of them:

- 528704 words
- 1920 newsletter subscribers
- 160K+ page views every month
- 110+ #1 ranked google queries
- an average of 100K impressions daily
- 5K clicks on search terms alone
- And so much more

I couldn't be happier.
In the beginning, I'd never thought that would even be possible, yet I achieved it.

And that's not because of my writing, but because of all you amazing people motivating me and reading the articles.

So from the bottom of my heart:

Thank you for joining me on this journey.

### 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)
One To One Relationship Laravel 9 Example
Tags: laravel, laravel9, relationship, webdev
Published: 2022-12-22 05:30:00

In this article, we will see one to one relationship in laravel 9 example. 

A one-to-one relationship is a very basic type of database relationship. You have one table with a primary key that references the id of the other table. 

For one to one relationships use hasOne and belongsTo the method in the model for access to each other model. 

Also, you can use one to one relationship in laravel 6 and laravel 7, and laravel 8.

So, let's see the laravel 9 one to one relationship, laravel 9 eloquent relationships example.

We will create a User and Phone table. User model might be associated with one Phone model. To define this relationship, we will place a phone method on the User model. The phone method should call the hasOne method and return its result.
Position-relative and absolute
Tags: position, relative, absolute, static
Published: 2022-12-22 04:50:14

**1.Relative**
  When your are using position relative it relative to itself means relative will try to position itself according to it's current position.

![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/w43aaie5k5mo56ldau9f.png)
So above image shows that suppose you have given a green box container **position:relative top:20px** this green box will moves it's current position.

**2.Absolute**
  When you are using position absolute it will try to look first it's ancestor(parent) if we have defined the **position relative** over there(parent),so it position according to its ancestor.otherwise it will position according your browser or other dimensions.

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

Above images when u do green box **position:absolute left:20px** and in black container you have defined a **position:relative** so the green box will move its parent position or we can say its ancestor if parent doesn't defined position relative . then it will look browser dimensions.

ThankYou!😃
Keep learning new things.
Setting up Apache Virtual Hosts on an Ubuntu Server
Tags: apache, webdev, virtualhost, ubuntu
Published: 2022-12-22 04:35:54

Virtual hosts allow you to host multiple websites on a single server. This can be useful if you want to host multiple websites on a single instance, or if you want to run multiple versions of a website (e.g. staging and production).

In this tutorial, we'll go through the steps of setting up Apache virtual hosts on an Ubuntu server.

## 1. Install Apache:

First, make sure that Apache is installed on your server. If it's not already installed, you can install it with the following command:

```
sudo apt-get install apache2
```

## 2. Enable Apache's virtual host module:

Next, we need to enable Apache's virtual host module. This can be done with the following command:

```
sudo a2enmod vhost_alias
```

## 3. Create a new virtual host file:

Next, we'll create a new virtual host file for each website that we want to host. These files can be placed in the /etc/apache2/sites-available directory.

To create a new virtual host file, copy the default virtual host file and modify it to suit your needs. For example:

```
sudo cp /etc/apache2/sites-available/000-default.conf /etc/apache2/sites-available/example.com.conf
```

Then, open the new virtual host file in a text editor and modify it to specify the document root (i.e. the directory containing the website's files) and the server name:

```
<VirtualHost *:80>
  ServerName example.com
  ServerAlias www.example.com
  DocumentRoot /var/www/example.com/public_html
  <Directory /var/www/example.com/public_html>
    AllowOverride All
  </Directory>
</VirtualHost>
```
Be sure to replace example.com with the actual domain name of your website.

## 4. Enable the new virtual host:

To enable the new virtual host, use the following command:

```
sudo a2ensite example.com.conf
```

## 5. Restart Apache:

Finally, restart Apache to apply the changes:

```
sudo systemctl restart apache2
```

That's it! You should now be able to access your website at the specified domain name.
GitHub Actions for Python Development
Tags: python, github, devops, webdev
Published: 2022-12-22 04:25:23

If you are developing your application on GitHub, then you might want to consider using GitHub Actions for your CI/CD. In this tutorial we will cover how to use GitHub actions for testing multiple version of python and on different platforms.

Our example will include a FastAPI application, using pytest to run our tests, pylint for linting check, on python versions (3.8, 3.9, 3.10, 3.11) with (Windows, Mac, Linux) platforms. You can find this example on GitHub [here](https://github.com/WMRamadan/fastapi-boilerplate).

First thing you will notice is under the `.github/workflows` directory there is a file named `python-app.yml` which is the YAML file that will be used for our GitHub Actions Pipeline.

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

In this file you will find the below break-down. 

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

You will see that the key `runs-on` uses the variable `matrix.os` which has the array of operating systems to use. While the key `python-versions` uses the variable `matrix.python-version` that takes the array of python versions.

```
    runs-on: ${{ matrix.os }}
    strategy:
      matrix:
        os: [ubuntu-latest, windows-latest, macos-latest]
        python-version: ["3.8", "3.9", "3.10", "3.11"]
```

Underneath you will see multiple keys named `run` each for installing dependencies, linting and testing.

```
    - name: Install dependencies
      run: |
        python -m pip install --upgrade pip
        pip install -r requirements.txt
    - name: Lint with pylint
      run: |
        pylint --recursive=y api --rcfile=.pylintrc
    - name: Test with pytest
      run: |
        pytest api/
```

Every time you push a change to your repository this action will run.

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

To learn more about Python automation and testing using GitHub Actions you can visit this [link](https://docs.github.com/en/actions/automating-builds-and-tests/building-and-testing-python).
Get Public IP Address using Golang and Ipify library
Tags: go, beginners, tutorial, programming
Published: 2022-12-22 04:11:28

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

**go playgrond**
https://go.dev/play/p/fSXBVH3O8cC
Método Kanban e Qualidade de Produto de Software
Tags: kanban, cienciadacomputacao, ifprcampuspinhais, qualidadedesoftware
Published: 2022-12-22 03:28:14

**Elaborar um texto individual baseado em 3 referências (artigos, livros, textos) sobre o método Kanban e qualidade de produto de software. Postar na comunidade dev.to, disponível em: https://dev.to/.**

**Artigos Analisados:**

JUNIOR. _Kanban no Desenvolvimento de Software: Origem e Conceitos._ EZ.Devs: 2019. Disponível em: https://ezdevs.com.br/kanban-desenvolvimento-de-software/. Acessado em: 21/12/2022.
DANTAS, André; JUNIOR, Gibeon. _Kanban no projeto SIGAA: Uma experiência bem-sucedida de melhoria da eficiência e qualidade do trabalho do Time._ SINFO - UFRN: 2016. Disponível em: https://wp-sites.info.ufrn.br/admin/wp-content/uploads/sites/2/2020/04/Artigo-WTICIFES-2016.pdf. Acessado em: 21/12/2022.
FARIA, Vanderlei; CARDOSO, Álvaro; CHAVES, Carlos. _Implantação do Kanban na linha de montagem de sistema e equipamentos Hidráulicos e Eletromecânicos._ XIII SIMPEP: 2006. Disponível em: https://simpep.feb.unesp.br/anais/anais_13/artigos/542.pdf. Acessado em: 21/12/2022.

A metodologia Kanban, oriunda do sistema de produção da Toyota que durante a crise do petróleo no mundo árabe, na década de 70, precisou se reinventar para tornar-se mais produtiva e consequentemente mais competitiva, chegou ao universo de desenvolvimento de softwares. David Anderson foi o pioneiro a introduzir o novo método na Corbis, de propriedade de Bill Gates. Os dois principais focos da metodologia são os trabalhadores da fábrica (o time de desenvolvimento) e a clareza de visão do andamento de todo o projeto, de forma clara e atualizada.
Muitas vezes na equipe de desenvolvedores não se tem uma visão clara de tudo que engloba o projeto, das atividades que precisam ser executadas e das que já foram concluídas. Um dos lemas da metodologia Kanban é pare de começar e comece a terminar. A otimização de todo o processo de desenvolvimento levando em consideração a qualidade esperada no desenvolvimento e entrega do software reflete nos números de desempenho das equipes e na satisfação do usuário que recebe as entregas.

Aluno: Rafael Oliveira Pereira
Engenharia de Software I
Profª Me. Lauriana Paludo
Bacharelado em Ciência da Computação
IFPR Campus Pinhais
O que é e para o que serve CRUD?
Tags: node
Published: 2022-12-22 03:08:25

CRUD nada mais é que um acrônimo em que cada letra representa as operações básicas de um banco de dados.

C de Create:
Create ou criar é a representação de adicionar dados a um banco.
O método post deve ser utilizado para esses casos.

R de Read:
Read ou ler é a representação da busca e apresentação de algum conjunto de dados que já foram armazenados no banco de dados.
O método get deve ser utilizado para esses casos.

U de Update: 
Update ou atualização é a representação de atualizar um conjunto de informações com novos dados.
Os metodos put ou patch devem ser utilizados para esses casos. 

D de Delete: 
Delete ou detetar é a representação de excluir, ou remover um conjunto de informações que estão no banco.
O método delete deve ser utilizado para esses casos.

Essas são as quatro principais operações de um banco de dados.


![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/zlfqttluscupsmr2rhwn.jpeg)
Git Как изменить любой коммит
Tags: git
Published: 2022-12-22 03:05:53

Для того, чтобы изменить любой коммит, нужно использовать команду `git rebase`. Важно, что при этом все изменения, которые планируется внести в коммит должны быть скрыты командой `stash`, то есть вывод команды `git status` должен быть пустой:
1.Допустим в области изменений git есть какие-то файлы, которые мы хотим добавить к коммиту командой `git rebase`, и есть файлы, которые добавлять не планируется.
В таком случае нужно скрыть изменения поочерёдно командой `git stash push [относительный путь к файлу]`.
Показать список скрытых файлов можно командой `git stash list`.
Команда `git stash` сохраняет записи по методу стэка, то есть последние добавленные записи имеют меньший индекс, а самая последняя добавленная запись имеет индекс 0.
Хорошая статья про команду `git stash` [https://tangenttechnologies.ca/blog/git-stash-single-file/](https://tangenttechnologies.ca/blog/git-stash-single-file/)
2.Выполнить команду
`git rebase —interactive [номер коммита^]`
обратить внимание на символ ^ - это означает, что мы перемещаемся в состояние «до» этого коммита
3.В открывшемся файле или консольном текстовом редакторе (в зависимости от того, какой редактор настроен для работой с git) с коммитами указать, какой коммит мы хотим изменить — вместо `pick` написать `edit`
4.Выполнить изменения, например добавить файлы к коммиту. Если изменения находятся в состоянии stash, выполнить команду
`git stash pop`
или
`git stash pop [номер изменения]`
5.Выполнить команду
`git commit —amend`
6.Выполнить команду
`git rebase —continue`
7.При необходимости перезаписать изменения на сервере командой
`git push --force`
React Libraries 2022
Tags: react, libraries
Published: 2022-12-22 03:04:35

This is a complementary post based on: [React Libraries for 2022](https://www.robinwieruch.de/react-libraries/)

Here you can find a list of most used and recommendations for React Libraries on 2022.



![React Libraries 2022](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/5l4t8tcgwhc7hx5n4jb9.png)
Schema hasn't been registered for model \"UserAddress.Address\".\nUse mongoose.model(name, schema)
Tags: mongodb
Published: 2022-12-22 02:57:16

```const addressSchema = new Schema({
  name: {
    type: String,
    required: true,
  },
  phone: {
    type: String,
    required: true,
  },
  address: {
    type: String,
    required: true,
  },
  city: {
    type: String,
    required: true,
  },
  district: {
    type: String,
    required: true,
  },
  state: {
    type: String,
    required: true,
  },
});

```

```
const userAddressSchema = new Schema(
  {
    user: {
      type: mongoose.Schema.Types.ObjectId,
      ref: "User",
      required: true,
    },
    address: [addressSchema],
  },
  { timestamps: true }
);
```

```
const orderSchema = new Schema(
  {
    user: {
      type: mongoose.Schema.Types.ObjectId,
      ref: "User",
      required: true,
    },
    addressId: {
      type: mongoose.Schema.Types.ObjectId,
      ref: "UserAddress.Address",
      required: true,
    }
 }
)
```
how can I return the AddressId field populated with values instead of just an ID. Please help me
Suppress Mixed-operators warning
Tags: react
Published: 2022-12-22 02:43:12

Our dev console has several of these warnings.

> Unexpected mix of '&&' and '||'. Use parentheses to clarify the intended order of operations  no-mixed-operators

We understand that some developers feel this way, but our development team strongly believes that operator precedence should be understood and that overuse of parentheses adds unnecessary syntax and reduces readability.

We do not want to turn off all warnings however, as most are helpful. We would love to see an option to disable this opinionated warning. Thanks!
SPVM 0.9670 is released
Tags: perl, spvm, programming, beginners
Published: 2022-12-22 01:20:04

<a href="https://metacpan.org/pod/SPVM">SPVM</a> 0.9670 is released.

## New Features and Enhancement

<a href="https://github.com/yuki-kimoto/SPVM/blob/master/Changes">Changes</a>

```
0.9670 2022-12-22
  [New Features]
    * Added the following Native APIs.
    
      const char* (*strerror_nolen)(SPVM_ENV* env, SPVM_VALUE* stack, int32_t errno_value);
      void* (*strerror_string_nolen)(SPVM_ENV* env, SPVM_VALUE* stack, int32_t errno_value);

  [Bug Fix]
    * Fixed the bug that the length of the return vlaue of the strerror_string Native API was wrong.
  [Test Fix]
    * Fixed the testging bug that the tests of the strerror and strerror_string Native APIs don't work.
```

## For Programming Beginners

### What Is SPVM?

SPVM is a static typed programming language that can be installed from Perl/CPAN.

### How potential dose SPVM have?

Growth is expected in the fields of Bio Tech, AI/ML, Apple/iPhone/iPad Apps, Google/Android Apps, IoT Device, Connected Car, Smart Device, Smart Home, etc.

This is because SPVM can produce an executable file that supports cross platforms and make easy to calculate arrays and bind C/C++