teleren/devto huggingface dataset:
Send cookies in Electron + React app
Tags: react, electron, webdev, typescript
Published: 2021-01-04 08:39:03

In this article I discuss using cookies to make an authenticated web call to an external domain.
Over the past few months I have been tinkering with an Electron + React app. I had never worked with these technologies before so mainly my goal has been to learn. I am using the opportunity to improve my developer experience at work. I like to call it my _developer console_.

Anyway, I wanted to create a small tool inside the developer console that would allow me to create reproducible data configurations for the software I work on, i.e., a one-button-click system for creating complex, reproducible test data scenarios. This required me to communicate and authenticate with my local development environment, something I hadn't previously had to do in the developer console.

Communication was an easy [`fetch` call](https://developer.mozilla.org/en-US/docs/Web/API/Fetch_API/Using_Fetch), but the authentication element was the unknown. How could I send cookies for a domain as part of my fetch? A quick internet search didn't give me _exactly_ what I wanted, but I was able to piece together what I needed from various sources. Below is a snippet for how to set the cookies for a domain in Electron, and how to include them in a `fetch`.

```typescript
import electron from 'electron';

function performExternalRequest() {
    const cookieJar = electron.remote.session.defaultSession.cookies;
    const cookie = { 
        url: 'https://youdomain.com',
        name: 'your-cookie-name',
        value: 'your-cookie-value'
    };
    
    cookieJar.set(cookie)
    .then(() => {
        fetch('https://your-api.domain/endpoint', {
            credentials: 'include'
        })
        .then((response) => {
            console.log(response);
        })
    });
}
```

A gist for the above is [here](https://gist.github.com/olsnacky/8f2bd20e916c01e1ec9575b42cf2f19f).

The key elements in the above are:
- adding the cookie to the cookies for the session; and
- setting the `credentials` property on the fetch request options to `include`.

The former sets the cookie so it can be included in the request. The latter ensures the cookie is included in the request.

Setting the `credentials` option warrants a bit of discussion. Depending on your browser version, the default value for `credentials` will either be `omit` or `same-origin`. If the former, then __no cookie will be sent__. If the latter, and if your electron app is on a different domain than the server you want to communicate with, which is likely, then also __no cookies will be sent to the server__. The only way to send the cookies to the server when your app is on a different domain is to set the `credentials` option as `include`.

For more information, see:
- [Electron documentation on cookies](https://www.electronjs.org/docs/api/cookies)
- [Mozilla documentation on `fetch`](https://developer.mozilla.org/en-US/docs/Web/API/Fetch_API/Using_Fetch)

__NB:__ While `fetch` is not exclusive to React, I mention React in this post as it was a key element of the context in which my questions existed.
Day 4 text to speech is done for second component and more about dohackathon
Tags: dohackathon, webdev, react, showdev
Published: 2021-01-04 16:11:15

Hackathon Journey
hello all 😊👋
In this Day 4(note day4 is just for the name I am working on this stuff for 1 2 weeks) article of the digital Ocean hackathon, I am going to write about how I did things and which things I completed till today so let's jump into the article now.

If you are following this series then you are knowing the second component of this project is almost completed already if you're not following the series then somewhere below you can find the series thing you can check out. 

As I yesterday talked about the next feature of the second in day 3 article at last so today I worked on that feature 

**Worked on text-to-speech in reactjs using react-speech-kit**

* **following changes are made in Space.js file for adding text-to-speech feature**
```js
const [ setValue] = useState('');
const { speak } = useSpeechSynthesis();
```
//firstly enabling text-to-speech on API generated text seems difficult task to me but after few minutes of thinking and looking at the code carefully I did below I will show that I did it.
```js
  <p className={styles.space.explanation} value={photoData.explanation}
        onChange={(event) => setValue(event.target.explanation)}>{photoData.explanation}</p>
      </div>
    </div> 
    <div>
    <button className={styles.button} onClick={() => speak({ text: photoData.explanation })}>Listen 🔊</button>
    </div>
```
and space.modules.css⤵️ for that button means text-to-speech one
```js
.button {
  display: inline-block;
  padding: 15px 25px;
  font-size: 15px;
  cursor: pointer;
  text-decoration: none;
  outline: none;
  color: #fff;
  background-color: #0719bb;
  border: black;
  margin-left:150px;
  margin-right:100px;
}
.button:hover {
  background-color: #101110;
}


.button {
  text-align: center;
  background-color: #384ab1;
}
```
**live view of the button it is just screenshot repository will be updated related to that soon**
![Alt Text](https://dev-to-uploads.s3.amazonaws.com/i/ff0e527dtsrkbmpg66kk.png) 
For detailed code check previous articles codebase section

as per my views, this component is done but I am thinking instead of the next button (I am thinking of exploring new things related to space) for that I will fetch another [NASA open API](https://api.nasa.gov/) and I will make a space travel web app as interactive as possible that component will be 3rd component and 4th component is going to be about space travel  like references and short info about project and me and special thanks section.
that's it for this article.
thank you for reading have a nice day all.😊 
![GIFY](https://media.giphy.com/media/dCdjSBHCwQQGBXayHM/giphy.gif)
special thanks to 
onkar khedhkar [Onkar Khedkar](https://www.linkedin.com/in/onkar-khedkar-767476148/)  and shook goud for suggesting changes and inspiring me to do good stuff.😊😊
Nested Request Throttling in Laravel
Tags: laravel, php
Published: 2021-01-06 09:13:39

Let me set the stage first: You have a globally assigned throttle middleware on a specific route group or maybe even assigned directly inside the `RouteServiceProvider` on all routes from a specific file. Then, you try to assign (nest) the throttle middleware inside that group onto a specific route expecting that the global throttle values will be overwritten by the nested values just to be surprised that the route gets locked after fewer requests than specified (more specifically, in the case of a single nested throttle middleware - two times fewer requests than expected).

I found myself in this scenario and after giving some thought it does make sense - the middleware is called twice so two hits rather than one. (The `X-RateLimit-Remaining` header gets decremented by two rather than one) However, how can we overcome this obstacle?
- We can remove the global throttle middleware and just apply it on all routes we need it. (Quite a bit of repeating indeed)
- Perhaps, we can extend the default throttle middleware and implement some kind of an identifier that we’ll use to differentiate the throttles.

Luckily, Laravel already has a [solution](https://github.com/laravel/framework/pull/28856) for us! It uses the second approach to prefix the various throttles so that we can use them independently. Unfortunately, the documentation doesn’t mention this, however, it is pretty straightforward.

```php
// User can send 1000 requests of any kind in an hour.
Route::prefix('image')->middleware('auth', 'throttle:1000,60')->group(function() {
    // User can download 10 times a minute.
    Route::post('/download', 'ImageController@download')->middleware('throttle:10,1,minute_download');
    // User can search 100 times an hour
    Route::get('/search', 'ImageController@search')->middleware('throttle:100,60,search');
    // Use default throttle, user can send 1000 images in an hour.
    Route::get('/send', 'ImageController@send');
});
```

The route group above wraps three routes inside the `auth` and `throttle` middlewares. These two middlewares can be considered as global to the routes within that group. Depending on the scenario, we might consider applying different throttle values for some of the routes in the group. This is the case with the `/download` and `/search` routes - we want to have a lower request limit for them (in the current case). We achieve this by passing a third argument to the throttle middleware. This is the prefix value that will be used to differentiate them - `throttle:max_requests,period,prefix`.

**This feature has been introduced in Laravel 6.0. For any previous versions, you need to extend the default throttle and implement your own solution.**

Originally posted on https://ntsanov.com/blog/nested-request-throttling-in-laravel
pyenv install fails on MacOS 11 BigSur
Tags: pyenv, python, macosx, bigsur
Published: 2021-01-06 09:23:57

If you are getting the following error:

```
pyenv install  3.8.6
python-build: use openssl@1.1 from homebrew
python-build: use readline from homebrew
Downloading Python-3.8.6.tar.xz...
-> https://www.python.org/ftp/python/3.8.6/Python-3.8.6.tar.xz

Installing Python-3.8.6...
python-build: use readline from homebrew
python-build: use zlib from xcode sdk

BUILD FAILED (OS X 11.1 using python-build 20180424)

Inspect or clean up the working tree at /var/folders/6x/cp1l4tr97y7g3jxm74n4c6v80000gn/T/python-build.20210106100539.35673
Results logged to /var/folders/6x/cp1l4tr97y7g3jxm74n4c6v80000gn/T/python-build.20210106100539.35673.log

Last 10 log lines:
    mod_name, mod_spec, code = _get_module_details(mod_name)
  File "/private/var/folders/6x/cp1l4tr97y7g3jxm74n4c6v80000gn/T/python-build.20210106100539.35673/Python-3.8.6/Lib/runpy.py", line 144, in _get_module_details
    return _get_module_details(pkg_main_name, error)
  File "/private/var/folders/6x/cp1l4tr97y7g3jxm74n4c6v80000gn/T/python-build.20210106100539.35673/Python-3.8.6/Lib/runpy.py", line 111, in _get_module_details
    __import__(pkg_name)
  File "<frozen zipimport>", line 241, in load_module
  File "<frozen zipimport>", line 709, in _get_module_code
  File "<frozen zipimport>", line 570, in _get_data
zipimport.ZipImportError: can't decompress data; zlib not available
make: *** [install] Error 1
```
 
It breaks because Python installation cannot find zlib. 

The solution is easy - provide CFLAGS from the xcode sdk:

```
$ CFLAGS="-I$(xcrun --show-sdk-path)/usr/include" pyenv install 3.8.6
python-build: use openssl@1.1 from homebrew
python-build: use readline from homebrew
Downloading Python-3.8.6.tar.xz...
-> https://www.python.org/ftp/python/3.8.6/Python-3.8.6.tar.xz
Installing Python-3.8.6...
python-build: use readline from homebrew
python-build: use zlib from xcode sdk


Installed Python-3.8.6 to /Users/kuba/.pyenv/versions/3.8.6
```
Improving image-specific testing with actual examples
Tags: testing, github, ci, mocha
Published: 2021-09-23 23:41:22

In Lagoon 1.x, Lagoon ran a full battery of tests for every pull request submitted to the GitHub repository. Not only was this inefficient, but unrelated errors also added false negatives to the testing process. In addition, running these tests required a full local instance of Lagoon to be created, which presented a significant technical and resource hurdle for contributions. With the addition of Kubernetes, this hurdle was reduced, but still significant.

At the same time as completing the work on Lagoon 2, we have been working hard on a set of example projects for Lagoon – covering a wider range of frameworks, content management systems, and situations than previously. We have gathered these examples over at https://github.com/uselagoon/lagoon-examples as Git submodules to the source repositories and branches.

We will be taking advantage of these example projects to test our images. We have built a CI process that will build our images, clone, build, and test the relevant example projects using the images being modified. With the introduction of automated dependency resolution triggering CI builds, we have automated a large portion of the image production process. 

The tests we will be using for the process have been written in Markdown, and are parsed into Mocha tests by the excellent [Leia](https://github.com/lando/leia) parser from the Lando team.  These tests are human-readable and easy to contribute to.  You can see an example at https://github.com/amazeeio/drupal-example-simple/blob/9.x-advanced/TESTING_dockercompose.md.

Likewise, we will be running the same set of tests inside these example projects to ensure the projects work with the latest and edge releases of the images prior to any changes being merged.
Post Test
Published: 2021-01-30 20:16:43

Donec sollicitudin molestie malesuada. 
**Mauris blandit aliquet elit, eget tincidunt nibh pulvinar a.**

_List_
1. Curabitur arcu erat, accumsan id imperdiet et, porttitor at sem.
2. Vivamus suscipit tortor eget felis porttitor volutpat. Vivamus suscipit tortor eget felis porttitor volutpat.

_Another List_
- Curabitur arcu erat, accumsan id imperdiet et, porttitor at sem.
- Vivamus suscipit tortor eget felis porttitor volutpat. Vivamus suscipit tortor eget felis porttitor volutpat.

Random Image

![Avatar](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/mlqedpftc69n0lv42dtz.png)

And yeap, this is a post test. [Link to second post.](https://dev.to/randyaguirre/second-post-59l0)

Spotify
{% embed https://open.spotify.com/track/20RHP0KD0gDz7xzmzZCGBo?si=a4fd6f9e4f6d46ac %}

Youtube
{% embed https://youtu.be/5yx6BWlEVcY %}

Twitter
{% embed https://twitter.com/NetflixLAT/status/1494730400295440389 %}

Wikipedia
{% wikipedia https://es.wikipedia.org/wiki/Internet %}
Explaining RSpec instance_double in 2 minutes
Tags: rspec, ruby, testing
Published: 2021-01-31 11:22:55

Let's take the `Notifications` example:
```ruby
class Notifications
  def as_json
    # Fetch latest notifications via HTTP API
  end
end

class NotificationsController
  def index
    render json: { data: notifications.as_json }
  end

  def notifications
    Notifications.new
  end
end
```

To avoid requesting remote API in tests, we use a `double`:

```ruby
describe "NotificationsController#index" do
  let(:notifications) do
    double(:datasource, as_json: { notifications: [] })
  end

  before do
    allow(Notifications)
      .to receive(:new)
      .and_return(notifications)
  end

  it "wraps notifications in 'data' key" do
    get :index, format: :json

    expect(json_response["data"])
      .to have_key "notifications"
  end
end
```

What happens if we rename `Notifications#as_json` to `Notifications#to_json`? Nothing. We will be left alone with a green test checking a useless double.

## instance_double

To avoid getting into a situation described above, use `instance_double`:
```ruby
describe 'NotificationsController#index' do
  let(:notifications) do
    instance_double(Datasource, as_json: { notifications: [] })
  end

  # ...
end
```

Such a double will test its interface. If there is no method `as_json` or it has other arguments, it will fail the test.

To check mocks and stubs in the same way, make sure that [verify_partial_doubles](https://relishapp.com/rspec/rspec-mocks/v/3-10/docs/verifying-doubles/partial-doubles) is enabled in spec_helper.rb.

-----------

More on this topic:
* [Using an instance double](https://relishapp.com/rspec/rspec-mocks/v/3-10/docs/verifying-doubles/using-an-instance-double)
* [object_double](https://relishapp.com/rspec/rspec-mocks/docs/verifying-doubles/using-an-object-double)
* [class_double](https://relishapp.com/rspec/rspec-mocks/v/3-10/docs/verifying-doubles/using-a-class-double)
Hire a Hacker
Tags: hacktoberfest
Published: 2021-01-31 16:43:08

We  Hacker’s Nest are a group of 48 hackers from across the world and have completed more than 40k jobs and have more than 35k satisfied clients in the time of 9 years. You can hire a hacker in very less and time and we ensure that we deliver in the least time possible.

Hire a hacker for wide range of services: 
 
Hire a Hacker for Cellphone Access, Cheating Partner, Parental Control, live GPS location, Email Access, Cyber Bullied, Facebook, Snapchat, Instagram password etc
[Booklog] ベタープログラマ(O'Reilly)
Published: 2021-02-01 08:52:10

 [備忘のためのメモ]

## ch3_少ないコードを書く

※コメントを書くときに意識すること

•コード自身は、何をどのようにしてを説明しているため、コメントでは「なぜ」を説明すること、しかし何故を説明する際にコードがかつて行っていたことを記載しないようにすること。

## ch10_バグ狩り

※問題解決を速やかに行う為に

•素早く、バグを特定する為にはバイナリチョップを行う、具体的にはコードのパスをひとつづつ実行するのではなく、事象の連鎖のはじめと終わりから始める。それから問題空間を二分して、中間点が良い状態か悪い状態かを調べる。それを繰り返して二分探索的に問題を特定する。（よくない打ち手としては1ステップずつ実行すること）


## ch13_二つのシステムの物語

※優れた構成を産むために

• コードを書き始める前に、意図して事前の設計を行うこと。多くのプロジェクトは、実際に開発する前にこの点で失敗し、そこには対立する緊張がある。設計が足りなさすぎず、その上過剰設計でないこと。

• 開発を進めながら、設計を明瞭に維持し続けること。

• ソフトウェアの全体設計の責任が与えられて、責任を持つチームであること。

• 設計を変更することを恐れないこと。永久に変わらないものは無し。

• チームにふさわしい人々を入れること。そこには設計者、プログラマ、マネージャが含まれる。開発チームを適切な大きさにすること。**彼らが健全な関係になるようにする。彼らの関係が必然的にコードの構造へ反映される。**

• 設計上の決定を、決定するためのすべての情報を分かっている適切な時期に行う。まだ行えない設計に関する決定を遅らせること。

## ch24_学びを愛して生きる

※スキル獲得のドレイファスモデルを読んで要点の抽出

• 初級者
経験が学習を導く、規則を破って独自のやり方を試すが、うまくいかなくなると行き詰まってしまう。関係のない詳細を省くことができない。

• 中級者
全体像を持つことで、未知な問題に対処したり、問題に対する方法論的な筋道を計画できる。新たな規則の限界も把握し始める。

• 上級者
全体像の深い理解、自らの経験からだけでなく他人の経験から学び、理解して吸収できる。問題に対するデザインパターンを持っている。

• 専門家
専門家は理解を極めた結果、直感を持っているので、規則を必要とせずに答えが自然にわかる。

## ch31_一生懸命でなく、賢く

※新たな作業が依頼されたら

• 今実際に必要とされているのが、なんであるかを調べること。初期の段階でTooMuchにやることを積み上げるのはやめること。

パレートの法則
https://blog.kairosmarketing.net/marketing-strategy/how-to-leverage-pareto-law-into-marketing-activities/
Setting up a development MacBook
Tags: macbook, tips
Published: 2021-02-01 21:43:01

I wrote a set of quick-start scripts for developers that use macOS. A Windows version of these scripts might follow soon.

Setting up a “fresh” laptop for development is always painful, be it windows, macOS or Linux.

It was the second time in the year when I was doing a fresh install of macOS on my MacBook. I was tired of installing all the apps that I need in a one-by-one fashion. I was tired of doing all the small configurations (for macOS and for the apps). Most of the time I forgot some of them and there are a couple of settings that I have to search online every time.

I started off by making a list of settings and applications that I use and then I discovered that most of these things can be automated via the command line. I was sure that someone did this before me and I started searching for some scripts that automate the installation of the development environment on a MacBook. I hit jackpot.

Using a couple of GitHub repositories as inspiration, I created a couple of simple scripts that should install almost everything that I need to start developing on a MacBook. The scripts and the instructions are available here: https://github.com/treaz/mac-dev-setup/

I’m curious how much it will hurt the next time that I have to set up a development MacBook.
The 7 Most Popular DEV Posts from the Past Week
Tags: top7
Published: 2021-02-02 18:49:03

---
title: The 7 Most Popular DEV Posts from the Past Week
published: true
description: A round-up of the most-read and most-loved contributions from the community this past week.
tags: icymi
cover_image: https://thepracticaldev.s3.amazonaws.com/i/sfwcvweirpf2qka2lg2b.png
---
Every Tuesday, we round up the previous week's top posts based on traffic, engagement, and a hint of editorial curation. The typical week starts on Monday and ends on Sunday, but don't worry, we take into account posts that are published later in the week. ❤️

### Please Emoji Responsibly 

As a software developer, it’s easy to use emojis the wrong way -- but there are very real accessibility consequences. @iamludal shares a better path. 

{% link https://dev.to/iamludal/you-are-using-emojis-the-wrong-way-i71 %} 


### Slow & Steady Serves You Better

@alexlsalt talks about the importance of taking things slow as an early-career developer. 


{% link https://dev.to/alexlsalt/the-importance-of-slowing-way-down-as-a-junior-software-engineer-4jei %} 

### No bones about it

… skeleton layouts have so much going for them! @lukekyl explains why. 

{% link https://dev.to/lukekyl/how-to-build-a-skeleton-layout-in-react-21hb %}

### Plots twists can lead to satisfying stories 

@anfibiacreativa shared a look inside their career journey -- from _physical_ architectural draftswoman to to solutions architect! 

{% link https://dev.to/this-is-learning/from-designer-to-software-engineer-to-solutions-architect-my-journey-2p5b %}

### The expert in anything was once a beginner

“To be honest,” writes @rajatarya007zxc “JavaScript still changes my perspective, but it also gives me more strength to work hard on it.”

This post provides great encouragement and guidance for when you’re beating yourself up over JavaScript (spoiler: don’t do that)

{% link https://dev.to/rajatarya007zxc/sometimes-javascript-is-tricky-67j %}

### Yearly health-screenings -- at a bare minimum. 

You go in to get your blood pressure checked at least once per year. Your websites need those screenings, too and security headers are an essential step in this wellness check. Thanks for these tips on checking security headers, @madsstoumann!

{% link https://dev.to/madsstoumann/frontend-security-security-headers-517p %}

### Getting into the freelance flow

As developers, it can be hard to switch to freelance in part because it requires you to “sell yourself” more frequently. Recently, @tanoaksam made this shift successfully! Here’s how.

{% link https://dev.to/tanoaksam/my-freelancing-workflow-from-cold-leads-to-paid-invoices-38hd %}

_That's it for our weekly wrap up! Keep an eye on dev.to this week for daily content and discussions...and if you miss anything, we'll be sure to recap it next Tuesday!_
How to remove duplicates from JavaScript array
Tags: javascript, codenewbie, tutorial, beginners
Published: 2021-02-02 00:02:28



Recently, I posted a small snippet on how to remove duplicates from an array using a filter function. That started a thread on all the different ways to achieve this. Therefore, in this post, I am covering different ways to solve this problem.
JavaScript logo

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

## 1. Creating new array and for loop

For loop and the new array would be the oldest possible solution. A solution you would use before array functions. Today you would do it this way.

```javascript
const numbers = [1, 2, 3, 1, 2, 3, 1, 2, 3];
 
const newNumbers = [];
 
for(let i = 0; i < numbers.length; i++) {
  if(newNumbers.indexOf(numbers[i]) < 0)
    newNumbers.push(numbers[i])
}
 
console.log(newNumbers);
```

## 2. Filter function
JavaScript arrays contain many different built-in functions, and a filter is one of them. This function takes one parameter, the filter function, which then has three parameters. The first one is the element you are testing, the second is its index, and the last one is the original array.

```javascript
const numbers = [1, 2, 3, 1, 2, 3, 1, 2, 3];

const newNumbers =
  numbers.filter(
    (element, index, array) =>
      array.indexOf(element) === index
    )

console.log(newNumbers);
```

## 3. Using the Set object
Using a set is one of the more modern solutions. Sets are part of the ES6 version of JavaScript, and they are objects that do not contain duplicates. You can create a set object using the original array and then convert it back to the array.

```javascript
const numbers = [1, 2, 3, 1, 2, 3, 1, 2, 3];

const newNumbers = Array.from(new Set(numbers));

console.log(newNumbers);
```

These are the three most common ways to remove duplicates from an array. But programming is creative, and I am sure there are many more. If you know of any, please write it in the comments.

---

For more, you can follow me on [Twitter](https://twitter.com/hi_iam_chris_), [LinkedIn](https://www.linkedin.com/in/kpajtasev/), [GitHub](https://github.com/kristijan-pajtasev/), or [Instagram](https://www.instagram.com/hi_iam_chris_/).