teleren/devto huggingface dataset:
What are services offered better by AWS?
Tags: aws, azure, career
Published: 2020-04-09 15:57:24

On the various aspects of Cloud offerings we can say :-

AWS - It has more than 175+ services to be offered. and Diversified in term of Data , Networking , Machine learning , Analytics etc.

AWS has More than 60% share of this cloud Market. Because It started early.

AWS`s Most used services are :-
 

S3 - [Simple Storage service]:- 
for storage purposes , It is an Object based storage services which is widely used. and works on Shared Responsibility Model for security.

EC2: -[Elastic Compute Cloud] :-
It is an Bread and Butter for AWS , more than 70% of all services used. Virtual servers are provided through this service.

VPC: [Virtual private Cloud] :-
Cloud Infrastructure service to host your own isolated networking infrastructure.

IAM: [Identity and Access management]:-
This is a service to manage your users, in terms of admin , db , admin , developers , etc.

These are the services are mostly used by its clients. AWS also provides devops services .

AWS Lambda : Serverless Automation service , You can it as a Function as a service.

To sum up : These services are offered under classifictaion such as:
Compute ,Storage, Networking etc
Wait for the WebSocket connection to be open, before sending a message
Tags: javascript, websocket, await, send
Published: 2020-04-09 15:41:21

Sometimes when you open a new WebSocket connection and try to send a message, you can receive an Error reporting something like this: `Failed to execute 'send' on 'WebSocket': Still in CONNECTING state.`, because the connection is not open yet.

To avoid that, I saw some people suggesting to send the message on the `onopen` event; something like:
```js
socket.onopen = () => socket.send(message)
```
This approach, though, only works if you need to trigger `send()` once (on open).

A more flexible approach would be to wait for the connection to be open (if it's not already).

The `waitForOpenConnection` function, in the example below, returns a `Promise` that resolves when the connection is finally open, checking it every _n_ milliseconds.
If, after a given number of checks, the connection is still not open, the Promise is rejected.
In the `sendMessage` function, you can see an example of the usage.

```js
const waitForOpenConnection = (socket) => {
    return new Promise((resolve, reject) => {
        const maxNumberOfAttempts = 10
        const intervalTime = 200 //ms

        let currentAttempt = 0
        const interval = setInterval(() => {
            if (currentAttempt > maxNumberOfAttempts - 1) {
                clearInterval(interval)
                reject(new Error('Maximum number of attempts exceeded'))
            } else if (socket.readyState === socket.OPEN) {
                clearInterval(interval)
                resolve()
            }
            currentAttempt++
        }, intervalTime)
    })
}

