teleren/devto huggingface dataset:
Odd Shuffling ( binary search variation)
Published: 2020-09-17 07:40:29

Problem Statement - 
> In a sorted array, the odd indices are divided in two parts. Elements on left are swapped with elements on right. We have to search for index of a given number in that array.

Example - 
"""
 A = [1, 6, 3, 4, 5, 2]
 B = 5
Ans = 4
"""

To Find = index of B.
Approach - We need to solve it in logN. So, we need to use binary search. But, it applies only on sorted arrays.
So, we apply binary search on even indices as they are sorted and try to find B or the number closest to B.

 case 1: We are able to find B. 
We return the index.
case 2: We are not able to find B.
So, we find the number next to our result. This is where B should reside in a sorted array. so, If that's equal to B we return it else, the number we found is the one that got swapped with B.
`to_find = A[ans + 1]`
 So, we try to do binary search over even indices and find to_find.
Again, If A[ans] = to_find we return it, else we check for + 1 index.
Solution
```
class Solution:
    # @param A : list of integers
    # @param B : integer
    # @return an integer
    def solve(self, A, B):
        lo = 0
        hi = (len(A)-1)//2
        ans = float('-inf')
        ans_idx = None
        # first search over all even indices
        while lo <= hi:
            mid = (lo + hi)//2
            if A[mid * 2] == B:
                return mid * 2
            else:
                if A[mid * 2] > B:
                    hi = mid - 1
                else:
                    ans = max(ans, A[mid * 2])
                    ans_idx = mid * 2
                    lo = mid + 1
        if A[ans_idx + 1] == B:
            return ans_idx + 1
        to_find = A[ans_idx + 1] # this is the number that was swapped
        # in binary search try to find, this smaller or larger number.
        lo = 0
        hi = (len(A)-1)//2
        ans = float('-inf')
        ans_idx = None
        # first search over all even indices
        while lo <= hi:
            mid = (lo + hi)//2
            if A[mid * 2] == to_find:
                return mid * 2
            else:
                if A[mid * 2] > to_find:
                    hi = mid - 1
                else:
                    ans = max(ans, A[mid * 2])
                    ans_idx = mid * 2
                    lo = mid + 1
        # print('ans', ans_idx, to_find, ans)
        if A[ans_idx + 1] == B:
            return ans_idx + 1
        return - 1
        
```
Sharing keyboard & mouse across devices
Tags: linux, sharing, keyboard, mouse
Published: 2020-09-21 05:41:20

As programmer, I often juggle between multiple computer systems, for various purposes. Personally, I own a Macbook Air, a Linux desktop and a Windows laptop from my office. Quite often I am juggling between all the three machines, moving my hands from one keyboard to another, a tedious and boring task. So I was googling for how to share single keyboard & mouse across devices. There were several paid solutions, but I was looking for a free and open source solution. That’s when I found out BARRIER.

The fantastic part about BARRIER is that it is available for Linux, Mac & Windows and can work across the combination of the OS. So, here is the procedure to setup BARRIER.
- Visit the Github BARRIER page — https://github.com/debauchee/barrier
- Based on the operating systems on your machines, download the appropriate versions and run the installer. If you are using Linux, use snap
- sudo apt-get install snap snapd -y
- sudo snap install barrier
- Logout and login again

Start barrier first on the machine from where you want to share the mouse & keyboard. Choose to run barrier as server. It might take a while to boot up.

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

Now start Barrier on the machine(s) where you want to use the shared keyboard & mouse and click start. It will take a while for barrier to connect with server. First it will ask for confirmation about verification of the server finger print. Allow it.

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

The important thing to remember is that **Screen name** plays an important role here. Go back to Barrier server and click on configure. From the right top corner, drag the icon to the desired position in the grid. Rename the newly dropped icon to the same name as of the client. Save the settings and click reload for server.

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

When the client(s) are connected to the server, you see a connection successful notification. Wallah, now you can use the keyboard & mouse from your server device across the mesh of devices.

That’s all folks.

**EDIT**: *The clipboard is shared across the devices.*

