teleren/devto huggingface dataset:
Capitalizing Words in Javascript
Tags: javascript, vue
Published: 2021-01-18 12:24:06

I was looking for a solution on capitalizing all words in a string in Javascript this morning to use as the title of a page, I found a bunch of solutions, some included regex, some included looping through every character, some required a whole function.

I wanted something much cleaner and thought I'd share with everyone my solution

For this example I will be using the string "my awesome title"

```js
"my awesome title".split(' ').map(i => {
    return i[0].toUpperCase() + i.substr(1);
}).join(' ');
```

So what is happening? First we split the string into an array by a space, we then iterate over it returning the first character of the string as uppercase, and the rest of the string starting at position 1. We then join it all back together with a space.

You can easily turn this into a function

```js
capitalizeWords(words) {
    return words.split(' ').map(i => {
        return i[0].toUpperCase() + i.substr(1);
    }).join(' ');
}
```

Or if you are writing in VueJS like I needed to you can created a computed property, you will need to change the `this.$route.params.category` to what you want and split it by the appropriate character, for my requirement it was split by a dash

```js
computed: {
    title: () => {
        this.$route.params.category.split('-').map((i) => {
            return i[0].toUpperCase() + i.substr(1)
        }).join(' ')
    }
}
```

There seems to be quite a few ways to do this, but I found this way to be cleaner than requiring regex, if you want to do it with regex, I found [this blog](https://codesource.io/javascript-snippet-capitalize-text-with-javascript/) had an example
Hello Libtorrent : Make Magnetlink
Tags: cpp, libtorrent, bittorrent, p2p
Published: 2021-01-25 01:20:25

This document describe how to create a magnet link from torrent file.

Magnet link is a part of URL scheme that begin with "magnet:".

if you already have a torrent client installed on your computer, once you click magnet link, start a torrent client.


# What is Magnetlink

Magnet link 's spcification is bep 0009
https://www.bittorrent.org/beps/bep_0009.html

Magnetlink is defined by bep0009 to share files without using torrent files. 

There is less information in the magnet link than in the torrent file as URLs have length and character limits, magnet link.

magnet link has following information

- info-hash or tagged-info-hash
 Info-hash is metadata's part hash in a torrent file. 

- peer-address
 peer addres is the address of Peer that has the target data
 having Target data torrent client address.
- tr (optional)
 tr is tracker server address.


# Write Code With libtorrent

Next, I explain how to write a code for making magnet link from torrent file with libtorrent.

```
#include<iostream>
#include<libtorrent/magnet_uri.hpp>

void print_usage(std::string args0) {
    std::cerr << ""<< args0 << " <torrentfile path>" << std::endl;
}

int main(int argc, char *argv[]) {
    if(argc != 2) {
        print_usage(argv[0]);
        return -1;
    }
    lt::error_code ec;
    lt::torrent_info torrent_info(std::string(argv[1]), ec);

    std::cout << lt::make_magnet_uri(torrent_info);
    return 0;
}
```

If you more information magnet link's spec, I recommend to read a libtorrent's code.

 
# Source Code

https://github.com/kyorohiro/hello_libtorrent
app/main_tiny_magnetlink_creator.cpp
ラーメンレシピ2021
Tags: javascript, discuss
Published: 2021-01-25 00:55:20

ラーメンレシピ2021
2021年1月19日のＴＢＳ系テレビ番組『教えてもらう前と後』で放送された、マニア厳選の「インスタント袋麺ベスト５」と絶品アレンジレシピをまとめたのでご紹介します。インスタントラーメンの全国LOVERSたちが愛する今年絶対食べるべき品とは！？サッポロ一番塩ラーメンや、韓国の辛ラーメン、中華三昧、一蘭など、人気ラーメンが続々登場！

https://ra.co/events/1436074
https://ra.co/events/1436075
https://ra.co/events/1436077
https://app.livestorm.co/josiyah69/assistir-as-pequenas-coisas-2021-hd-f-i-l-m-e-completo-online-gratis-dublado
https://app.livestorm.co/website-5/as-pequenas-coisas-2020-assistir-filme-online-hd1080p
https://app.livestorm.co/keita044/assista-online-as-pequenas-coisas-2021-filme-completo-dublado
https://app.livestorm.co/joahan6/guan1-kan4-tang2-ren2-jie1-tan4-an4-3-wan2-zheng3-dian4-ying3-zai4-xian4-mian3-fei4-wan2-zheng3-ban3-ben3
https://app.livestorm.co/playfix/tang2-ren2-jie1-tan4-an4-3-wan2-zheng3-ban3-zai4-xian4-2021
https://app.livestorm.co/playfixhk/tang2-ren2-jie1-tan4-an4-3-wan2-zheng3-ban3-xiao3-ya1-hdhk
https://app.livestorm.co/kissmovies/guan1-kan4-ku1-bei1-wan2-zheng3-dian4-ying3-zai4-xian4-mian3-fei4-wan2-zheng3-ban3-ben3
https://app.livestorm.co/luukaki/ku1-bei1-wan2-zheng3-ban3-zai4-xian4-2021
https://app.livestorm.co/gracey07/ku1-bei1-wan2-zheng3-ban3-xiao3-ya1-hdhk
SQL
Tags: flatironschool, learntocode, sql, sqlite
Published: 2021-01-25 00:50:43

Tomorrow starts Week 3 of Flatiron School and for now we're moving away from exclusively Ruby and adding some SQLite in the mix. I'm doing a little weekend learning and went ahead and finished the first SQL lab. ![Screenshot of VS Code where Zed is showing the code he's written to pass the Flatiron provided tests](https://dev-to-uploads.s3.amazonaws.com/i/qh42ohvwdr0o474romsy.png)
สรุปสิ่งที่ได้จากการอ่านบทความ [Go] Packages as layers, not groups
Tags: go, programming
Published: 2021-01-25 00:50:20

เช้านี้ได้อ่านโพสต์เรื่อง [Packages as layers, not groups](https://www.gobeyond.dev/packages-as-layers/) โดย Ben Johnson แล้วน่าสนใจ เลยมาสรุปเอาไว้หน่อย

สิ่งที่บทความพยายามสื่อคือ package ของ Go นั้นไม่ใช่แค่กลุ่มของฟังก์ชันที่ทำหน้าที่คล้ายกันอย่างเดียว package ของ Go นั้นถูกใช้เพื่อออกแบบ dependencies ของโค้ดภายใน package ด้วย ดังนั้น package ของ Go จะไม่ยอมให้มีการอ้างอิงกัน (depends ต่อกัน) ในลักษณะ cyclic เช่น A ใช้ B แล้ว B ก็ใช้ A แบบนี้ (ข้อจำกัดตรงนี้เนี่ยแหละที่ทำให้ Go compiler compile ได้เร็ว)

ดังนั้นเวลาออกแบบจะเห็นว่า package ถูกออกแบบเป็นชั้นๆ (layer) โดยหน้าที่ของชั้นล่างจะคอย support ฟังก์ชันการทำงานของชั้นถัดๆไป เช่น net/http เรียกใช้ net แล้ว net ไปเรียกใช้ io อีกที

จะเห็นว่าแต่ละชั้นก็จะ absract ความซับซ้อนให้กับชั้นด้านบน net ไม่ต้องเขียนการติดต่อ io เอง net/http ก็ไม่ต้องจัดการ socket เอง

ในการออกแบบ application ของเราเองก็เช่นกัน เขายกตัวอย่าง app ง่ายๆที่มี 2 layers และออกแบบโดยแยกเป็นแค่ 2 packages คือ http จัดการ http service endpoint ต่างๆ ส่วน sqlite จัดการข้อมูลที่ต้องเขียน/อ่านกับฐานข้อมูล sqlite

ทิศทางของ dependency ก็คือ http เรียกใช้ sqlite

แล้วเขาก็ refactor design ให้ดูว่าจริงๆยังแยกออกเป็น package สำหรับ business domain ได้นะ แล้ว sqlite package ก็จะเหลือแค่ส่วนจัดการ sqlite จริงๆ อะไรเกี่ยวกับ domain logic แยกออกมา ในตัวอย่างชื่อ package คือ wtf

สุดท้ายแยกอีกรอบคือทำให้ http ไม่ยึดโยงกับ sqlite โดยตรงเพื่อให้ง่ายต่อการเขียนเทสหรือเปลี่ยนไปใช้ db ตัวอื่น โดยการทำให้ http ขึ้นกับ interface ที่ออกแบบเพื่อติดต่อ db แล้วตัว interface นี้ก็กำหนดไว้ใน wtf package

จากบทความนี้ก็มีประโยชน์มากๆเลยในการออกแบบ package ให้เป็น layer โดยที่แต่ละ layer คอย abstract ฟังก์ชันการทำให้ให้ layer ที่เรียกใช้อีกทีนึง

<a href="https://www.buymeacoffee.com/weerasak" target="_blank"><img src="https://cdn.buymeacoffee.com/buttons/v2/default-yellow.png" alt="Buy Me A Coffee" style="height: 60px !important;width: 217px !important;" ></a>
Framework Apache Camel
Published: 2021-01-25 00:40:25


Neste artigo, irei fazer um breve recurso do framework Java chamado de Apache Camel e falarei sobre alguns dos métodos mais utilizados no desenvolvimento.

![Alt Text](https://dev-to-uploads.s3.amazonaws.com/i/6z2gmzog4jhbfm6qq340.jpeg)

O Apache Camel é um framework que ajuda o desenvolvedor a lidar com a integração entre todos os formatos (xml, json, csv, http, SOAP, AMQP, SQL, Jax-RS, etc) utilizando boas práticas de integração. Basicamente, o apache Camel é um routing-engine (máquina de roteamento) e que utiliza uma linguagem de alto nível (Camel DSL). Vamos criar nosso primeiro projeto com o Camel, começando criando a classe principal:


![Alt Text](https://dev-to-uploads.s3.amazonaws.com/i/pkqg7slok2ktqqqyoeqv.JPG)


O método from() indica de onde os arquivos estão saindo, com um intervalo de 5 segundos entre eles (delay = 5s). O método to() indica o local-alvo para onde os arquivos estão indo. O método log() exibe no console as mensagens do processo, baseados em seus ids. O métodos context.start() é o responsável por iniciar o processo do Camel. O método sleep() mantém o projeto "ligado" durante mais 20 segundos após a finalização da execução de todos os processos. E, por fim, o método context.stop() é o responsável por finalizar o processo do Camel, após executar todas as suas tarefas.


O método .marshal().xmljson() é utilizado para transformar um arquivo do tipo XML em um arquivo JSON. O método .setHeader("CamelFileName", constant("pedidos.json")) cria um novo arquivo com o nome de pedido, do tipo JSON, com as informações do arquivo. O método .filter().xpath("/pedido/itens/item/formato[text()='EBOOK']") irá filtrar informações de algum lugar e xpath é uma linguagem que se comunica com arquivos do tipo XML. O método .split() é utilizado para se dividir alguma informação. O método .log("{body}") mostra o conteúdo de alguma mensagem.


O método .setHeader(Exchange.HTTP_METHOD, HttpMethod.GET) está realizando uma requisição do tipo GET. O método .to("direct:http") é utilizado para melhorar a organização de rotas muito grandes, redirecionando o Camel para trechos específicos do código, conforme o exemplo:


![Alt Text](https://dev-to-uploads.s3.amazonaws.com/i/mxnuy4w2kiiy374t9lif.JPG)


O atributo mock:soap é utilizado para criar uma requisição de testes. O método multicast() vai pegar informações de uma rota e fazer um multicasting, espalhando as informações para as sub-rotas, conforme o exemplo:


![Alt Text](https://dev-to-uploads.s3.amazonaws.com/i/5jxdll67ftuq86betffv.JPG)


O método .routeId("rota-pedidos") cria um nome para uma rota, facilitando a organização do código. O método .to("xlst:pedido-para-soap") converte um arquivo do tipo XML para XLS.
Introduction
Published: 2021-01-25 00:35:56

Hello, I am Jared Rice. I am a senior at Penn State University studying Information Sciences and Technology. I grew up in a small town in Northeastern Pennsylvania. I've always enjoyed working with computers since I was little. I enjoy almost all aspect of IT. I didn't really know what I wanted to do until my Junior year in high school when I took an A++ computer tech course, and finally realized my passion. I have greatly enjoyed my last four years at Penn State.I really am going to miss being here, but I am even more excited to see what the future holds for me and my career. 

During my time spent at Penn State I built a Java application that took in user input and gave them suggestions on local State College restaurants based on that input. It was very simple but taught me a lot about coding and project management. I learned a lot about Java and NetBeans, the IDE I used to develop the application. 

For almost two years I have been working for Penn State Arts and Architecture IT as a support specialist intern. I have many responsibilities such as printer maintenance, computer maintenance, computer life cycle management, etc. I have gained a lot of problem solving experience.  

For this blog I would ideally like to learn new skills and share them with anyone who wants to take part. I am always willing to learn new things and hopefully you can learn something by reading or watching my videos. My first video is here and it goes over making a basic java project in NetBeans. Go check it out!: https://youtu.be/yNOOa6nvRRw

I am very excited for what the future holds!
GitHub or Azure DevOps? The Interview
Tags: github, azuredevops, codenewbie, devops
Published: 2021-01-25 00:32:08

Today's video is very special, we have managed to put on an __exclusive double interview between Azure DevOps and GitHub__! 

We tried and asked the most common questions about the 2 platforms, which I receive on my [Twitter](https://twitter.com/DavideBenvegnu), [Facebook](https://www.facebook.com/CoderDaveYT), [LinkedIn](https://www.linkedin.com/in/davidebenvegnu/) and email almost on daily basis, but let me know in the comment section below if you have any other question, I will try and answer to everyone.

### The Interview

Alright, let's see what our 2 _honorable guests_ have to say. ;)

> Note: this was recorded few months back, some things might have changed in the mean time. For example, now __GitHub Actions CAN be [triggered manually](https://youtu.be/uNYDgUBClYY)__

{% youtube I6m8pa5nfpE %}

([Link to the video: https://youtu.be/I6m8pa5nfpE](https://youtu.be/I6m8pa5nfpE))

### Wrap up

This double interview was of course done in a _silly_ way, but I've tried to squeeze in most of the __questions I receive almost on daily basis__, and I hope you found it interesting and you had an answer for some of your questions or doubts.

Let me know in the comment section below if you have another question I haven't answered in this video, I will try and answer to everyone.

I hope you had fun watching this interview because I had a ton of fun making it!
Accordion using Html,Css,Js
Tags: 100daysofcode, html, css, javascript
Published: 2021-01-25 00:24:24

Fifth day of my 100 days of code.
#Html Code:
We have to create buttons and give contents below in div.
```
<h1>Accordion</h1>
    <h3>Click the button</h3>
    <div class="accordion">
      <button type="button" class="acc">What is Html?</button>
      <div class="panel">
        <p>
          Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do
          eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad
          minim veniam, quis nostrud exercitation ullamco laboris nisi ut
          aliquip ex ea commodo consequat.
        </p>
      </div>
    </div>

    <div class="accordion">
      <button type="button" class="acc">What is CSS?</button>
      <div class="panel">
        <p>
          Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do
          eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad
          minim veniam, quis nostrud exercitation ullamco laboris nisi ut
          aliquip ex ea commodo consequat.
        </p>
      </div>
    </div>
```
#Js code:
Access your button by using Classname and add eventlistener 'click' to all button.
Access your content by using **nextSiblingElement** and write the condition to display the content.

```
let acc = document.getElementsByClassName('acc');

for(let i=0; i< acc.length; i++){
    acc[i].addEventListener('click', function() {
        this.classList.toggle("active");
        let panel = this.nextElementSibling;
        if(panel.style.display === "block") {
            panel.style.display = "none";
        } else {
            panel.style.display = "block";
        }
    })
}
```
#Css Code:
Add the plus and minus sign using before property.
```
body {
  height: 100vh;
  background-color: #eee;
}

button {
  text-align: left;
  padding: 10px;
  margin-right: 5px;
  cursor: pointer;
  width: 50%;
  border-color: 1px solid #ccc;
}

button::before {
  content: "+";
  padding: 10px;
}

.active {
  background-color: #2c2b2b;
  color: #fff;
}
.active::before {
  content: "-";
  padding: 10px;
}

.panel {
  display: none;
  width: 50%;
 padding-left: 10px;
}
```
New to the world of developers. Learning Angular. Up next React or Vue ---what's your POV and why?
Tags: discuss, angular, vue, react
Published: 2021-01-25 00:23:36

Dear Devs, 
HELP?! So I am a newbie who decided she wanted to dump the corporate world and enter into the coding universe.  I am self teaching, with the help of DEV, You Tube, Medium, to name a few. So I want to know from you all, what do I learn next, Vue or React?

My real question is what is best Angular, React, or Vue for a girl like me and why.
A React "if component"
Tags: javascript, react
Published: 2021-01-25 00:09:23

---
title: A React "if component"
published: true
description: A smart component to avoid ugly ternary operators in your React code.
tags: javascript, react
canonical_url: https://www.stefanjudis.com/snippets/a-react-if-component/
---

After using Vue and Angular.js (I used the first version of Angular when it came out) for many years, I have to say that I always enjoyed the simplicity of using `v-if` and `ng-if` to render child components conditionally.

Now I'm writing React primarily and honestly I'm bothered by the constant use of ternary operators when dealing with conditionally rendered components.

```javascript
function SomeComponent({condition}) {
  return <div>
    { condition ? <span>Yes it is true!</span> : null }
  </div>
}
```

It's not a big deal, and there are many different ways to render boolean-dependent components, but I find myself writing code such as the above repeatedly. 

Today I read [7 Ways of Achieving Conditional Rendering in React](https://blog.asayer.io/7-ways-of-achieving-conditional-rendering-in-react), and it included a handy snippet that I'll adopt from now on.

## A conditional `if` component

I can't say that I didn't consider abstracting the ternary operators away, but somehow I never took it into practice. Fernando Doglio's article now moved me over the line to adopt a nicer pattern. Say hi to the functional `if` component.

```javascript
function IF({children, condition}) {
  if (condition) {
    // render children if the condition is truthy
    return children;
  }

  return null;
}

/**
 * Use the component as follows:
 *
 * <IF condition={condition}>
 *   <Greeter username={user.name} />
 * </IF>
 */
```

It's seven lines of code and this tiny component can be brought into any React project as handy utility. Much better! Thank you Fernando!
C# Useful Array.Methods()
Published: 2021-01-25 00:04:55

Array.IndexOf()
* returns index of item inside array
* *params: (array, value to find)*

Example
```
var colors = new[] { "red", "green", "blue" };

var result = Array.IndexOf(colors, "red");
WriteLine(result); // 0 
```


Array.Exists()
* returns a boolean if conditions are met
* *params: (array, conditions)*

Example
```
var colors = new[] { "red", "green", "blue" };

var result = Array.Exists(colors, color => color.Contains("green"));
WriteLine(result); // true
```

Array.Find()
* returns the first item to meet a condition
* *params: (array, condition)*

Example
```
var colors = new[] { "red", "green", "blue" };

var result = Array.Find(colors, color => color.Contains("green"));
WriteLine(result); // "green"
```

Array.FindLast()
* Starts search from the LAST index
* returns the first item to meet a condition
* *params: (array, condition)*

Array.FindIndex()
* returns the index of the element that meets the condition
* *params: (array, condition)*

Example
```
var colors = new[] { "red", "green", "blue" };

var result = Array.FindIndex(colors, color => color.Contains("green"));
WriteLine(result); // 1
```

Array.FindAll()
* returns array of all conditions met
* *params: (array, condition)*

Example
```
var colors = new[] { "red", "green", "blue" };

var result = Array.FindAll(colors, color => color.Contains("r"));

foreach (var color in result) 
{ 
  WriteLine(color); 
}
// "red"
// "green"
```

Array.Reverse()
* returns array with all elements in reverse order
* *params: (array)*

Example
```
var colors = new[] { "red", "green", "blue" };

var result = Array.Reverse(colors);

foreach (var color in result) 
{ 
  WriteLine(color); 
}
// "blue"
// "green"
// "red"
```

Array.Copy()
* copy elements to a new array
* can specify how many elements to copy
* *params: (originalArray, copy, numberOfElementsToCopy)*

Example
```
var colors = new[] { "red", "green", "blue" };
var colors2 = new string[colors.length];

Array.Copy(colors, colors2, 2);

foreach (var color in colors2) 
{ 
  WriteLine(color); 
}
// "red"
// "green"
```

Array.Sort()
* sort the elements of an array
* *params: (array)*

Example
```
var colors = new[] { "red", "green", "blue" };
Array.Sort(colors);

foreach (var color in colors) 
{ 
  WriteLine(color); 
}
// "blue"
// "green"
// "red"
```

Array.BinarySearch()
* search a sorted array
* returns the index of the found item
* returns -1 if nothing is found

Example
```
var colors = new[] { "red", "green", "blue" };
Array.Sort(colors); // "blue", "green", "red"

var index = Array.BinarySearch(colors, "green");
if (index == -1)
{
  WriteLine("not found");
}
else
{
  WriteLine(index); // 1
}
```
How to get the connection type of a user's device using JavaScript?
Tags: javascript
Published: 2021-01-25 00:00:00

---
  title: How to get the connection type of a user's device using JavaScript?
  published: true
  tags: JavaScript
  date: Mon Jan 25 2021 05:30:00 GMT+0530 (India Standard Time)
  canonical_url: https://melvingeorge.me/blog/get-connection-type-of-device-javascript
  cover_image: https://melvingeorge.me/_next/static/images/main-0756d2d744106277e1e99adf9522d1d0.jpg
  ---
  [Originally posted here!](https://melvingeorge.me/blog/get-connection-type-of-device-javascript)
  
## This is an experimental technology still in Draft, so it may not work in all browsers.

To get the connection type of a user's device, you can use the `effectiveType` property in the `navigator.connection` object in JavaScript.

```js
// get the connection type
const connectionType = navigator.connection.effectiveType;

console.log(connectionType); // 4g
```

For better usability, it's better to check whether the Network API is available in the appropriate browsers by first checking for the appropriate `connection` object in the `navigator` object.

```js
// check if connection object present
const connection =
  navigator.connection || navigator.mozConnection || navigator.webkitConnection;

// then use the effectiveType property
// to get the connection type
console.log(connection.effectiveType);
```

- **This API can be used to determine whether to load high bandwidth data or low bandwidth data by first checking the user's connection type is slow or fast and thus making the application much faster in accessing the content**.

See this example in [JSBin](https://jsbin.com/xepahuhebo/2/edit?js,console).

### Feel free to share if you found this useful 😃.

---
UIBuzz Podcast - Episode 8 - NextJS First Moments
Tags: javascript
Published: 2021-01-25 05:46:48

---
title: UIBuzz Podcast - Episode 8 - NextJS First Moments
published: true
date: 2021-01-24 23:46:00 UTC
tags: javascript
canonical_url: 
---

[Play it here on Spotify](https://open.spotify.com/embed-podcast/episode/75Bhce39aQlwhT4Jz9IXbv)

Anytime I work on a personal project I see it as a chance to try something new and also expand my skill set.

So this week, as I look to rebuild my photography site [GrfxMedia.com](http://grfxmedia.com), I decided I would take a look at [NextJS](https://nextjs.com).

NextJS is built on top of React, something pretty common these days. In many ways it is similar to GatsbyJS in that regards. Something this very site is built on (at least at the time of this post).

In this episode I share my findings from starting as a total novice to getting a working site and the ups and downs in-between.