const sendMessage = async (socket, msg) => {
    if (socket.readyState !== socket.OPEN) {
        try {
            await waitForOpenConnection(socket)
            socket.send(msg)
        } catch (err) { console.error(err) }
    } else {
        socket.send(msg)
    }
}
```

[Link to the GitHub gist](https://gist.github.com/ndrbrt/4fb9af2084316ac0c0f9d3c46b9f2d02)
Why is affectedRows method returning 0 in CodeIgniter?
Tags: todayilearned, codeigniter, php
Published: 2020-04-09 15:40:22

---
title: Why is affectedRows method returning 0 in CodeIgniter?
published: true
description: Tips on using the affected rows query method in CodeIgniter, and why you might be getting ‘0 rows affected’
tags: todayilearned, codeigniter, php
cover_image: https://live.staticflickr.com/2948/15331505770_346a5a81d1_b.jpg
---

After a database update or insert function, I usually use `return ($this->db->affected_rows() > 0)` and assume that true means success and false means failure. This has been going pretty well, until the other day when I was working on a reset pin functionality. 


For simplicity, we were resetting all pins to a default pin, say **pin1234**, which is also the same pin that is assigned when users are first created. 

```
function resetPin($id) {
    $this->db->set('pin', 'pin1234');
    $this->db->where('id', $id);
    $this->db->update('users');

    return ($this->db->affected_rows() > 0);
}
```

All goes well and I'm happy with my code. But wait, why am I always getting false as the result?

![Gif of confused man](https://media.giphy.com/media/KB7wTwgc58Lij6Gcv0/giphy.gif)

I made sure that the query syntax was correct, and even used `$this->db->get_last_query()` to get the query that was being run and pasted it into phpMyAdmin (yes, I still use phpMyAdmin). Curiously, when I ran it there, the result was '0 rows affected'!

![Gif of Rachel Anniston rubbing her chin with 'Hmm interesting' text at the bottom](https://media.giphy.com/media/3oKIPl97G9KsnxS3XG/giphy.gif)

After a bit more tinkering, I found out that this happens when the pin's value is _already_ **pin1234**. Because we're trying to update it to **pin1234**, it's going to say that 0 rows were affected.


![Gif of Andy Samberg nodding and saying Aha!](https://media.giphy.com/media/FG14fnY17opr2/giphy.gif)

So, how to refactor the function so we can handle this? Easy, first we get the user's current pin, and if it's equal to **pin1234**, then we can return true, because there will be no need to reset the pin. However, if the pin is _not_ equal to **pin1234**, we will update it and return the number of affected rows.


```
function resetPin($id) {
    $this->db->select('pin');
    $this->db->where('id', $id);
    $currentPin = $this->db->get('users')->result()[0]->pin;


    if($currentPin == 'pin1234') {
        return true;
    } else {
        $this->db->set('pin', 'pin1234');
        $this->db->where('id', $id);
        $this->db->update('users');
        return ($this->db->affected_rows() > 0);
    }
}
```

Thank you for reading. Until next time :wave:

_Note: I got the cover image from [Flickr](https://www.flickr.com/photos/kovah/15331505770)_
The 2 ways to use global stylesheet in Nuxt
Tags: vue, webdev
Published: 2020-04-09 15:26:01

The first way is, write any stylesheet in `layout/default.vue`. This way is very simple and good for small project. You won't need any another file.

and as alternative, you can make `style.css` file in aseets folder and import it in `default.vue`. Or, just make the file and load it in `nuxt.config.js`.

The second way is, use `@nuxtjs/style-resources`. I think this is not good way because this causes mess the project.
Setup Tensorflow.js to React Native Expo project
Tags: reactnative, machinelearning, android, ios
Published: 2020-04-09 15:06:04

```
expo init myLittleProject
cd myLittleProject
    
npm install @tensorflow/tfjs
npm install --save react-native-fs
npm install --save @react-native-community/async-storage
```
To test that everything is working replace App.js code temporary with this:
```
import React from 'react'
import { Text, View } from 'react-native'
import * as tf from '@tensorflow/tfjs'

class App extends React.Component {
  state = {
    isTfReady: false
  }

  async componentDidMount() {
    await tf.ready()
    this.setState({ isTfReady: true })
    console.log(this.state.isTfReady)
  }

  render() {
    return (
      <View style={{
	flex: 1,
	justifyContent: 'center',
	alignItems: 'center'
      }}>
        <Text>
	  {this.state.isTfReady ? "Ready" : "Waiting"}
	</Text>
      </View>
    )
  }
}

export default App
```
[https://github.com/tensorflow/tfjs/tree/master/tfjs-react-native](https://github.com/tensorflow/tfjs/tree/master/tfjs-react-native)

## Using Own Model
Create `metro.config.js` to root folder and add following content there (you might need to add some assetExts or something else but first check errors):
```
const blacklist = require('metro-config/src/defaults/blacklist');
 
module.exports = {
  transformer: {
    getTransformOptions: async () => ({
      transform: {
        experimentalImportSupport: false,
        inlineRequires: false,
      },
    }),
  },
  resolver: {
    assetExts: ['bin', 'txt', 'jpg', 'ttf', 'png'],
    sourceExts: ['js', 'json', 'ts', 'tsx', 'jsx'],
    blacklistRE: blacklist([/platform_node/])
  },
};
```
Model is trained somewhere else and it's saved using `tf.save('file://model')` It creates a directory with `model.json` and `weights.bin` inside it.

Then this model can be used in React Native (Expo) project following way:
```
import React from 'react'
import { Text, View } from 'react-native'
import * as tf from '@tensorflow/tfjs'
import { bundleResourceIO } from '@tensorflow/tfjs-react-native'
    
class App extends React.Component {
   state = {
     isTfReady: false,
     model: false,
   }
    