Originally published at [https://vishalraj.blog](https://vishalraj.blog/sharing-keyboard-mouse-across-devices/) on September 21, 2020.
Docker Images to Heroku
Published: 2020-09-21 05:38:25

Hey Devs,

So I was wondering how to push my docker image to Heroku.
Turns out it wasn't that hard.
Below is a walk-through of what I did.
 
So for the starters, I created an express app.
```
mkdir express-docker-up
cd express-docker-up
git init
npm init -y
npm install --save express
```
Never forget the .gitignore file to keep the node_modules folder out of you git history. (If the your machine's node_modules get cloned to a different machine, errors may dial in)
```
/node_modules/
```
add the index.js
```
const express = require('express')
const app = express()
const port = process.env.PORT

app.get('/', (req, res) => res.send('Hello World!'))

app.listen(port, () => console.log(`Example app listening on port ${port}!`))
```
Create the Dockerfile
```
FROM node:10-alpine
WORKDIR /app
COPY package.json .
RUN npm install
COPY index.js .
CMD ["node", "index.js"]
```
Create the heroku.yml
```
build:
    docker:
      web: Dockerfile
```
Let's start working on heroku now
```
heroku login
```
If you don't have a pre-made app, create one
```
heroku create
```
Set the stack as container for the app
```
heroku stack:set container --app APP_NAME
```
now to commit and push
```
git add .
git commit
```
Don't forget to give a meaningful commit message
Check if heroku is present in your remote
```
git remote
```
If not, make sure you have the heroku remote set
```
git remote set heroku <heroku git repo(check your app settings on the web)>
```
OR
```
heroku git:remote --app APP_NAME
```
And now push
```
git push heroku master
```
Now you wait, and when it's done, just go to the app url.
Voila!

I've uploaded this code to my [github](https://www.github.com/anuj97/express-docker-up)
Laravel Clear Cache Using Artisan
Tags: laravel
Published: 2020-09-21 05:32:44

In This tutorial Simply clear cache from the command line (CLI). we will discuss how to clear cache from blade (views), routes, config, etc using the (CLI) and artisan command.

we need to make cache in laravel projects for better completion. But if our application is development mode then what we want to get cured due to the cache. Then this time we need to clear the cache.
```
//Clear route cache:
 Route::get('/route-cache', function() {
     $exitCode = Artisan::call('route:cache');
     return 'Routes cache cleared';
 });

 //Clear config cache:
 Route::get('/config-cache', function() {
     $exitCode = Artisan::call('config:cache');
     return 'Config cache cleared';
 }); 

// Clear application cache:
 Route::get('/clear-cache', function() {
     $exitCode = Artisan::call('cache:clear');
     return 'Application cache cleared';
 });

 // Clear view cache:
 Route::get('/view-clear', function() {
     $exitCode = Artisan::call('view:clear');
     return 'View cache cleared';
 });
```
[laravel clear cache](https://www.phpcodingstuff.com/blog/laravel-clear-cache.html)
Bulk updating MongoDb documents
Tags: mongodb, database
Published: 2020-09-21 04:40:48

Just like SQL Mongo also has a bulk update command. It's as simple as - 
```
db.getCollection('<name>').bulkWrite
([
    {
        updateOne:
        {
           filter: {<your-condition>},
           update: {<what-you-want-to-update>
        }
    }
]);
```
And the updateOne block can be repeated "n" times.

If you are trying to update from an excel file, use the CONCATENATE().

Here is a sample - 

```
=CONCATENATE("{updateOne:{filter:{","'brands.brandId'",":'",E2,"'},update:{$set:{","'brands.$.image'",":'",F2,"'}}}},")
```

I have values in E2 and F2 columns. 
Note: Don't forget the last comma in the CONCATENATE(). Since bulkWrite() accepts an array, it will need the jsons comma separated. 




Happy coding :D
The Mysterious React hook: useRef() 
Tags: react, codenewbie, beginners, html
Published: 2020-09-21 02:33:22

**useRef()** hook is used to create references (or refs in short) in functional components of React.
Yes, that’s it, you can stop reading now (just kidding). 

In this article, I’ll briefly explain what a **Ref** is, what it can do and how to use it without making it much complex.


As per the definition from Reactjs official docs,
> Refs provide a way to access DOM nodes or React elements created in the render method.

This is the best definition anyone can give about refs but let me put it even more simply. 

> Refs let you target any HTML or React element just like the *id* attributes. 

Though refs are slightly different and more convenient in some cases.


* Now Let’s see where to assign ref and how does the **useRef** hook helps us:
As I said earlier, it works like ids so you can put it in a div element like the ids: `<div ref={myTarget} />` but why am I using curly brackets instead of strings like we use while assigning ids to elements: `<div id='mytarget' />`?
The reason is self-explanatory, we are passing that *myTarget* as a variable into the ref. This variable is like a name to that particular div element and will help us target it later. Now you might ask that we haven’t defined any variable named *myTarget* then what are we passing? 
Well then let’s define that variable but a little trick here. You cannot just define any variable and pass it to ref (like const ref = something) because when we pass a variable to ref, it needs to be created specially just to be used in ref. But how do we create a special variable like that? This is where the hook **useRef** comes in. We use this hook to create our special variable and also assign it an initial value of null as shown in the image. 


* We have created our ref, time to use it:
To target our beloved element, we use a property called *current* which acts like an indicator or a signal that tells us whether our targeted element is painted (or loaded) in the DOM or not. We will add an if else condition in useEffect to check that and then do whatever magic we want.
There are a bunch of things you can do after targeting an element once the DOM loads like adding some animation to that element or if it is an input element then you can add a property called *focus* to it and it will focus on that input. This comes handy when you want a user to navigate to a form to fill their names once they visit your website or something else. You can also use many third party libraries in it. Here is an image showing the code for whatever I've explained so far.
![Alt Text](https://dev-to-uploads.s3.amazonaws.com/i/cfx0xxjvezztce7cf3i7.png)

Hope this article helped you understand the use of ref attribute and **useRef** hook in React. I am leaving some links down here in case you want to explore more. 
Happy Coding.


[Reactjs docs](https://reactjs.org/docs/refs-and-the-dom.html)
[CSS-tricks article](https://css-tricks.com/working-with-refs-in-react/)
How to make VS Code read dotenv file when debugging
Tags: vscode, debug
Published: 2020-09-17 06:11:33

---
title: How to make VS Code read dotenv file when debugging
published: true
description: How to use a dotenv file when debugging
tags: vscode, debug
---

Today I got stuck trying to figure out why the JS-debugger in Visual Studio Code didn't pick up my environment variables. I use the [dotenv-package](https://www.npmjs.com/package/dotenv) when running Node outside of its Docker-container, so somehow adding `-r dotenv/config` to the command being executed seemed like the obvious solution.

It turns out the correct way is through the `envFile` attribute in the task configuration. This is how my task configuration looks now:

```json
{
  "version": "0.2.0",
  "configurations": [
    {
      "type": "node",
      "stopOnEntry": false,
      "envFile": "${workspaceFolder}/.env",
      "request": "launch",
      "name": "Launch Program",
      "skipFiles": ["<node_internals>/**"],
      "program": "${workspaceFolder}/src/app.js"
    }
  ]
}

```

I thought this should be mentioned with the most common examples in the docs so I created a [Pull Request](https://github.com/microsoft/vscode-docs/pull/4027) to add this.
Offline form file-format
Tags: data, forms, beginners
Published: 2020-09-21 02:31:44

so I don't really know anything about coding but I was wondering if there was a way to create a form type file format but offline -not hosted like several online forms- where you collect answers to a question as text or images.
and I was thinking it should be graphically customizable and easy to make (drag and drop or graphic/vector design) just like a pdf but with space for input like forms, so it can be downloaded.

or if that type of thing already exists.
Bootcamp Java Developer Day #1
Tags: java, bootcamp
Published: 2020-09-21 02:14:28

Today I started a [Bootcamp Java Developer](https://web.digitalinnovation.one/track/java-developer).

The track contains video courses and challenges and I must complete it until 19th November 2020. I'm going to report my accomplishes here in the dev community.

#### Day 1:

##### 1) Completed: Welcome 
I completed the first course which is actually just an introduction to the website and its features.

##### 2) Completed: Programming Logic Essential
It is an introduction to **programming logic** and **algorithms**. It teaches how to created **flowcharts** using [Flowgorithm](http://www.flowgorithm.org/). I've already knew how to organize algorithms as flowcharts, but I liked to learn about the Flowgorithm software. It is easy to use. It also introduced the concept of **pseudocode** and used [**Portugol**](https://github.com/UNIVALI-LITE/Portugol-Studio/releases), a software to write and run pseudocode in Portuguese. I've studied a little the book Introduction to Algorithms by Thomas H. Cormen, Charles E. Leiserson, Ronald L. Rivest, and Clifford Stein but I used to write the pseudocode in English and coded it in python.

##### 3) Completed before: Introduction to Git and Version Control
I have completed this course months ago. This course covers very little about **Git** and **Version Control**. I took a course on Git & Github last year by Bibhash Roy and it was more complete. You can find a similar course at [udemy](https://www.udemy.com/course/git-basic-concept-fundamentals-github/).

##### 4) Completed before: Introduction to Github and Commands to work in a team.
I have also completed this course on **github** months ago. Bibhash Roy covers github as well.
Passing Props in React
Tags: react, codenewbie, webdev
Published: 2020-09-21 02:09:42

Somehow, I seem to have lost access to my old blog on this topic that I had posted up through my school's website (during the program), but no sweat!  Here we go again, a quick little explanation on getting started with using props in React. 

##What Are Props?

Props (aka "properties") in React allows us to pass values from a parent component down to a child component.  The values can be any data type, from strings to functions, objects, etc.

Components cannot change their props - this can only be done externally, as the parent component changes the values passed down.

*(Components also have values called state, but unlike props, state is directly initialized and managed by the component itself.)*

##How to Create a Prop

In order to pass props to a component, we need to add them as attributes when rendered.  They are written the same way as writing attributes for an HTML tag. 

```
const catName = "Pusheen"
<Cat name={catName} />
```

With the above code, the `<Cat>` component now has access to a prop/value of `name` that is set to the string "Pusheen".  The prop name can be anything, just like you can give a variable just about any name.  In this case, the prop's variable name has been declared as `name`.

##Passing Props

This is how we can access the `name` prop in our `<Cat>` component: 

```
const Cat = (props) => {
  return (
    <div>
      My name is {props.name}.
    </div>
  )
}
```

Be sure to pass `props` as an argument to the entire functional component first.  When referencing a prop, it must be in curly braces.

If we are passing the prop to a class component, it will look slightly different. 

```
class Cat extends Component {
  render() {
    <div>
      My name is {this.props.name}.
    </div>
  }
}
```

[Click here for the documentation on React Components and Props](https://reactjs.org/docs/components-and-props.html)

I hope this helps simplify the basic usage of props!  

Feel free to comment any suggestions you may have to help improve this post.  (  ^_^  )
Where's the disconnect? 
Tags: thestruggleisreal, learningishard, justkeepswimming
Published: 2020-09-21 01:29:31

Today's struggle:  I totally understand everything as i learn it - I swear.  But somehow I can't quite manage to transfer that knowledge into active problem solving.  Or at least not in timed situations.  Maybe I'm a bad test taker, I honestly don't remember it's been so long since I was in school.  
I comfort myself with the knowledge that I can and have written functional programs so I must be retaining something... but it's still frustrating.
Context API preventing rerenders?
Tags: node, react
Published: 2020-09-21 00:51:26

Hello All,

I am no react wizard and would appreciate some help please. I have tried googling but the answers arent exactly what I need or bit cryptic to me.

Using the context api. I have one function that calculates a value and a functional  component to display the value. The functional component uses the useContext hook to get access to state and functions.


Do i simple using react.memo inside where the calculate function is or do i useMemo hook in the component? not sure how context api works with this.

appState where I have my functions I export provider with values added as object
``` 
return (
    <AppContext.Provider
      value={{
        output: state.output,
      }}
    >
      {props.children}
    </AppContext.Provider>
  );
};
export default CalcState;
```

because the values are in an object does that mean i have to use useCallback?
specify image-repository fo kubeadm
Published: 2020-09-21 00:37:14

    --image-repository=registry.cn-hangzhou.aliyuncs.com/google_containers

add a trailling slash in the url like 

    registry.cn-hangzhou.aliyuncs.com/google_containers

will cause failure

> failed to pull image "registry.cn-hangzhou.aliyuncs.com/google_containers//kube-apiserver:v1.19.2": output: invalid reference format
Living alone, how do you cope up with anxiety, depression and stress from work or from the current events?
Tags: discuss, webdev, productivity, career
Published: 2020-09-21 00:34:18

A few days ago my roommate just moved back to their province and I'm the only one left now. I'm used to living alone but not in this kind of situation where I'm limited on things that I can do like going outside to unwind or go to the mall, eat in a restaurant, see some of my friend, play outdoor sports.

Lately I find my self having hard time going to sleep at night, I'm having panic attacks which I didn't experienced before, worrying about things, getting sick and hard to focus at work. I'm worried that this can affect my performance in my current job.

Any advice on how to cope up in this kind of situation? Thank you keep safe and God Bless!
How to setup your domain w/Netlify when using a externally hosted backend
Tags: netlify, heroku, digitalocean, domains
Published: 2020-09-21 00:32:38

---
title: How to setup your domain w/Netlify when using a externally hosted backend
published: true
description: 
tags: netlify, heroku, digitalocean, domains
//cover_image: https://direct_url_to_image.jpg
---

So let's say you've [deployed your front-end to Netlify](https://dev.to/easybuoy/setting-up-domain-with-namecheap-netlify-1a4d) and you're going to host your backend on a Heroku / [DigitalOcean](https://m.do.co/c/f139fbacd4fc) type of setup. It's a pretty easy process, and only gets easier the more you do it.

The basic idea is that you're going to create a sub-domain and tell it where to look to find your backend. A sub-domain is anything extra before your domain, like ``api.yourdomain.com`` or ``store.yourdomain.com``.

What we're going to need is the IP of your backend server to tell Netlify where to route your sub-domain. Inside of your control panel at Heroku or [DigitalOcean](https://m.do.co/c/f139fbacd4fc) you will need to add the domain to your server. I am using [Hatchbox.io](https://hatchbox.io) to deploy my Rails API's so I'll add my domain there.

![Hatchbox domain](https://dev-to-uploads.s3.amazonaws.com/i/9iew63vu5nosatb4qhbh.png)

Now that we have the IP address of the server, let's go in to your Netflify DNS Panel and we'll create a new record connecting them.

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

Let's create the A record and then you'll be all setup.

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

You'll need to determine how you're going to set your SSL certs up, but that another topic for another day.
Client.Timeout exceeded while awaiting headers in docker pull 
Tags: docker, k8s
Published: 2020-09-21 00:28:51

# systemctl edit docker

```
[Service]
Environment="HTTP_PROXY=http://USER:PASSWD@SERVER:PORT/"
Environment="HTTPS_PROXY=http://USER:PASSWD@SERVER:PORT/"
```

systemctl daemon-reload
systemctl restart docker
tsParticles Documentation Website
Tags: showdev, news, javascript, html
Published: 2020-09-21 00:12:00

Finally, the documentation website is shaping the way it should, or at least how I imagined it.

It's still far from being completed since many classes and interfaces need some documentation and more pages are needed, like how to create plugins, how to use react templates, or others.

[![Website Preview](https://dev-to-uploads.s3.amazonaws.com/i/0mpiwwcckpdu9ywsu78i.png)](https://particles.js.org)

If you want to see it working click the link below:

<https://particles.js.org>

The particle configurations are randomly picked so try refreshing the page.

If you have some cool ideas or want to contribute to adding documentation or fixing broken things you are welcome in the project.

{% github matteobruni/tsparticles %}

If you like the `typedoc` template you can find it here

{% github tsparticles/typedoc-particles-theme %}

You are welcome to contribute to that project too!

And remember to leave a star, the 1k star goal is really near!
100 Days Of Code | Day 1
Tags: 100daysofcode, javascript, beginners, productivity
Published: 2020-09-21 00:01:35

Hello Everyone,

I arise from my quarantine cave, after finally beating the old & ugly monster of procrastination, with my mechanical keyboard. Today is the day I start making an impact in the programming community.

Before we get this show on the road, I must come clean, the people deserve it. I've been coding consistently for about 6 months...

So even though I'm technically not a beginner I po·sess a beginner mentality, so hopefully, some of you don't throw me to the wolves. (joking about the wolves part)...

On my first day of the 100DOC challenge, I decided to start on improving my JavaScript fundamentals. I reviewed some core concepts and wrote down what concepts I forgot, and are difficult for me.

JavaScripts Fundamentals Practice

Current Weaknesses
Methods - Math.floor, Math.Random, indexOf(), 
Functions - Helper Functions, Function Expressions,  Helper Functions, Default parameters