teleren/devto huggingface dataset:
Effective Java: Beware the Performance of String Concatenation
Tags: java, effective, string, architecture
Published: 2021-05-19 04:26:07

---
title: Effective Java: Beware the Performance of String Concatenation
published: true
description: A dive into chapter 63 of Effective Java
tags: java, effective, string, architecture
cover_image: https://images.unsplash.com/photo-1506744038136-46273834b3fb?ixid=MnwxMjA3fDB8MHxwaG90by1wYWdlfHx8fGVufDB8fHx8&ixlib=rb-1.2.1&auto=format&fit=crop&w=1050&q=80
series: Effective Java Review
canonical_url: https://blog.scaledcode.com/blog/effective-java/string_concat_perf/
---

An attribute of the `String` type is that they are immutable. This allows for a number of good attributes. Another attribute of the `String` type is that Java provides some syntactic sugar to concatenate `String`s by using the `+` operator. This is a very beneficial ability but putting these two capabilities together, immutability and simple contenation can lead us to accidentally cause performance issues. Let's consider an example:

```java
public String concatenateStrings(int numberOfIterations) {
  String result = "";
  for (int i=0; i < numberOfIterations; i++) {
    result += randomStringOfLength(m);
  }
  return result;
}
```

With a low value for `numberOfIterations` this can turn out to be fine. As the number of iterations goes up the cost goes up drastically. This is because the `String`s can't be modified and must be copied. This not only costs a lot of compute power but also creates a lot of garbage for the garbage collector to clean up. Compare this to the much more performant version:

```java
public String concatenateStrings(int numberOfIterations) {
  StringBuilder result = new StringBuilder();
  for (int i=0; i < numberOfIterations; i++) {
    result.append(randomStringOfLength(m));
  }
  return result.toString();
}
```

This code uses a mutable holder to collect the `String`s so it can concatenate them all at once. 

So when should we use string concatenation and when should we use the `StringBuilder`. A good rule of thumb is to use a `StringBuilder` when concatenating in a loop. When concatenating a static number of `String`s the performance won't get any better or worse from your initial testing so you won't be surprised by performance problems.
LeetCode 791. Custom Sort String (javascript solution)

Tags: algorithms, javascript
Published: 2021-05-19 04:21:38

###Description:
order and str are strings composed of lowercase letters. In order, no letter occurs more than once.

order was sorted in some custom order previously. We want to permute the characters of str so that they match the order that order was sorted. More specifically, if x occurs before y in order, then x should occur before y in the returned string.

Return any permutation of str (as a string) that satisfies this property.

###Solution:
Time Complexity : O(n)
Space Complexity: O(n)

```javascript
var customSortString = function (order, str) {
    const map = new Map();
    // Count chars in str and save into map
    for(let i=0;i<str.length;i++){
        map.set(str[i],map.get(str[i])+1||1);
    }
    let res=''
    // Add characters common between str and order to the res string
    for(let i=0;i<order.length;i++){
        res += order[i].repeat(map.get(order[i]))
        map.delete(order[i])
    }
    // Add characters from str not found in order to the res string
    for(let [key,value] of map){
        if(value>0){
            res+= key.repeat(value);
            map.delete(key)
        }        
    }
    return res;
};
```
Simple navbar with flexbox
Tags: css, codenewbie, beginners, todayilearned
Published: 2021-05-19 04:14:57

First of all, this is not a responsive menu, but we can use it for the desktop device without a dought. I have used flexbox to make it. Let's see how it looks like on the screen. And this is not last, it just starts in the next other posts we will learn how to make navbars like Burger menu, responsive menu, sidebar menu and much more. So make sure you are following me.