   async componentDidMount() {
     await tf.ready()
     this.setState({ isTfReady: true })
    
     const modelJSON = require('./assets/model/model.json');
     const modelWeights = require('./assets/model/weights.bin');
     const model = await tf.loadLayersModel(bundleResourceIO(modelJSON, modelWeights));
     model.summary();
     this.setState({ model })
   }
    
   render() {
     return (
       <View style={{
         flex: 1,
    	 justifyContent: 'center',
    	 alignItems: 'center'
       }}>
         <Text>
    	   TF: {this.state.isTfReady ? "Ready" : "Waiting"}
    	 </Text>
         <Text>
           MODEL: {this.state.model ? "Ready" : "Waiting"}
         </Text>
       </View>
     )
   }
}
    
export default App
```
Build a Python CLI Part 2
Tags: cli, python, live
Published: 2020-04-09 15:00:36

---
title: Build a Python CLI Part 2
published: true
description: 
tags: cli, python, live
---

In this cont. series we do some  refactoring, and keep hacking away in our LS utility. I also show you how to setup a task on vscode that triggers when you save a file. Happy coding!

{%youtube JFbwtXIyEHI%}
Asteroid App: Phase One
Tags: twiliohackathon, javascript, node
Published: 2020-04-09 14:57:35

For the Twilio Hackathon, I'm doing an automated WhatsApp account to which you can ask information about the closest asteroid to Earth at a particular date.

## What I have done so far

I have decided to use [Sanctuary](https://github.com/sanctuary-js/sanctuary), because some functional types (particularly Maybe) are going to be useful. It also provides a layer to declare types using Haskell notation, which is really cool. I'm not sure I'll use that part, though, as I'm not used to it. If I've got enough time, it might be cool to dive into it.

I have finished the functionality that fetches data from [NeoWs](https://api.nasa.gov/index.html#browseAPI). The most challenging part was delving through the vast amount of data that the API provides to take only what I'm interested on. I also had to create my own version of `take`, because, for some reason, Sanctuary has decided to make it return a Maybe with Nothing if you ask for more items that the list's length. So, following the way Elixir does it, I created one that returns the whole list if you ask for more elements than it has.

I have also created a module that calls [Cat Facts API](https://catfact.ninja/). If the program can't parse a user's request, instead of simply failing, it'll respond with "Sorry, I didn't understand your request, but did you know that cats' eyes shine in the dark because of the tapetum, a reflective layer in the eye, which acts like a mirror?" (or some other random cat fact).

Lastly, I have created a Twilio account and got WhatsApp running. I'm going to leave actually connecting it to my Node's endpoint until that's finished, but I can now send and receive WhatsApp messages.

## Next Steps

For the next phase, I plan on doing the following:

- Making a module to parse the user's request, i.e., reading the message that the user sends and extracting the data to make a request to NeoWs.
- Writing a function that returns a Maybe. If the parsing is successful, it'll return the data for the request to NeoWs and the next function will do the request. If it isn't, it'll return Nothing and the next function will do a request to Cat Facts.
- Put together a first draught of a readme.

It's not a whole lot, but the project is starting to take shape. Plus, investigating this Sanctuary library is proving to be quite fun.
What if CSS was imperative?
Tags: healthydebate, css
Published: 2020-04-09 14:52:46

---
title: What if CSS was imperative?
published: true
description: How can something like CSS be too easy and too difficult at the same time?
tags: healthydebate,css
---

Many developers (especially back-end developers) often dismiss web development in general (and CSS in particular) as a lesser branch of software development. I find interesting that the people that diminish it as something easy or simple are often the same people that make comments such as, "_CSS is too difficult_."

**How can something be too easy and too difficult at the same time?**

And we see it every day in web programming. New tools are created to get rid of CSS's difficulty/complexity, and those tools end up adding new layers of complexity (although maybe not in the eyes of the user.)

There are many reasons why this mismatch with CSS could happen: misconception, threat response, lack of interest, lack of understanding...

This last reason came as a realistic possibility: maybe people that are used to a more imperative language syntax have issues understanding a different type or approach to programming.

This is a declarative approach with some CSS code to add color to a post and to show/hide an element when an action (mouse over) is performed by the user:

```css
#post {
  color: blue;
}

.socialLink {
  display: none;
}

