teleren/devto huggingface dataset:
Native Javascript AJAX POST Request with Data or Parameters
Tags: javascript, ajax, sinatra
Published: 2020-05-30 14:04:24

---
title: Native Javascript AJAX POST Request with Data or Parameters
published: false
date: 2018-08-26 22:54:00 UTC
tags: javascript,ajax,sinatra,javascript
canonical_url: https://www.railsmine.net/2018/08/native-javascript-ajax-post-request-with-data-or-parameters.html
published: true
---

If we don’t care about response from the server, native Javascript AJAX POST request with data / parameters is quite simple.

```js
var request = new XMLHttpRequest();
request.open('POST', '/example', true);
request.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded; charset=UTF-8');
request.send(data);
```

`data` variable is a body of data to be sent in the XHR request. This can be:

- A Document, in which case it is serialized before being sent.
- A BodyInit, which as per the Fetch spec can be a Blob, BufferSource, FormData, URLSearchParams, ReadableStream, or USVString object.

I’ve tried to send data with [FormData](https://developer.mozilla.org/en-US/docs/Web/API/FormData) object, but it’s not working with my Sinatra Application. So I use [URLSearchParams](https://developer.mozilla.org/en-US/docs/Web/API/URLSearchParams) to send the data.

Here is example of my native Javascript AJAX POST request with parameters.

```js
var mydata = document.getElementById('mydata');
var myresponse = document.getElementById('myresponse');
var data = 'mydata=' + mydata.value;

var request = new XMLHttpRequest();
request.open('POST', 'http://example.com/mypath', true);
request.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded; charset=UTF-8');

request.onreadystatechange = function() {
  if (this.readyState == XMLHttpRequest.DONE && this.status == 200) {
    console.log('succeed');
    myresponse.value = request.responseText;
  } else {
    console.log('server error');
  }
};

request.onerror = function() {
  console.log('something went wrong');
};

request.send(data);
```

More Information:

- [XMLHttpRequest.send()](https://developer.mozilla.org/en-US/docs/Web/API/XMLHttpRequest/send)
- [FormData](https://developer.mozilla.org/en-US/docs/Web/API/FormData)
- [URLSearchParams](https://developer.mozilla.org/en-US/docs/Web/API/URLSearchParams)
Go sql.DB Periodic Error: invalid connection
Tags: go, sql, beginners
Published: 2018-08-26 22:04:33

---
title: Go sql.DB Periodic Error: invalid connection
published: true
description: Dealing with periodic invalid connection errors in Go.
tags: go, sql, beginners
---

## Background
Up until now, my team at work were primarily PHP developers. We recently deployed our first Go application (a REST API) to our production server to take care of some of the backend functions of our primary [Symfony](https://symfony.com/) app.

## Issue
After 15-20 minutes of inactivity, the next request to our API would fail because of an `invalid connection` error when trying to make any database query, but then the next query would be successful.

This would normally happen overnight when we would have much lower traffic to our API.

I suspected the idle connections were being killed by the MySQL server. We never had this problem with PHP because a new MySQL connection would be made on each request, or if a PHP script was running for more than 15 minutes it would be constantly making requests keeping the connection alive.

## Solution 
I thought of adjusting the timeout on the MySQL server but it is managed for us by another team so I was hoping to find a solution that my team could implement.

Looking through `go doc sql.DB` I saw it had a `Ping()` method. The description says: `Ping verifies a connection to the database is still alive, establishing a connection if necessary.`

That sounded exactly like what would solve my problem, and it did! I just set a simple goroutine to run the `Ping()` method every 5 minutes.


```go
package main

import (
	"database/sql"
	"log"
	"time"

	_ "github.com/go-sql-driver/mysql"
)

var db *sql.DB

func main() {
	db, _ = sql.Open("mysql", "user:password@/dbname")
	// Error handling omitted for this example
	
	go periodicPing()

	// Start the web server
}

func periodicPing() {
	for {
		time.Sleep(time.Minute * 5)

		err := db.Ping()
		if err != nil {
			log.Println(err)
		}
	}
}
```

## Update (Jan 3, 2019)
I acknowledge that this was not a good solution and I wanted to come back and reference an update to my issue: 

{% link aaronellington/importance-of-configuring-go-sqldb-connections-15bc %}
What do you do in your two hours out of home?
Tags: discuss, outsidehome
Published: 2018-08-26 21:24:18

---
title: What do you do in your two hours out of home?
published: true
description: 
cover_image: https://thepracticaldev.s3.amazonaws.com/i/uru93rlmhp2cq7omjyjl.jpg
tags: #discuss, outsidehome
---

I read the [StackOverflow statistics for this year (2018)](https://insights.stackoverflow.com/survey/2018/#developer-profile-how-much-time-do-developers-spend-outside) and it shows the time developers spend outside is about 30min to 2h per day.

This number is very reasonable, by my self. Now I'm curious about: **What you do at this time?**

During the work week I spend time riding a bike and exercising me, and at the weekend I try to know the cool places in my city, like the "Two Brothers Hill" in Rio de Janeiro.


![Two Brothers Hill](https://thepracticaldev.s3.amazonaws.com/i/uru93rlmhp2cq7omjyjl.jpg)
Javascript array iteration with 'some()' and 'every()'
Tags: javascript, arrays, beginners, webdev
Published: 2018-08-26 17:45:16

---
title: Javascript array iteration with 'some()' and 'every()'
published: true
description: using 'some()' and 'every()' to iterate arrays
tags: javascript, arrays, beginners, webdev
canonical_url: https://wangonya.com/blog/array-iteration/
---
If you're using an array in your code, chances are, you'll need to iterate over the values in the array. There's a couple of ways you can do that, some better and more efficient than others depending on what you want to accomplish.

For this post, I'll focus on two ways: `some()` and `every()`.

#### `some()`
The `some()` method tests whether **at least one** element in the array passes the test implemented by the provided function. It checks the elements one by one, and if it finds an array element where the function returns a truthy value, `some()` returns `true` and does not check the remaining values. Otherwise it returns `false`.

Lets say you want to check if a contact exists in your contact list:
```javascript
const contacts = ['Stewie', 'Meg', 'Quagmire', 'Cleveland'];

function checkContacts(arr, val) {
  return arr.some(arrVal => val === arrVal);
}

checkContacts(contacts, 'Lois');   // false
checkContacts(contacts, 'Meg'); // true
```
When checking for `Lois`, `some()` checks the array elements beginning at `Stewie` to the end, and having not found a match, returns `false`. When checking for `Meg`, it stops at `Meg` and returns `true`, ignoring the rest of the elements.

#### `every()`
This method tests whether **all** elements in the array pass the test implemented by the provided function. It checks the elements one by one, and if it finds an array element where the function returns a falsy value, `every()` returns `false` and does not check the remaining values. Otherwise it returns `true`.

Lets check if all the names in our contacts list have more than 3 characters:
```javascript
['Stewie', 'Meg', 'Quagmire', 'Cleveland'].every(contact => contact.length >= 4); // false
['Stewie', 'Megan', 'Quagmire', 'Cleveland'].every(contact => contact.length >= 4); // true
```
The first test returns `false` since `Meg` has only 3 characters. Remember: for `every()`, *all* the elements in the array have to be truthy for it to return `true`. Changing `Meg` to `Megan` in the second test therefore returns `true`.

These two methods can come in handy if you need to perform somewhat similar tasks as described above. But of course, they're not the only way. Hope someone finds this useful! :)
Four Key Elements of a Healthy Framework Ecosystem
Tags: opensource, frameworks
Published: 2018-08-26 17:56:27

---
title: Four Key Elements of a Healthy Framework Ecosystem
published: true
description: 
tags: opensource, frameworks
---

I wanted to share a great comment from [this thread on Rails](https://dev.to/ben/the-rails-ecosystem-is-healthier-than-ever-2il8). But I think these lessons apply to any ecosystem.

These concepts are well-described and generalizable. If you are choosing a framework, or even building one, I suggest taking these four concepts into account.

{% devcomment 525l %}

Happy coding. ❤️
Ask Dev: How do you learn new things and keep up with the trends in development.
Tags: programming, discuss, help, career
Published: 2018-08-26 17:54:38

---
title: Ask Dev: How do you learn new things and keep up with the trends in development.
published: true
description: 
tags: programming,discuss,help,career
---
Hey Devs,

I'd love to know how you guys are keeping up with the latest trends in software development as there are always new things to learn and the best practices to keep up with. 

It's nice to mention:
1. What are the resources you are using? I mean any blogs/newsletters/youtube channels you follow.
2. How often you read or watch tutorials.
3. Do you only read if you got stuck in any problems or in implementing any features?
Storybook Addon AngularJS (1.x)
Tags: javascript, storybook, angular
Published: 2018-08-26 15:57:31

---
title: Storybook Addon AngularJS (1.x)
published: true
description: An addon for Storybook with support for AngularJS
tags: javascript, storybook, angularjs
cover_image: https://thepracticaldev.s3.amazonaws.com/i/fd0law9lrk482iqis68h.png
---

A few weeks ago I published the package [storybook-addon-angularjs](https://www.npmjs.com/package/storybook-addon-angularjs) to help create stories for Storybook with AngularJS components.


Features:
- Simple syntax
- Supports integration with other addons like `knobs` and  `actions`

The Tweet with the first announcement and a small screen capture:

{% twitter 1017450306362380289 %}

Creating a story with an AngularJS component is as simple as this: 

```javascript
import { storiesOf } from "@storybook/html";

import { withKnobs, text, number } from "@storybook/addon-knobs";
import { action } from "@storybook/addon-actions";

import { forModule } from "storybook-addon-angularjs";

storiesOf("Components/Demo", module)
  .addDecorator(withKnobs)
  .add(
    "default",
    forModule("myApp").createElement(compile => {
      const name = text("Name", "Jane");

      const foo = {
        bar: number("Value", 20, { range: true, min: 0, max: 30, step: 1 })
      };

      const onEvt = action("clicked");

      return compile`<demo-component
                       name="${name}"
                       foo="${foo}"
                       on-ev="${onEvt}(num, name)"></demo-component>`;
    })
  );
```

This depends on Storybook 4+ and the HTML Addon.

The code for the addon:
{% github titonobre/storybook-addon-angularjs %}

A working example:
{% github titonobre/storybook-addon-angularjs-example %}

Feedback is appreciated.
Thanks for reading.
Why I Joined Dev.to Community And You Should Too
Tags: devto, opensource, developers, beginners
Published: 2018-08-26 15:14:50

---
title: Why I Joined Dev.to Community And You Should Too
published: true
description: how i found dev.to and why i joined
tags: devto, opensource, developers, beginners 
cover_image:  https://palash.tk/assets/images/why-i-joined-dev-to.jpg
---

I knew about Dev.to for a long time , even I read some articles there but I didn't Signup there. I was not at all convinced to join till 16th August.

![.](https://palash.tk/assets/images/why-i-joined-dev-to.jpg)

On 16th August morning , I was looking into GitHub Trending projects, and on the top I found this.

![dev.to](https://palash.tk/assets/images/devto-is-open.jpg)

Dev.to became Open Source! **Open Source** is like a loved word to me, I immediately went straight to dev.to and signed up.

I started surfing through lots of articles, I liked them so much. Then I posted some of my articles from [Adventure of Palash](https://palash.tk) there and surprisingly I got very good responses even daily traffic on [Adventure of Palash](https://palash.tk) got boosted. 

And You won't believe within few days **I crossed 200+ followers** and now heading to 300.

#### One thing I liked most is the friendly folks. People on dev.to are very friendly.

Within few days , I started using dev.to very much , it is like a kind of home to me. It is like **Facebook for Developers**

I even learnt (and still learning) lots of thing from there , such as **mistakes** I make while writing articles for my blog and about some new technologies, new concepts, new programming languages and much morr.

If I talk about the User Interface, it's fabulous simple but powerful. Easy use and free from bloating unwanted widgets. I like it very much!

Another good thing is you don't need to install a bloated mobile app to use it properly on Android or iOS devices, it is quite simple to add it's PWA to home screen without needing to install something.

From the first day , I read new new articles every day and learn something new everytime. 

You can see it's on the third position on my frequently used apps.

![my frequently used apps](https://palash.tk/assets/images/freq-app-devto.jpg)

One Thing I mentioned Earlier, Dev.to open source and its Source Code is available on GitHub. If you found something wrong , you can create issue there. If you want a feature very badly, you can let the Developers know via a issue. You can also contribute to the codebase to make it better.


### Recommendation

If you are a Developer ar thinking of being a Developer, you should definitely join dev to now.
Visit <https://dev.to> and Signup now.

#### I believe , you'll surely like it

---
### Hey Guys I have a kind request, please follow me on twitter [@bauripalash](https://twitter.com/bauripalash) , I feel very lonely there 😢

---
That's it for now friends , see you next time. Till then let me know your thoughts, suggestions and questions in the comments below 👇

---
If You Like My Work (My Articles, Stories, Softwares, Researches and many more) Consider [Buying Me A Coffee ☕](https://www.buymeacoffee.com/palash) 🤗
Nuxt.jsでSSRかブラウザ上の処理かを判定する方法の一つ
Tags: nuxt, node, typescript
Published: 2018-08-26 15:02:38

---
title: Nuxt.jsでSSRかブラウザ上の処理かを判定する方法の一つ
published: true
description: 
tags: nuxtjs,nuxt,node,typescript
canonical_url: https://crieit.net/posts/Nuxt-js-SSR
---

Nuxt.jsで開発する場合、書いた処理がサーバーサイドレンダリング（SSR）時と、ブラウザ上での処理時の両方で実行される場合がある。それを判定したい時の方法。

## 正規の方法

正規の方法として、公式にも書かれているやり方。

[window or document undefined?](https://nuxtjs.org/faq/window-document-undefined/)

こんな感じで判定できる。

```javascript
if (process.browser) {
  require('external_library')
}
```

## TypeScriptの場合

ただし、TypeScriptの場合はprocessの型にbrowserというプロパティが無いため、エラーになってしまう。そのため色々あれこれ型をうまい事設定する方法も可能かもしれないが、とりあえず古式ゆかしい方法でも判定することができる。

```javascript
    if (typeof window !== "undefined") {
```
Omniauth-Twitter
Tags: rails, omniauthtwitter, twitterapi
Published: 2018-08-26 14:29:36

---
title: Omniauth-Twitter
published: true
description: Omniauth-Twitter still throwing 403
tags: rails, omniauth-twitter, twitter-api
---

I have realized all my twitter apps keep breaking after the new api settings since July. I have tried to get my developer account approved and tried to many times to add the callback URL so many times but I still get the 403. Any help about how to get around this? Thanks
Retrieve TextInput entered value on Button Click onPress in React Native
Tags: react, reactnative, android, mobileapp
Published: 2018-08-26 14:27:37

---
title: Retrieve TextInput entered value on Button Click onPress in React Native
published: true
description: Retrieve TextInput entered value on Button Click onPress in React Native
tags: #react #reactnative #android #mobileapp
---

Post Link : https://www.skptricks.com/2018/08/retrieve-textinput-entered-value-on-button-click.html

This post explains <a href="https://www.skptricks.com/2018/08/retrieve-textinput-entered-value-on-button-click.html">how to retrieve TextInput Layout component entered value in react native application </a> with the help of state and props. TextInput is a basic component that allows the user to enter text. It has an onChangeText prop that takes a function to be called every time the text changed, and an onSubmitEditing prop that takes a function to be called when the text is submitted.

<img src="https://2.bp.blogspot.com/-CHNl1CXsAWc/W4KrypO6-VI/AAAAAAAAB0w/mbMllz_-Iukbhoz1ZBa-VlnR8be2_EqlQCLcBGAs/s1600/tt.jpg" />

In this example we are entering and retrieving value TextInput layout entered value on button click and displaying the entered value on screen using Alert dialog box.

{% youtube 64Afcxg-FC0 %}

<a href="https://www.skptricks.com/2018/08/retrieve-textinput-entered-value-on-button-click.html"> <b>Download Source Code </b> </a>
My Microservices Stack
Tags: microservices, softwaredevelopment, distributedsystems
Published: 2018-08-26 14:04:54

---
title: My Microservices Stack
published: true
description: Here is my some what opinionated stack for building resilient and elastic distributed system
tags: microservices, software development, distributed systems
canonical_url: https://blog.elegantmonkeys.com/my-microservices-stack-a2befd410063
---

Here is my some what opinionated stack for building resilient and elastic distributed system. I describe each framework or platform with a single marketing line followed by how I use it.

* Node.js — A Javascript runtime built on Chrome’s V8 JavaScript engine. Used to build stateless API and automation scripts. Usually my “go-to” language for everything unless heavy lifting is needed.
* Lagom — An open source framework for building reactive systems in Java or Scala. Used to build systems and API based on Event Sourcing & CQRS.
* Akka — An open source toolkit for building highly concurrent, distributed and resilient message-driven applications for Java and Scala. Used to build data processing and complex processed based on the Actor Model.
* PostgreSQL — World’s most advanced open source relational database. Usually my “go-to” database as it fits most of the use cases and most cloud services provide it as a service.
* Docker — An open platform build, ship, and run distributed applications, whether on laptops, data center VMs, or the cloud. Used to package the applications in a uniform and immutable regardless the language or framework inside.
* Kubernetes — An open-source system for automating deployment, scaling, and management of containerized applications. Nothing more to say, just the perfect solution for deployment and application orchestration.
* Google Cloud Platform — Build, innovate, and scale. It simply provides everything I need for running my applications. Kuberenetes, Postgres, Docker registry and much more as a service with no ops needed (just your credit card, of course :P)


Looking forward to see your stack and comments!
Explain JS's radix in parseInt(str, radix), like I'm five.
Tags: javascript, explainlikeimfive, beginners, help
Published: 2018-08-26 13:29:01

---
title: Explain JS's radix in parseInt(str, radix), like I'm five.
published: true
description: 
tags: #javascript,#explainlikeimfive,#beginners,#help
---

Explain to me the parseInt(str, radix) **Radix**. **like I'm five**.

what does this **radix** mean? and why would you use it.

**thanks in advance**.
(sapass) With this module you can easy generate password in python projects
Tags: python, password, pypi
Published: 2018-08-26 13:08:42

---
title: (sapass) With this module you can easy generate password in python projects
published: true
description: With this module you can easy generate password in python projects
tags: #python, #password, #pypi
---

sapass
First version of password generator for python projects

Install easy

Use Easy

Use python version >= 2.7

Please visit below link:

https://pypi.org/project/sapass/
Timing your Python Code
Tags: python, profiling
Published: 2017-08-22 02:50:57

---
title: Timing your Python Code
published: true
canonical_url: https://cnu.name/timing-python-code/
description: A quick and dirty way to measure how much time your python code takes to execute.
tags: python, profiling
---

There are many times when you would want to see how much time your program takes to execute. The easiest way to do it on a unix system is to use the `time` command before running the program.

    $ time command

    real    0m1.320s
    user    0m0.010s
    sys     0m0.023s

This shows that the `command` took 1.32 seconds of wall clock time and 0.01s of time spent in userspace and 0.023s of time spent in kernel space.

This works well for any command you can run on the shell. But how would you find out how long a python function took? Or how long a particular line of code took?

The usual way I used to do was create a `time.time()` object before the piece of code, store it in a variable. Do the same `time.time()` and subtract from the previously stored value and print it. 

Nothing wrong with it. But instead of repeating this same piece of code everywhere, there has got to be a better way.

Let me introduce the timing context manager.

Create a module called `timer.py` and paste the following piece of code in it.

    import time

    class Timer(object):
        def __init__(self, verbose=False):
            self.verbose = verbose

        def __enter__(self):
            self.start = time.time()
            return self

        def __exit__(self, *args):
            self.end = time.time()
            self.secs = self.end - self.start
            self.msecs = self.secs * 1000  # millisecs
            if self.verbose:
                print 'elapsed time: %f ms' % self.msecs

Now all you have to do is, in the module where you want to time a piece of code,

    from timer import Timer
    ...
    with Timer() as t:
        some_slow_function()
    print 'elapsed: %ss' % t.secs

You can use `t.msecs` to display it in milliseconds. 

This is such a simple and elegant solution to log the time taken, that these kind of modules will probably have to go in a private python-utils package which I can import in any project I want. 

![track](http://bkit.co/w6id79ay)
BxJS Weekly Episode 25 - javascript news podcast
Tags: javascript, node, podcast, news
Published: 2018-08-26 09:42:16

---
title: BxJS Weekly Episode 25 - javascript news podcast
published: true
description: Listen to the best javascript news of the week in a podcast form
tags: javascript, node, podcast, news
---

Hey dev.to community!

BxJS Weekly Episode 25 is now out! 🚀
Listen to the best javascript news of the week in a podcast form right here.
You can find all the mentioned links [here on github](https://github.com/BuildingXwithJS/bxjs-weekly/blob/master/episodes/Episode-25-2018-08-25.md).

You can also watch or listen to this episode on:
- [YouTube](https://youtu.be/6UMIYAjTg3I)
- [Castbox](https://castbox.fm/episode/BxJS-Weekly-Ep.-25-Aug-25%2C-2018-(javascript-news-podcast)-id1378315-id89799861)

Any feedback is appreciated 😁

Additional stuff:
- [Twitch channel](https://www.twitch.tv/yamalight)
- [Discord server](https://discord.gg/hnKCXqQ)
- [BxJS Weekly github repo](https://github.com/BuildingXwithJS/bxjs-weekly)

Social media links:
- [Twitter](http://twitter.com/yamalight)
- [Medium](https://medium.com/@yamalight)
- [Github](http://github.com/yamalight)

If you enjoy my content, please consider [supporting me](https://codezen.net/support.html) 😉