{% codepen https://codepen.io/atulcodex/pen/RwpoRqV %}

{% link https://dev.to/atulcodex/instagram-login-page-4e39 %}
ESP8266 MicroPython reset() 的陷阱
Tags: micropython, esp8266, reset
Published: 2021-05-19 04:12:12

如果你的程式需要強制重置, 像是底下這個簡單的範例：

```python
from machine import reset

count = 0
while True:
    print(count)
    count = count + 1
    if count == 10:
        reset()
```

你可能會以為執行了 reset() 之後就會重置, 所以也不會再回到 while 迴圈中, 那你就錯了, 實際的執行結果如下：

```
0
1
2
3
4
5
6
7
8
9
10
11
12
...
278
279
280
281

 ets Jan  8 2013,rst cause:2, boot mode:(3,6)

load 0x40100000, len 30712, room 16 
tail 8
chksum 0x16
load 0x3ffe8000, len 996, room 0 
tail 4
chksum 0x70
load 0x3ffe83f0, len 1064, room 4 
tail 4
chksum 0xa3
csum 0xa3
��n�r��n|�llll`�rl�l�l`�rl�l�l`�rl$�ll`rl$rl�bbČb�bbr�$b�n'�
MicroPython v1.15 on 2021-04-18; ESP module with ESP8266
Type "help()" for more information.
>>>
```

計數到 10 時候的確執行了 reset(), 但這只是發出訊號通知系統重置, 實際上你的程式執行從 reset() 返回後還會繼續執行, 你可以看到程式一路列印到 281 才真的重置。

根據 [MicroPython 的原始碼](https://github.com/micropython/micropython/blob/7408ca1d7857df5ea348da35c9ee12f70a024478/ports/esp8266/modmachine.c#L76)：

```cpp
STATIC mp_obj_t machine_reset(void) {
    system_restart();
    return mp_const_none;
}
```

reset() 實際上會叫用 [ESP8266 SDK](https://www.espressif.com/sites/default/files/documentation/2c-esp8266_non_os_sdk_api_reference_en.pdf) 的 system_restart, 而 SDK 文件中特別表示：

```
The ESP8266 will not restart immediately. Please do not call other functions after calling this API.
```

也就是說系統不會真的立即重置, 而且也不希望在此之後叫用其他函式。為了避免這個問題, 建議在 reset() 後加個無窮迴圈等待系統重置：

```python
from machine import reset

count = 0
while True:
    print(count)
    count = count + 1
    if count == 10:
        reset()
        while True:
            pass
```

這樣就會正確執行了：

```
0
1
2
3
4
5
6
7
8
9

 ets Jan  8 2013,rst cause:2, boot mode:(3,6)

load 0x40100000, len 30712, room 16 
tail 8
chksum 0x16
load 0x3ffe8000, len 996, room 0 
tail 4
chksum 0x70
load 0x3ffe83f0, len 1064, room 4 
tail 4
chksum 0xa3
csum 0xa3
��n�r��n|�llll`�rl�l�l`�rl�l�l`�rl$�ll`rl$rl�2bbČb�bbr�$b�n'�
MicroPython v1.15 on 2021-04-18; ESP module with ESP8266
Type "help()" for more information.
>>> 
```
Python Tips & Tricks: JSON to DataFrame
Published: 2021-05-19 04:07:28

### Aprende Python

<p>
¿Sabes cómo convertir un archivo JSON en DataFrame con Python? Hoy les traemos cómo hacerlo en unas líneas de código 😎.
<br><br>
Revisa el código completo aquí:
<br>
👉🌐 <a href="https://go.datahacks.ai/repositorio">https://go.datahacks.ai/repositorio</a>
<br><br>
Tenemos un supercurso de Python con un enfoque en Data y Analytics:
<br>
👉🌐 <a href="https://go.datahacks.ai/crece">https://go.datahacks.ai/crece</a>
<br><br>
Únete al #DataHackChallenge: 
<br>
👉🌐 <a href="https://go.datahacks.ai/challenge">https://go.datahacks.ai/challenge</a>
</p>

<img src="https://dev-to-uploads.s3.amazonaws.com/uploads/articles/h5blrw2hxwc8bvaax94d.png" alt="ptt"></img>
<img src="https://dev-to-uploads.s3.amazonaws.com/uploads/articles/pqovq63cgxzjmwadshd8.png" alt="ptt"></img>
<img src="https://dev-to-uploads.s3.amazonaws.com/uploads/articles/gzd8nj3nus070a5lkb1s.png" alt="ptt"></img>

Aprende, Aplica y Crece en áreas de Data, Analytics y Cloud.
Search Box Part 1- eCommerce Accessibility
Tags: a11y, accesibility, ecommerce, searchbox
Published: 2021-05-19 03:37:29

To celebrate this year's [Global Accessibility Awareness Day](https://globalaccessibilityawarenessday.org/) (GAAD) I started working on one of my 2021 goals, **write more technical notes** on eCommerce accessibility.  

I will start making an assumption that not a single eCommerce website can live without a search box. It should allow users a way to discover products & categories. Easier than the menu sometimes.  

But what makes a search box actually useful? Let's dive in.  

## Design Principle
Let's build a search box component that allows you to type characters. and as user types, results are automatically updated showing the top X related products. These are the high level requirements:  

* Component should be located on the header
* Should have a label & a magnifier icon
* Should have `default`, `:hover` & `:focus` styling
* It should start showing suggestions after user has typed 2 characters.
(this will be develop in part 2)


## Basic Code
```html
<form action="/search" method="get" role="search">
    <button type="button" class="search-btn" aria-label="Search">
        <svg focusable="false" class="search-icon">
            <use xlink:href="#icon-search"></use>
        </svg>
    </button>
    <input id="search" type="search" name="q" autocomplete="off" autocorrect="off" spellcheck="false" placeholder="Search" aria label="Search for products"/>
</form>
<svg xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" width="0" height="0" style="position: absolute;">
    <symbol id="icon-search" viewBox="0 0 32 32">
        <path d="M21.6 19.2h-1.264l-.448-.432a10.373 10.373 0 0 0 2.516-6.793c0-5.76-4.669-10.429-10.429-10.429S1.546 6.215 1.546 11.975c0 5.76 4.669 10.429 10.429 10.429 2.601 0 4.98-.952 6.806-2.527l-.014.011.432.448V21.6l6.8 6.8a1.686 1.686 0 0 0 2.383-2.384l.001.001zm-9.6 0a7.2 7.2 0 1 1 7.2-7.2v.01a7.19 7.19 0 0 1-7.19 7.19H12h.001z"></path>
    </symbol>
</svg>
```
Wow, that's escalated quickly! Let's see what all this mumbo jumbo means.


Read the entire article in medium: 
[Search Box Part 1— eCommerce Accessibility](https://hecosbornerod.medium.com/search-box-part-1-ecommerce-accessibility-c7e7f0e527a8)
Structures in C Language
Published: 2021-05-19 03:35:04

Structure is a user-defined datatype in C language which allows us to combine data of different types together. Structure helps to construct a complex data type which is more meaningful. It is somewhat similar to an Array, but an array holds data of similar type only. But structure on the other hand, can store data of any type, which is practical more useful.

For example: If I have to write a program to store Student information, which will have Student's name, age, branch, permanent address, father's name etc, which included string values, integer values etc, how can I use arrays for this problem, I will require something which can hold data of different types together.

In structure, data is stored in form of records.

Defining a structure
struct keyword is used to define a structure. struct defines a new data type which is a collection of primary and derived data types.

Syntax:

struct [structure_tag]
{
    //member variable 1
    //member variable 2
    //member variable 3
    ...
}[structure_variables];
Element-UI
Tags: elementui, vue
Published: 2021-05-19 03:19:51

<h2>ElementUI rules format</h2>
note: the rules should in data() {}
```javascript
data () {
  return {
    rules: {
        productKey: { required: true, message: '请选择产品', trigger: 'change' },
        // errorCode: { required: true, message: '请填写故障代码', trigger: ['change', 'blur'] },
        errorNum: { required: true, message: '请填写故障位', trigger: ['change', 'blur'] },
        errorDesc: { required: true, message: '请填写故障详情', trigger: ['change', 'blur'] }
      },
  }
}
```
<h2>Form validate trigger by event</h2>
```javascript
methods: {
      submitForm(formName) {
        this.$refs[formName].validate((valid) => {
          if (valid) {
            alert('submit!');
          } else {
            console.log('error submit!!');
            return false;
          }
        });
      }
}
```
A simple log collector listening log file written to clickhouse
Tags: clickhouse, php
Published: 2021-05-19 03:16:06

A simple log collector, Monitor files through tail -F command, write to the Clickhouse. Very low occupancy of resources, It can process more than 100 thousand log information per second

## install

`composer require lizhichao/log2ck`

## example

`tail -F apapche/access.log | php apache_log.php -h tcp://127.0.0.1:9000 -u default -p 123456 -d logs -t apache_log`

options : 

- `-h` clickhouse host port
- `-u` clickhouse user name
- `-p` clickhouse password
- `-d` clickhouse database name
- `-t` clickhouse table name


## principle

Use clickhouse to support streaming writing

Code factory library used

https://github.com/lizhichao/log2ck

https://github.com/lizhichao/one-ck
YouTube Live Stream ON: Bash Shell for Data Sciences
Tags: linux, live, tutorial, beginners
Published: 2021-05-19 02:35:06

Welcome to the Bash Shell for Data Sciences | Scientific Programming School – FREE YouTube Live Stream. [🔴 LIVE NOW!](https://youtu.be/2SyrHh65qMk)

[https://youtu.be/2SyrHh65qMk](https://youtu.be/2SyrHh65qMk)

In this awesome live class ❤️ we will cover three practical flat file data mining projects involving four data projects (each with a different objective function):

- University ranking data,
- Facebook data,
- Australian statistics crime data and

Please don’t forget to Subscribe our new [YouTube channel] if you want more weekly updates on Linux, Devops, HPC and Advanced coding. We create advanced code videos and present you a platform [scientificprogramming.io](https://scientificprogramming.io) to run scientific codes/ OS commands as you learn with playgrounds and Interactive shells, inside your browser!
![Bash for data science](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/c0gxtrt6ru9c1icw6tos.png)
Almost everyone can benefit from learning to use Bash ([Learn Practical Data Sciences with Bash Shell](https://school.scientificprogramming.io/course/learn-practical-data-sciences-with-bash-shell/2)) particularly in data mining: particularly students who want to learn Bash and the command line to improve their career prospects, researchers who want to add Bash and other command line tools to their bag of tricks, scientists who want to learn to explore and analyze the data that their lab generates.
A simple parameter validator
Tags: php
Published: 2021-05-19 02:22:44

A simple parameter validator

```php
$_POST  = [
    'email' => 'xxxx',
    'age'   => 2
];
$vt     = new Validator();
$result = $vt->validate($_POST, [
    'name'  => 'required|min_len:5|max_len:10', // required 5<= strlen(name) <=10
    'email' => 'required|email', // required email
    'age'   => 'uint|min:18|max:200'  // options Positive integer 18<= age <=200
])->isOk();

if ($result === false) {
    print_r($vt->getErrs());
}


//Array
//(
//    [0] => name can not be empty
//    [1] => email incorrect format
//    [2] => age not less than 18
//)

```

### Built-in rules

- `required`
- `numeric` numbers include floating point numbers
- `min` cannot be less than
- `max` cannot be greater than
- `min_len` cannot be shorter than
- `max_len` cannot be longer than
- `int` integer
- `uint` positive integer 
- `email` mailbox format
- `ip` ip format
- `stop` prevents bubbling (when a rule is not met, the remaining rules are not verified)


### If not enough? Customizable rules

```php
$vt->addRule('between', [
    'msg' => ':attribute can only be between :arg1-:arg2',
    'fn'  => function ($value, $arg1, $arg2) {
        return $value >= $arg1 && $value <= $arg2;
    }
]);

$vt->validate(['a' => 10], [
    'a' => 'required|between:3,10'
]);

// Check whether a value exists in the database
$vt->addRule('exist', [
    'msg' => 'the :attribute already exists',
    'fn'  => function ($value, $table, $filed) {
        return Model::from($table)->where($filed,$value)->find() !== null;
    }
]);

$vt->validate(['email' => 'sss@ss.com'], [
    'email' => 'required|exist:users,email'
]);
```
Can be used here 
https://github.com/lizhichao/one
Stop fighting with npm by isolating it into a container
Tags: docker, node, script, devtool
Published: 2021-05-19 02:13:24

Hello,

Let me share a small script that i'm using on my local machine to develop.

> Before we start, let me share a bit more my profile: I wrote my first line of code 15 years ago and I'm not so much into following trends... Then I develop using vim, tmux and ... bash (yes still 🤪)

As you know nowadays there is new tools, new version, new framework, new system... Installing all of this into your machine has a cost.

### A new way of working by isolating projects

This is why a few years ago,  I made a shift to work only  within Docker container... And I LOVE IT! 🚀

I made a small script to automate the flow...

As a NodeJs developer i was tired of:
* Installing global module into my computer.
* Using nvm to change node version.
* Having conflict between projects.
* Tracking all the weird files that are installed in my HOME folder
* keep trying to save space...

Now all of those problems are gone since I don't have node installed on my computer anymore, the only way I use node is through an isolated container by using this script: 

```sh

#!/bin/bash

# File located in: ~/.dotfile/scripts/docker-run.sh

port=""
while getopts "p:" arg; do
  case $arg in
    p)
      for I  in "$OPTARG"
      do
        port="-p $I $port"
      done
      ;;
  esac
done

name=${PWD##*/}

docker run --name ${name} -v $(pwd):$(pwd) --workdir $(pwd) ${port} -it node:14 bash
```
and adding this into my `~/.bash_alias`:

```sh
drun="sh ~/.dotfile/scripts/docker-run.sh"
```

Then when i run the alias command in a project folder:

```
drun -p 8080:8080
```

It will:

* Create a fresh container with the name of the current folder
* Map the 8080 port of my local machine into the 8080 port of the container.
* Mount the current folder into the container.
* Enter in the container.

From there, I can still edit the file from my local machine, but run any node command from the container

##### Example:

[![asciicast](https://asciinema.org/a/jcuPxW5rpldm1WM938s3JgJky.svg)](https://asciinema.org/a/jcuPxW5rpldm1WM938s3JgJky)

### Conclusion

If you are still reading until here, I think you understand the potential of this. It can be use for any use case.
I also use this tips a lot, to try different programing language without installing them.

Let's break the dependency with our machine as much as possible 😇.

I forgot: Take a look at [RestQA](https://restqa.io)

See Ya!

---



More about Me:
* 🤓 : Blogging and Coding in English 🇬🇧 with a French accent 🇫🇷 while sitting in Thailand 🇹🇭.
* 🚀: API Dealer and Test automation Addict.
* ⭐️: Give a star to the next [Open source API test automation platform](https://github.com/restqa/restqa)
* 💼 : Head Of API Governance @ [FWD Insurance](https://www.fwd.co.th/en/)
* 🐥: [https://twitter.com/olivierodo](https://twitter.com/olivierodo)
5/18 TIL: Cartesian Product
Published: 2021-05-19 01:50:49

- Cartesian Product A X B is the set of all ordered pairs (a,b) where a ∈ A and b ∈ B
- A function:
    - For every input, there is some output
    - Has one output at most for an input—vertical line testing could be done to test this
- A function F between A and B is a relation between A and B (subset of A X B)—define this using the Cartesian Product:
    - For every element x ∈ A there is an element y ∈ b such that (x, y) ∈ F
    - If (x, y) ∈ F and (x, z) ∈ F then y = z
- Two statements are logically equivalent if they have the same truth table
    - p ≡ ~(~p) (p equals to not not p)
    - DeMorgan's Laws
Rocket Chat iOS WebSocket Error
Tags: ios, docker
Published: 2021-05-19 01:43:22

Hello to everyone,

I redesign the on-prem building with micro architecture. I started Rocket Chat in docker, but on iOS devices; When I log in, "Websocket has been disabled. Contact the system administrator." warning was available.

I did a little research to fix the problem. If you add the following commands to your Nginx configuration file, the problem is solved.

Happy days everyone.

```
upstream rocket {
   server [CONTAINER_IP:PORT];
}

server {
   listen 443 ssl;
   client_max_body_size 200M;                                        
   server_name ROCKETCHATURL;                                      
   access_log /dev/stdout;
  # I use "valian/docker-nginx-auto-ssl" image.                                         
   include resty-server-https.conf;                                  
 location / {                                                      
   proxy_pass http://rocket;                                         
   proxy_http_version 1.1;                                           
   proxy_set_header Upgrade $http_upgrade;                           
   proxy_set_header Connection $connection_upgrade;                  
   proxy_set_header Host $host;                                      
 }      
 location ~ "/sockjs/[\d]{3}/[\w]{8}/websocket" {
   proxy_pass http://rocket;
   proxy_http_version 1.1;
   proxy_set_header Upgrade $http_upgrade;
   proxy_set_header Connection $connection_upgrade;
   proxy_set_header Host $http_host;
   proxy_set_header X-Forwarded-For  $proxy_add_x_forwarded_for;
   proxy_set_header X-Real-IP $remote_addr;
   proxy_set_header X-Forwarded-Origin ''
  }
 location /websocket {
   proxy_pass http://rocket;
   proxy_http_version 1.1;		
   proxy_set_header Upgrade $http_upgrade;
   proxy_set_header Connection $connection_upgrade;
   proxy_read_timeout 7d;
   proxy_set_header Host $http_host;
   proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
   proxy_set_header X-Real-IP $remote_addr;
   proxy_set_header X-Forwarded-Origin '';
 }
}
```
crypto.randomUUID is three times faster uuid.v4
Tags: node, benchmark
Published: 2021-05-19 00:36:30

---
title: crypto.randomUUID is three times faster uuid.v4
published: true
description: I wondered how big the difference between uuid generation by Node.js API and uuid package. 3 times! 
tags: node, benchmark
cover_image: https://dev-to-uploads.s3.amazonaws.com/uploads/articles/c98lo6finga6fdv33jlf.png
---

Node.js v14.17 release added `crypto.randomUUID()`. This method allows to generate random [RFC 4122](https://www.rfc-editor.org/rfc/rfc4122.txt) Version 4 UUID strings. Example:

```javascript
const { randomUUID } = require('crypto');

console.log(randomUUID());
// '43c98ac2-8493-49b0-95d8-de843d90e6ca'
```

I wondered how big the difference between uuid generation by Node.js API and uuid package.

For benchmarking I prefer to use [hyperfine](https://github.com/sharkdp/hyperfine). It is like apache benchmark, but for CLI commands. There are have two cases:
1. require('crypto').randomUUID()
2. require('uuid').v4()

Let's put them into two files:

```javascript
// test-native.js
const { randomUUID } = require('crypto');

for (let i = 0; i < 10_000_000; i++) {
  randomUUID();
} 
```

```javascript
// test-uuid.js
const { v4 } = require('uuid');

for (let i = 0; i < 10_000_000; i++) {
  v4();
}
```

Now we ready for benchmarking:
`hyperfine 'node test-native.js' 'node test-uuid.js'`

This command shows that native generation is three times faster than `uuid` package. Awesome!