#post:hover .socialLink {
  display: block;
}
```

Imagine that you could get the same code written in a more imperative way. Say something like the pseudo-JavaScript-ish code below. It has the same number of lines, but it is quite more verbose:

```javascript
if (this.id === "post") {
  this.color("blue");
}

if (this.className === "socialLink") {
  this.hide();
  if (this.parent().id === "post") {
    this.parent()
        .addEvent("mouseover", function() { this.show(); });
        .addEvent("mouseout",  function() { this.hide(); });
  }
}
```

Ignoring performance/syntax of this pseudo-language, would you consider this more imperative approach easier?
Game: Example Gun War
Tags: codepen, vue, javascript, showdev
Published: 2020-04-09 14:35:38

<p>Example game written in VueJS</p>

<p>Description, and instruction is on the game, but I am still going to write it down here:</p>

<p>Description:</p>
<p>Test your reflexes with this game. Just fight with the AI. Dodge its fire, or shoot it with all your might.</p>

<p>Instructions:</p>
LEFT ARROW KEY : MOVE to the LEFT direction.<br />
RIGHT ARROW KEY : MOVE to the RIGHT direction.<br />
SPACE BAR KEY : SHOOT the FIRE to the OPPONENT.<br />
<p>You may also press these keys at the screen instead, to make an action.</p>

<p>Disclaimer:</p>
<p>The character is the only thing that I made here. I used the 'assets', for most of the resources I used.</p>
<p>Eg)</p>
<p>Patterns</p>
<p>Icons (For buttons)
</p>
<p>Fonts</p>
{% codepen https://codepen.io/takaneichinose/pen/xxGzdqg %}
Day- 2 Given an integer array arr, count element x such that x + 1 is also in arr. 
Tags: python, beginners, programming, discuss
Published: 2020-04-09 14:33:39

---
title: Day- 2 Given an integer array arr, count element x such that x + 1 is also in arr. 
published: true
description: 
tags: #python #beginners #programming #discuss
---
This was one of the problems in LeetCode's ongoing 30-day challenge. Published on 7th April 2020.

Given an integer array arr, count element x such that x + 1 is also in arr.

If there're duplicates in arr, count them separately.

##### Example 1:
```
Input: arr = [1,2,3]
Output: 2
Explanation: 1 and 2 are counted cause 2 and 3 are in arr.
```
##### Example 2:
```
Input: arr = [1,1,3,3,5,5,7,7]
Output: 0
Explanation: No numbers are counted, cause there's no 2, 4, 6, or 8 in arr.
```
##### Example 3:
```
Input: arr = [1,3,2,3,5,0]
Output: 3
Explanation: 0, 1 and 2 are counted cause 1, 2 and 3 are in arr.
```
##### Example 4:
```
Input: arr = [1,1,2,2]
Output: 2
Explanation: Two 1s are counted cause 2 is in arr.
```

##### Solution Approach

1. As the original list contains duplicate elements as well. Convert the list to set to get unique elements.
2. Iterate over the set and check if element+1 exists in the original list.
3. If it exists. Find the count of the element in the original list.
4. Keep adding the count to the new list.
5. Sum of all the counts. Returns the required output.

##### Code snippet

```
class Solution:
    def countElements(self, arr: List[int]) -> int:
        unique_elements = set(arr)
        L = []
        for element in unique_elements:
           if element + 1 in arr:
               item_count = arr.count(element)
               L.append(item_count)
        return sum(L)
