teleren/devto huggingface dataset:
How to setup Font Awesome 5 as VueComponent in Nuxt.js
Tags: vue, nuxt, webdev, tips
Published: 2018-01-06 16:21:53

---
title: How to setup Font Awesome 5 as VueComponent in Nuxt.js
published: true
description: How to setup FontAwesome 5 as VueComponent in Nuxt.js
tags: #vue #nuxtjs #webdev #tips
---

There were a couple of things that I needed to understand in Nuxt.js so hopefully this will make it quicker for other people as well

1. To have a global component in Nuxt, just create a plugin. Even if the documentation isn't very clear on setting that up it works well if you look around the Github issue list

2. [Font Awesome 5's VueJS integration works well](https://github.com/FortAwesome/vue-fontawesome), but you need to keep in mind to install the icon categories.

3. __Update: It got fixed in 1.1.3__ ~~Currently there's an issue with[Fontawesome 5 SSR](https://github.com/FortAwesome/Font-Awesome/issues/11984), follow toadkicker's advice and go back a version.~~ {% github https://github.com/FortAwesome/Font-Awesome/issues/11984 %} 

That being said let's create a plugin, I've called it `font-awesome.js`
```js
import Vue from 'vue'
// the component
import FontAwesomeIcon from '@fortawesome/vue-fontawesome'
// the library
import fontawesome from '@fortawesome/fontawesome'
// add more icon categories as you want them, even works with pro packs
import brands from '@fortawesome/fontawesome-free-brands'

// asociate it to the library, if you need to add more you can separate them by a comma
fontawesome.library.add(brands)
Vue.component(FontAwesomeIcon.name, FontAwesomeIcon)
```

Now we just need to add the plugin in `nuxt.config.js`
```js
module.exports = { 
  ...

  plugins: [
    ...
    { src: '~/plugins/font-awesome' }
  ]
}

```
And this allows us to use the component in our page
```html
<font-awesome-icon :icon="['fab', 'linkedin']" />
```
Arch Linux: Stop recommending people to use makepkg for the AUR
Tags: archlinux, aur
Published: 2018-01-06 11:22:13

---
title: "Arch Linux: Stop recommending people to use makepkg for the AUR"
published: true
description: Look at me I'm so good I know how to git clone a repository
tags: arch linux, aur
---

*This is relevant to Arch Linux and the Arch User Repository. If you don't know what that is, no need to read this article.*

Alright, there seems to be around 3 kinds of people:
 1. "Pacman should be like apt"
 2. "You probably want an AUR helper"
 3. "Real men use makepkg"

2/3 of these people know that adding a custom repository to get a program is HORRIBLE security-wise. That's not worth mentioning.
I will instead be focusing on eliminating the 3rd kind, leaving us with the second (which I'm a part of).

Let me tell you a tale of how I got used to the AUR.
Immediately when I started off, I wanted to be the 3rd kind. I wanted to use only the official tools. "Real men don't need no helper" or whatever. I scanned the wiki on my phone (Arch wasn't completely set up yet), and found out how to install packages. I failed to find out how to update them, so I assumed pacman did that for you. I started cloning all packages to ~/Downloads, building them, and deleting them.
That was my first pitfall. Already, I had made a mistake. I needed to keep them updated. Alright, that's simple enough. I re-downloaded all my packages (TIP: pacman -Qm) to ~/AUR. Then I made a bash script to git pull all the things, and building them if there was anything to update (NOTE: I hadn't thought of -git packages).
This is what I used for a while. And it worked, except it required a lot of interaction. I had to copy the URL, cd, git clone, cd, makepkg. I started avoiding the AUR as much as I could. Alright, simple fix: Just make a bash script to download it? No. This is where I stopped. And I'll tell you why in a second.
But first I want to inject that I never checked any other files than the PKGBUILDs. I never read the wiki carefully enough, so I failed to realize that ALL files could contain viruses. If I had used a helper, this risk would have been avoided all together.

I saved my most important point to last. If you make shell scripts around the manual way of doing it, are you really still using the manual way...
*...or have you created a helper?*
LogicApp Template Creator
Tags: azuredevops, serverless, logicapps, azure
Published: 2019-09-09 10:23:47

---
title: LogicApp Template Creator
published: true
tags: AzureDevOps,Serverless,logicapps,Azure
canonical_url: https://peterrombouts.nl/2018/01/06/logicapp-template-creator/
---

When trying to put your LogicApp code in a CICD pipeline, it is always problematic getting your code into a proper template.  
Obviously switching to ‘LogicApp Code View’ is an option, but there is a better solution to this problem.

[LogicAppTemplate](https://www.powershellgallery.com/packages/LogicAppTemplate/1.0.10) is a PowerShell commandlet that makes is very easy to get the content (even automatically) of the app and save it to disk.

The usage is very simple, open up a PowerShell window and execute the next command:  
[Check out this gist](https://gist.github.com/prombouts/73ce2c5eeb8c7ca2db516223ad311732)

Big thanks to [Jeff Hollan](https://twitter.com/jeffhollan) who authored this!
Cryptocurrency Mining
Tags: cryptocurrency, bitcoin, script, discuss
Published: 2018-01-06 08:42:24


---
title: Cryptocurrency Mining
published: true
description: Help needed how to start with cryptocurrency mining 
tags: #cryptocurrency #bitcoin #script #discuss
image: https://thepracticaldev.s3.amazonaws.com/i/7zo9zscnw71p0z6zupva.jpeg
---

Hello people,

I am planning to start Cryptocurrency Mining as a hobby.
But first I need some tips how to stars and some useful sources, like digital wallets, other miners, etc etc. Some useful scripts maybe!

Any help will be appreciated! 

Thank you so much!!
If you could write a programming language how would it be?
Tags: discuss
Published: 2018-01-06 05:11:28

---
title: If you could write a programming language how would it be?
published: true
description: currently there are a lot of programming language with very different features, some are faster and hard to use, some are powerful but it take too much typing to write a simple command. How would it be your perfect programming language? would it be interpreted or compiled? What about the paradigm? What would you do and why would you do it? Let us know it here!
tags: #discuss
---
Spectre & Meltdown: How does this affect mobile apps?
Tags: discuss, security, spectre, meltdown
Published: 2018-01-06 01:49:44

---
title: "Spectre & Meltdown: How does this affect mobile apps?"
published: true
tags: discuss, security, spectre, meltdown
---

I'll be honest, I live in a bit of a Web bubble. While I dabble in other languages, JavaScript is by far what I spend the majority of my time researching. And through that I've read how because of Spectre and Meltdown certain features in web browsers (Chrome, Firefox, Edge, and Safari) are all disabling SharedArrayBuffers (while allow for sharing memory between threads in a web page) as well as making the readings from performance metrics temporarily less specific.

On top of that, Windows, Linux, and macOS have all worked on OS level patches in the mean time.

So I thought I'd ask about Android or iOS since I've seen ARM is affected too.
入門自然言語処理 pp.48-111
Tags: python, nlp, reading
Published: 2018-01-05 23:50:56

---
title: 入門自然言語処理 pp.48-111
published: true
description: 
tags: python, nlp, reading
---

第2章は語彙資源。コーパスに入っている、構造化された単語データの説明が書かれている。単純な辞書データからはじまり、意味が階層化された WordNet の説明など。なんとなく流し読みしたけど、これあとで、読み返すことになるだろう。
Coding Livestreams
Tags: discuss
Published: 2018-01-05 19:43:21

---
title: Coding Livestreams
published: true
tags: #discuss
cover_image: https://www.believemusic.com/wp-content/uploads/2017/05/live.jpg
---

I _really_ enjoy watching live demos during keynotes and talks, but I hardly even know any coding live streamers.

## Which are your favorite coding livestreams?
Upload de SVG com Image Magick + AWS
Tags: rails, aws, imagemagick, desenvolvimento
Published: 2019-10-08 23:45:04

---
title: Upload de SVG com Image Magick + AWS
published: true
date: 2018-01-05 17:57:47 UTC
tags: rails,aws,imagemagick,desenvolvimento
canonical_url: https://medium.com/@debborafernandess/realizando-upload-e-convers%C3%A3o-de-svg-com-image-magick-7af4dbea8135
---

![](https://cdn-images-1.medium.com/max/500/1*iiBd1DD7NaAkjL9cOCgYaQ.png)

Esse foi mais um dia daqueles _“Na minha máquina funciona”_, onde o upload de arquivos funcionava perfeitamente no ambiente de DEV e no ambiente de produção antigo, mas quebrava na nova instância que estavamos homologando na AWS.   
Já imaginava que tinha o ImageMagick instalado em produção, mas como o upload de imagens não acontecia:

```
convert -background none some\_image.svg some\_image.jpg 
convert: not authorized `some\_image.svg’ @ error/constitute.c/ReadImage/454.
convert: no images defined `some\_image.jpg’ @ error/convert.c/ConvertImageCommand/3046.
```

> #whathell

Desconfiei que talvez a versão estivesse desatualizada…

```
$ convert -version

Version: ImageMagick 6.7.8–9 2016–06–22 Q16 http://www.imagemagick.org
Copyright: Copyright © 1999–2012 ImageMagick Studio LLC
Features: OpenMP
```

> Okay, tinha a versão atualizada!   
> 😏 até janeiro de 2018 ao menos

Aí começou aquele trabalho de formiguinha, para entender um pouco melhor como funciona o ImageMagick.

O ImageMagick tem entre outros helpers, o comando convert -list delegate, que exibe o comando que é executado para cada tipo de manipulação de imagem. A conversão de SVG usa por baixo dos panos o comando rsvg-convert-o "%o" "%i".   
Como esse comando não era reconhecido no SO do server, foi fácil de ver que era necessário instalar essa **_lib e suas dependências_**.   
Se tornou mais fácil, pq contamos com a ajuda do @tavinus que publicou esse gist [install-gm-w-librvg.sh](https://gist.github.com/tavinus/2265625d3e323737211e). 😃

Legal né? Mas após tudo isso, ainda não conseguia fazer a conversão de arquivos _svg_ para _png_…

![](https://cdn-images-1.medium.com/max/748/1*PHzmIie9PDr1RrYI6KtlFA.jpeg)<figcaption>Não foi =/ #dammit!</figcaption>

Pesquisando um pouco mais, vi que alguns tipos de arquivos .svg, .txt, etc e algumas fontes ( como imagens vindas da web ) tem upload blockeada por padrão na configuração de policies do ImageMagick, que geralmente fica em /etc/ImageMagick/policy.xml e podem ser vistas nos rightsdo comando convert -list policy

A solução então era alterar esses direitos para esse tipo de arquivo na linha:

```
\<policy domain=”coder” rights=”none” pattern=”MVG” /\>
```

E finalmente, após instalar a lib necessária para conversão de SVG e ajustar a regra para esse tipo de arquivo, meu upload finalmente funcionou!
Should we wrap critical built-in modules?
Tags: discuss, bestpractices
Published: 2018-01-05 17:52:28

---
title: Should we wrap critical built-in modules?
published: true
description: 
tags: discuss, best-practices
---

I've spent the last two weeks migrating one project from Angular's deprecated `Http` module to the new (more elegant) `HttpClient`. *Two weeks* -- in my opinion that's way too much maintenance time on a single layer of the app. I encountered something similar in the fall with Angular Material.

Which brings me to the question: **should we wrap critical built-in modules to avoid this kind of massive overhaul?**

While Uncle Bob suggests that we should avoid concrete dependencies where possible, you'd think that concrete dependencies on the framework itself would be okay. But this `HttpClient` debacle is proving otherwise.

Additional follow-up question: **If / when we should put our own interface around critical modules, how do we define "critical?" What sort of modules warrant this kind of architecture?**
Binary Search: Code and complexity
Tags: video, coding, algorithms, leaf
Published: 2018-01-05 15:36:58

---
title: "Binary Search: Code and complexity"
published: true
description: Showing how a binary search works and analysing it.
tags: video, coding, algorithms, leaf
---

{% youtube lORaWyzGN5M %}

I write a binary search algorithm in Leaf and give a few visual descriptions of how it works. I get a bit into the distinction between big-O and big-Theta notation

Watch my streams live on [Twitch - Mortoray](https://www.twitch.tv/mortoray)
[Discussion] Time Tracking App
Tags: timetracking
Published: 2018-01-05 13:29:30

---
title: "[Discussion] Time Tracking App"
published: true
description: Looking for suggestion
tags: time tracking
---

Hi everyone

Recently I have been involved in more than 2 projects and I am having difficult time in tracking time spent on the projects. I tried Tsheets.com but it seems that it is only possible to track one time (not on basis of projects). I would also like to use similar apps in my team. I am looking for your suggestions and your review of the apps you are using for project based time tracking app.
20 Lines Simple Store with RxJS 
Tags: typescript, rxjs
Published: 2018-01-05 12:34:43

---
title: 20 Lines Simple Store with RxJS 
published: true
description: 
tags: ["TypeScript", "RxJS"]
---

```ts
import { distinctUntilChanged, map } from 'rxjs/operators';
import { BehaviorSubject } from 'rxjs/BehaviorSubject';

export abstract class Store<T> extends BehaviorSubject<T> {
  constructor(initialState: T) {
    super(initialState);
  }

  public dispatch(fn: (state: T) => T) {
    this.next(fn(this.getValue()));
  }

  public select<R>(fn: (state: T) => R) {
    return this.pipe(map<T, R>(fn), distinctUntilChanged());
  }

  public selectSync<R>(fn: (state: T) => R) {
    return fn(this.getValue());
  }
}
```

Example: UserStore

```ts
import { User } from '../entity/user';
import { Store } from '../../store';

export interface State {
  currentUser: User | null;
}

export class UserStore extends Store<State> {
  constructor() {
    super({
      currentUser: null,
    });
  }

  get currentUser$() {
    return this.select(state => state.currentUser);
  }
  get currentUser() {
    return this.selectSync(state => state.currentUser);
  }

  setCurrentUser(user: User) {
    this.dispatch(state => ({
      ...state,
      currentUser: user,
    }));
  }
}
```
Udemyの「【UE4】Unreal Engine 4 + VR で建築ビジュアライゼーション」でドアノブの処理を改善してみた
Tags: vr, ue4, unrealengine, unrealengine4
Published: 2018-01-05 11:54:00

---
title: Udemyの「【UE4】Unreal Engine 4 + VR で建築ビジュアライゼーション」でドアノブの処理を改善してみた
published: true
tags: VR, UE4, UnrealEngine, UnrealEngine4
date: 20180105T11:54Z
canonical_url: https://qiita.com/shiena/items/0f0315bf26e3a94b7387
---
# はじめに

[Udemy](https://www.udemy.com)で @shop_0761 さんの[【UE4】Unreal Engine 4 + VR で建築ビジュアライゼーション](https://www.udemy.com/unrealengine-4-archviz-vr/)をやってみて気になる挙動があったので改善してみました。

# 気になる部分

この講座ではVR内にドアを設置してコントローラーでドアノブを回すとドアを開けるようになります。

![image.png](https://dev-to-uploads.s3.amazonaws.com/i/p0laheo6kyk3i9kuxu4b.png)

ドアノブを掴むと`Pickup` イベントが呼ばれて手のオブジェクトとなる `Contoller` を非表示にします。
そしてドアノブを離すと `Drop` イベントが呼ばれて `Controller` を再表示しています。

この時に両手でドアノブを掴むと次のように先に握った手が消えたままになります。

1. 右手でドアノブを掴む
    * 右手が消える → OK
1. 左手でドアノブを掴む
    * 左手で掴み直して消える → OK
    * 右手も消えたまま → 掴んでない手は再表示したい

更にどちらの手から先に離してもおかしな事になります。

* 先に右手を離す
    1. 左手も離して再表示される → 左手は掴んだままにしたい
    1. 右手は消えたまま → 離した手は再表示したい
* 先に左手を離す
    1. 左手は再表示される → OK
    1. 右手は消えたまま → 掴んでいない手は再表示したい

これを後から掴んだ手がドアノブを掴み、先に掴んでいた手を再表示する。
また先に掴んでいた手を離しても何もしないといった改善をしてみます。

# ドアノブを掴む処理の改善

改善するに当たってまずは仕様を決めます。

1. 後から掴んだ手がドアノブを掴む
1. 先に掴んでいた手を再表示する
1. 先に掴んでいた手を離しても何もしない

最初の項目は実現できているので残り2つを改善したのがピンクの線で囲んだ部分です。
![image.png](https://dev-to-uploads.s3.amazonaws.com/i/3s2wbin4kgpdp9l4fffz.png)


## 先に掴んでいた手を再表示する

`Pickup` イベントが呼ばれた時に既に掴んでいるか判定できればよいので `Controller` が有効かどうかで分岐します。

* `Drop` イベントで `Set Visibility` の後に `Controller` を破棄する
* `Pickup` イベントで `Attach To` を `Controller` に代入する前に `IsValid` 関数の結果が `Is Valid` なら `Set Visibility` で表示する

どちらかの手でドアノブを掴んでいれば `Controller` を有効、両手を離していれば `Controller` を無効にしているわけです。


## 先に掴んでいた手を離しても何もしない

`Drop` イベントが呼ばれた時にどっちの手を離したのか分からないのでちょっと詰まったのですが、VR Templateから持ってきたBPを改造して実現できました。

![image.png](https://dev-to-uploads.s3.amazonaws.com/i/e6cmkf0sb7yprhaazjop.png)

まずは `VirtualRealityBP/Blueprints/PickupActorInterface` の `Drop` のInputsに変数を追加します。
次に `VirtualRealityBP/Blueprints/BP_MotionController` の `ReleaseActor` グラフで `Drop` の引数 `DettachFrom` に `MotionController` をつなぎます。

これでドアの `Drop` イベントが呼ばれた時に離した手を取れるようになったので変数 `Contoller` と比較して同じなら後から掴んだ手なので処理を進める、違うなら先に掴んでいた手なので何もしない、として判定できるようになりました。

# さいごに

VR Templateを使うと簡単に掴み処理を実装できたり、改造も割と簡単にできるので導入におすすめです。
ここから更に両手で掴んだ時に拡大縮小したり色々発展できそうです。
Using React ErrorBoundary with HOCs
Tags: react, javascript
Published: 2018-01-05 09:44:48

---
title: Using React ErrorBoundary with HOCs
published: true
description: Using ErrorBoundary with HOCs
tags: React,JavaScript
---

```javascript
// withErrorBoundary.js

import React, { Component } from 'react'
import PropTypes from 'prop-types'

class ErrorBoundary extends Component {
  constructor(props) {
    super(props)
    this.state = { hasError: false }
  }

  componentDidCatch(error, info) {
    this.setState({ hasError: true })
    console.group('componentDidCatch')
    console.error(error)
    console.info(info)
    console.groupEnd('componentDidCatch')
  }

  render() {
    if (this.state.hasError) {
      return <h1>An Error Occurred 😢</h1>
    }
    return this.props.children
  }
}


export default Component => props => (
  <ErrorBoundary>
    <Component {...props} />
  </ErrorBoundary>
)
```

Easy to Use with ES7 decorator... `@withErrorBoundary`

```javascript
// App.js

import withErrorBoundary from './withErrorBoundary.js'

@withErrorBoundary
export default class App extends Component {

  simulateError = () => {
    throw new Error('Sample Error')
  }

  render() {
    return (
      <div>
        <h1 onClick={this.simulateError}>Hello World</h1>
      </div>
    )
  }
}
```
Elixirのコードレビューで出るやつ
Tags: elixir
Published: 2018-01-05 07:38:08

---
title: Elixirのコードレビューで出るやつ
published: true
description: 
tags: Elixir
---

[Elixir Advent Calendar 2016](http://qiita.com/advent-calendar/2016/elixir) の12日目です。

Elixir で開発していてコードレビューの指摘点で出たものについて、
一般的だと思うものをいくつか列挙しました。


## 返り値を想定している場合は _ でマッチさせず名前付ける

名前付けておいた方が読んだときにわかる。


## 関数定義でマッチできるならそっちで

```
def spam(x) do
  case x do
    :aaa ->
      :ok
    :bbb ->
      :error
  end
end
```

のようにやるなら、次のようにする。

```
def spam(:aaa) do
  :ok
end
def spam(:bbb) do
  :error
end
```


## if より case を使う

場合分けで if を使うことは多くない。
case を使う方が良い場合が多い。

```
user = Repo.get(query, id)
if user != nil do
  ...
else
  ...
end
```

と書くなら次のようにする。

```
case Repo.get(query, id) do
  nil ->
    ...
  user ->
    ...
end
```


## エラー返り値の形式が違うものは with でまとめず case ネストで

```
with {:ok, foo} <- spam(),
     {:ok, bar} <- ham() do
  ...
else
  :error ->
    ...
  {:error, reason} ->
    ...
end
```

のように spam() は :error、ham() は {:error, reason} を返すような場合、
with でまとめるとどれがどのエラー形式を返すかわからなくなってつらい。
ので普通に case ネストで書く。

```
case spam() do
  {:ok, foo} ->
    case ham() do
      {:ok, bar} ->
        ...
      {:error, reason} ->
        ...
    end
  :error ->
    ...
end
```



## 関数呼び出しはカッコ省略せず必ず () 付ける

統一するメリットがあるので。


## 再代入しない

再代入するなら基本的に別の名前を付ける。
Phoenix の conn のようなごく一部の例外は除く。
再代入の必要性は今のところ特に感じていない。


## %URI{} 使おう

```
url_base = "https://#{host}"
url = "#{url_base}/user/#{user_id}"
```

とかやるなら URI を使う。(HTTPoison など URI 型で渡せる)

```
url = %URI{scheme: "https",
           host: host,
           path: Path.join("/user", user_id)}
```

String にしたければ URI.to_string() を使えばよい。


## 条件を満たすならリストに追加する

List や Map を作るときに条件を満たす場合は追加することがある。
例えばこんな感じ。

```
@spec build_spams() :: list()
def build_spams() do
  spams = base_spams()
  spams = if condition1() do
    [additional1() | spams]
  else
    spams
  end
  spams = if condition2() do
    [additional2() | spams]
  else
    spams
  end
  spams
end
```

要素追加する部分を関数に切り出すと見通しがよくなる場合がある。
以下のような感じ。

```
@spec build_spams() :: list()
def build_spams() do
  base_spams()
  |> maybe_add_spams1()
  |> maybe_add_spams2()
end

defp maybe_add_spams1() do
  if condition1() do
    [additional1() | spams]
  else
    spams
  end
end

defp maybe_add_spams2() do
  if condition2() do
    [additional2() | spams]
  else
    spams
  end
end
```


## おまけ: credo

CI で mix credo は必ず回すようにしている。
.credo.exs は次の感じでやってる。

```.credo.exs
%{
  configs: [
    %{
      name: "default",
      files: %{
        included: ["lib/"],
        excluded: []
      },
      checks: [
        {Credo.Check.Readability.MaxLineLength, max_length: 120},
        {Credo.Check.Readability.ModuleDoc, false},
        {Credo.Check.Refactor.Nesting, false},
        {Credo.Check.Refactor.PipeChainStart, false},
      ]
    }
  ]
}
```
GCP API の認証設定
Tags: gcp
Published: 2018-01-05 07:30:47

---
title: GCP API の認証設定
published: true
description: 
tags: GCP
---


GCP (Google Cloud Platform) の API を使うための認証・認可は OAuth 2.0 で、
サーバーでの使い方は [Using OAuth 2.0 for Server to Server Applications](https://developers.google.com/identity/protocols/OAuth2ServiceAccount) に書かれている。
結論としては [Google Application Default Credentials (ADC)](https://developers.google.com/identity/protocols/application-default-credentials
) を使い、OAuth 2.0 Access Token を取得して使う。

ADC は AWS での Default Credential Provider Chain にあたる。


## ADC とは

次のロジックで得られる credentials が ADC と呼ばれる。

1. 環境変数 `GOOGLE_APPLICATION_CREDENTIALS` が指定されていたら、そのファイルを service account の credentials として読んで使う
2. `gcloud auth application-default login` を実行して well_known_file が作成済みであれば、それを authorized user の credentials として読んで使う
3. GAE (Google App Engine) 上で実行されていれば、その built-in service account を使う
4. GCE (Google Compute Engine) 上で実行されていれば、その build-in service account を使う
5. ここまで該当がなければエラーとする


## well_known_file について

```
$ gcloud auth application-default login
```

を実行すると作成される。
デフォルトだと `~/.config/gcloud/application_default_credentials.json`
環境変数 `CLOUDSDK_CONFIG` が指定されていれば `$CLOUDSDK_CONFIG/application_default_credentials.json`


## Access Token を取得する

service account か authorized user の credentials を使う場合は、
然るべきリクエストを作ってトークンエンドポイントに POST する。
GCE の場合はメタデータサーバーに GET する。


## Access Token を使って API を叩く

取得した access token を Authorization ヘッダに Bearer 形式で入れる。
`Authorization: Bearer xxxx.yyyyyyyyyyyyy`


## 使うとき

[Google 的に優先度高い言語](https://developers.google.com/identity/protocols/OAuth2WebServer#libraries) は公式ライブラリが用意されていて、マニュアル見て使えばよい。
Elixir はライブラリが無かったので作った。
https://github.com/aktsk/gcp_auth
MySQL(InnoDB) で charset を utf8mb4 にする注意点の現在
Tags: mysql
Published: 2018-01-05 07:23:18

---
title: MySQL(InnoDB) で charset を utf8mb4 にする注意点の現在
published: true
description: 
tags: MySQL
---


絵文字に対応したいなどの理由で utf8mb4 を使う。
ただ、utf8mb4 に設定するだけだと以前は問題があった。
MySQL 5.7.9 以降では解決されたので、その話をまとめる。


## charset を utf8mb4 にする

server 全体に設定するでよければ my.cnf に次を設定すればよい。

```
[mysqld]
character_set_server=utf8mb4
collation_server=utf8mb4_unicode_ci
```

database 単位で設定したければ、次を発行すればいい。

```
ALTER DATABASE spam CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci;
```


## 対応すべき問題

utf8mb4 に変えると、VARCHAR 等のカラムで、同じ文字数でも size が大きくなる。
デフォルトではこの size の上限は 767byte で、index を張ろうとして落ちるなどする。
ということが、[MySQL(InnoDB) で "Index column size too large. The maximum column size is 767 bytes." いわれるときの対策](http://blog.kamipo.net/entry/2012/11/13/102024)、で詳しく説明されている。


## 以前の解決方法

innodb_large_prefix パラメータを ON にすることで、size 上限が 3072byte になり、問題なくなる。
ただしそのためには、テーブルの ROW_FORMAT を DYNAMIC (か COMPRESSED) にする必要がある。
さらにそのためには、innodb_file_format が Barracuda であることが必要。

なので実際には

```my.cnf
innodb_large_prefix=ON
innodb_file_format=Barracuda
innodb_file_format_max=Barracuda
```

として、また CREATE TABLE するときに `ROW_FORMAT=DYNAMIC` を付けることで解決できた。


## 現在

- `innodb_file_format` はデフォルトで `Barracuda` (5.7.7 以降)、
- `innodb_default_row_format` はデフォルトで `DYNAMIC` (5.7.9 以降)
- `innodb_large_prefix` はデフォルトで ON (5.7.7 以降)で、deprecated で、じき項目が消える予定

ということで、上記の問題を解決するために設定すべき項目は 5.7.9 以降では無くなり、解決していた。


## 参照

- https://dev.mysql.com/doc/refman/5.7/en/innodb-parameters.html#sysvar_innodb_file_format
- https://dev.mysql.com/doc/refman/5.7/en/innodb-parameters.html#sysvar_innodb_default_row_format
- https://dev.mysql.com/doc/refman/5.7/en/innodb-parameters.html#sysvar_innodb_large_prefix
- https://dev.mysql.com/doc/refman/5.7/en/innodb-restrictions.html
- https://dev.mysql.com/doc/refman/5.7/en/innodb-row-format-specification.html
- https://dev.mysql.com/doc/refman/5.7/en/innodb-row-format-dynamic.html