```

Discussion on more optimized solutions are welcome.
`undefined` Does NOT Mean 'not defined' 😕
Tags: javascript, beginners
Published: 2020-04-09 14:27:54

# TLDW

`let` is a *keyword* that we use to *declare* *variables* in memory.

This may be done in the *global scope.* In that case, if we don't use the *assignment operator* `=`, our *variable* will be *bound to* the *primitive data type*, `undefined` (absence of a *value* - ironically, it itself *is* a *value!* 🤷🏽‍♂️).

We can also see `undefined` if we access a 🔑in an *object* that doesn't exist...it doesn't have a *value...*there is an 'absence of a value.'

However, if we access a *variable* in the *global scope* that doesn't exist, we are '*referencing* a variable erroneously.' That...is when we will see a `ReferenceError` with a message saying that something is `not defined`.
Is Machine Learning AI (Artificial Intelligence)?
Tags: machinelearning, ai, python, aws
Published: 2020-04-09 14:25:09

The short answer is No. Machine learning is where the traditional Statistical modelling of data meets the algorithmic and computational field of data science. Such statistical modelling has been used for a long time probably since mid 60’s or even before to model some real-world process. Actuarial modelling in the insurance industry is a good example, where a lot of data about general health, longevity, personal habits are used to model and determine insurance premiums. Statisticians and Actuaries have been doing this unsexy work for modelling for decades with none of the pomp and attention that Machine learning has been getting the last few years.

So if Machine learning is mostly about model building then why is there all the recent hoopla? Well it is not just model building based on the data, there is also some learning involved by turning the model parameters to achieve better prediction accuracy. This learning part could be somewhat thought of Artificial Intelligence since the algorithm learns on its own from the data without human intervention.

In the recent years new algorithms are being invented that create complex and computationally intensive models that are very good at detecting and parsing subtle patterns in the data. This coincided with the exponential increase in computational resources at very low cost through cloud computing. There is also an exponential increase in the data generated in fields like Biostatistics, Bioinformatics, FinTech etc that started exceeding existing means of analysis. This troika of events precipitated in bringing Machine Learning to the main stream. Researchers and Data Scientist from these diverse disciplines started looking at Machine learning to help them in their data analysis and classification tasks. The advent of sites like Kaggle, brought open competitions into the world of data modelling and it really helped machine learning take off.

We at Optisol, are building a team of data analysis and machine learning experts to satisfy our customers growing need for analyzing and classifying their data and build data centric decision support practices. It has been an interesting journey for us in the last one year and we are excited about the prospects of this interdisciplinary blend of Statistics, Computation and Data to answer our customer’s questions.
hCaptcha instead of Google's reCaptcha
Tags: captcha, privacy, spam
Published: 2020-04-09 13:49:23

---
title: hCaptcha instead of Google's reCaptcha
published: true
description: Moving away from Google's reCaptcha to a more privacy friendly alternative.
tags: captcha, privacy, spam
cover_image: https://dev-to-uploads.s3.amazonaws.com/i/mihwum5ri939ybg0pszz.jpg
---

[CAPTCHA](https://en.wikipedia.org/wiki/CAPTCHA) means _Completely Automated Public Turing-test to tell Computers and Humans Apart_. It is a vital feature to keep spam bots away from your site.

Years ago everybody wrote their own system, usual a picture containing an obscured word or number. But technology of the spammers also improved and these methods would no longer stop them. Some smart people invented reCAPTCHA, which was based on solving problems computers were not really good at. As with most useful and popular technology this was bought by a large tech company, in this case Google.

We all know Google and their primary business: selling advertisements. One of their ad-platform's major selling point is targeted advertisements based on information they harvested about the website visitors. 

If you want to run a privacy minded website you obvious want as little technology on which invades on your visitors privacy. There are many [alternatives for various Google products](https://restoreprivacy.com/google-alternatives/). 

On one of my websites I removed Google Ads, because I did not earn much from it anyway. I removed Google Analytics, because I was not looking at it anyway. But, I was still using reCAPTCHA to fend of spammers. 

Yesterday I saw a [blogpost from Cloudflare](https://blog.cloudflare.com/moving-from-recaptcha-to-hcaptcha/) on how they moved from reCAPTCHA to hCaptcha. So there is also an alternative for the last Google product I had on my site. Today I started all the work to move to hCaptcha.

[hCaptcha](https://hcaptcha.com/?r=bb3dd94fa5e7) is basically the same as reCAPTCHA, with some major differences:

* They respect the privacy of your visitors.
* The problems visitors solve are not for the benefit of a single company.
* You can earn money, or donate it, by visitors solving these problems.

So now the difficult part: moving away from reCAPTCHA to hCaptcha. All the steps you need to perform to convert are [detailed in the documentation](https://docs.hcaptcha.com/switch). It basically required me to perform _three_ replace-all actions, and updating two settings to covert my existing reCAPTCHA implementation to hCaptcha. I think it cost me almost 30 minutes to execute and verify! Yes, it took me more time to write this article.