teleren/devto huggingface dataset:
ssh and 'warning: setlocale: LC_CTYPE: cannot change locale (UTF-8): No such file or directory'
Tags: linux, ssh, osx
Published: 2022-05-22 09:58:06

This post is about an issue that upon googling today seems to be quite widespread, and there's a lot of confusion about it. I think I have built a fairly good understanding about it, so to hopefully take away some of the confusion, I have created this blogpost.

This post is about when you encounter the following dreaded line after applying an update on Mac OSX when logging into a linux system with ssh:
```
warning: setlocale: LC_CTYPE: cannot change locale (UTF-8): No such file or directory
```
This is just a message, and it allows you to carry on. However, much that uses "locales" (language specifics) can stop functioning, or generate errors. This is the confusing bit: because it doesn't immediately stop you from your work, any actual crashes (such as perl crashing) might seem random.

I did encounter did for the first time when I was doing patching at a client. Patching meant things go down, and therefore are time-sensitive. So that was really frustrating. I did find the root cause, and provided this with the vendor which software I was patching, who then put it in its non-public issue database, and the support engineer who didn't do anything took credits for it.

So, what is happening here? This is happening because of ssh (secure shell) mechanisms allowing lots of flexibility about how a session is created on a remote server, and some settings which gets reverted on patching OSX. Let's look at the message again:
```
warning: setlocale: LC_CTYPE: cannot change locale (UTF-8): No such file or directory
```
LC_CTYPE makes linux try to set something. Let's query the environment for LC_CTYPE:
```
$ env | grep LC_CTYPE
LC_CTYPE=UTF-8
```
So that is the reason. But how come this seems to be set all of a sudden? 

The reason is the ssh client, and a ssh setting called 'SendEnv', which allows you to send environment settings along with logging on to a remote ssh server. 

So why does this pop up all of a sudden? The reason is there is a global ssh _client_ settings file on mac at `/etc/ssh/ssh_config`. Every time OSX is updated, this file gets rewritten. Well, to be very precise: I do not make changes to this file, at least the global host declaration (`Host *`) is changed to send the environment variables LANG and all LC ones: `SendEnv LANG LC_*` upon OSX update. Every single update.

How to solve it? The only viable solution I have found so far is to simply remove `LC_*`, so the line in `/etc/ssh/ssh_config` becomes: `SendEnv LANG`.

There is a user-specific ssh_config file to in `~/.ssh/config`, but using that file it only seems to be possible to add environment variables to `SendEnv`, not remove them. 

Please mind there also is a file called `/etc/ssh/sshd_config`, that is the sshd (daemon) configuration, so the configuration of a local OSX ssh server, and thus NOT the settings for the client.
Use These Formats for Smaller File Sizes and Excellent Read/Write Performance.
Tags: programming, datascience, python, tutorial
Published: 2022-05-22 09:55:35

You'd soon regret it if you're using CSVs. I did!

Pickle files aren't perfect either. Perhaps a little better than CSVs.

What we truly need is one that takes little storage space on the disk. Yet it should take the shortest time to read and write on the disk.

They do exist. 

[CSVs Are Overrated! Use These Alternatives for Smaller File Sizes and Excellent Read/Write Performance.](https://towardsdatascience.com/best-file-format-to-store-large-data-dfa47701929f?sk=baa8b8bb5b35b52cefef81e6b61f4c97)
PWA (mobile) app: Read configuration from QR code
Published: 2022-05-22 09:44:54

_This is my 2nd write up on dev.to site. This article shows proof-of-concept, fully working with Chrome on Android._

## A small background
I am a fan of mobile apps, I have developed a few apps (HTML + CSS + JS) using Cordova in past. One day i found out that there are [PWA applications](https://www.google.com/search?q=pwa) and since then I have loved them. Now I write apps as PWA/SPA ones using [Quasar framework](https://quasar.dev/).

## Apps need settings
As I have developed apps, some of them used configuration, often using dialog box. So, user fill/change configuration via standard dialog.

Sometimes I need special configuration of app (not related to user). Instead of fill API keys (or similar _strange_ text string) manually we can use QR code. It assumes that we use QR library to mane reading QR code. And the app grows...

But wait! Many of us have **QR reader app** already installed on mobile phone. So, can we use it as an external source via clipboard? Yes, we can. :-)

Just scan QR code using external QR reader app, it stores text/config/whatever to clipboard. 

## Paste from clipboard

Nothing new, nothing fancy, yawn. One button and a function called on click event. And that's it!

vanilla JS code:
```
async function paste(input) {
  const text = await navigator.clipboard.readText();
  input.value = text;
}
```

VueJS code:
```
pasteFromClipboard: async function(){
  const text = await navigator.clipboard.readText();
  this.textFromClipboard = text;
}
```
_Hope this help you :-)_
JavaScript Function
Tags: javascript, function, functiondeclarations
Published: 2022-05-22 09:40:22

## **Function Declarations**

```
function myFunction(a,b){
    return a*b;
} 
console.log(myFunction(3,4)); 

```

`function myFunction(a,b){
    return a*b;
}`
Here  this portion is a declaration that's why don't use any semi colon(;)

`console.log(myFunction(3,4));`

This portion is function execution ( an statement) , that's why we are using semi colon(;)
Customizing Input Capitalize From Buffer Text-Form When Using Keyup Event
Published: 2022-05-22 09:12:41

Sometime we need input value to form Capitalize when client type like for input client name, we can use regex and combine it with JS event key. But the thing is the key event only keyup we can use, it because when key have been lifted and the new value is formed. If we use other key event (keypress or keydown) the value shown are the old value. But by using keyup event it mean our browser need to wait what char has been type then form into capitalize, and there is some buffer time that is when we type a capital letter on word we want to create that should be lowercase it will show a Capital latter first then turn it into lowercase, this is the buffer what we talk about. What we want is to form without any buffer, so the only solution is only keypress or keydown when we form it.

The keypress is will fire after keydown so we chose keydown event.

1. Filter only alphabet and space are allowed using regex

2. Get position of cursor in a input box 

3. If next or prevouse cursor position is a space char and we type a space char then abort it

4. Check is control key is still down or the input value is on block mode if it is then abort it

5. add a new char into text value and set the new value and form capitalize 

6. dont forget if the control is up or what client type is not combination of key (shortcut key) then prevent from adding new value.

```
function ucwords(string, trim = true) {
    if (string == null) {
        return '';
    }
    let str = string;
    if (trim) {
        str.trim()
    }
    return str.toLowerCase().replace(/\b[a-z]/g, function(letter) {
        return letter.toUpperCase();
    });
};

const inputName = document.getElementById("input-name");
let ctrl;
inputName.addEventListener("keyup", function(e) {
    if (e.key == "Control") {
        ctrl = "up";
    }
});

inputName.addEventListener('keydown', function(e) {
    let pattern = /^[^a-zA-Z\s]+$/;
    let ceretS = e.target.selectionStart;
    
    if (pattern.test(e.key) === true) {
        e.preventDefault();
        return false;
    }

    if (e.code == 'Space' && e.key == ' ' && (this.value.substring(ceretS, ceretS+1) == ' ' || this.value.substring(ceretS, ceretS-1) == ' ')) {
        e.preventDefault();
        return false;
    }

    if (e.key == 'Control' || ctrl == 'down' && e.code.indexOf('Key') >= 0) {
        ctrl = 'down';
        return false;
    }

    if (e.code.indexOf('Key') >= 0 || e.code == 'Space') {
        if (this.value.length > 0 && ceretS == 0 && e.target.selectionEnd == this.value.length) {
            return false;
        }
        this.value = ucwords(this.value.slice(0,ceretS) + e.key + this.value.slice(ceretS), false);
        e.target.selectionStart = ceretS+1;
        e.target.selectionEnd = ceretS+1;
        if (ctrl != 'down') {
            e.preventDefault();
            return false;
        }
    }
});
```
How to Rotate a String in JavaScript
Tags: javascript, beginners, interview, programming
Published: 2022-05-22 09:10:59

Recently, I applied a job in a certain company that was hiring a React developer. I sent my CV, did a coding assessment and passed. After this I was invited for an in-person interview where I was required to write code on paper.

The coding problem was: **write code in the programming language of your choice that rotates a given string a specified number of times**.

At first I freaked out as I had not tackled such a problem before, keep in mind that I am not a guru. I took the pen and paper and started writing code.

After struggling for a few minutes, I was able to write code for positive number rotation but I didn't know that they also required the code to also handle negative number rotation and my time was up. 

Anyway, I was able to solve the negative rotation part in my mind on my way home and I want to share it here in case you ever encounter such a problem.

Here's is the JS code to rotate a string(handles both left and right rotation):

```js
const rotate = (text, n) => {
  txtArr = text.split("") 
  
  if(n>0){
    for(let i = 1; i<=n; i++){
      let firstel = txtArr[0]
      txtArr.shift()
      txtArr.push(firstel)
    }
  }
  else if(n<0){
    for(let i = -1; i>=n; i--){
      let lastel = txtArr[txtArr.length-1]
      txtArr.pop()
      txtArr.unshift(lastel)
    }
  }
  
  console.log(txtArr.join(""))
}

rotate("hello", -2)
```

### Code explanation:

I will explain the code with the steps involved:

1. Convert the text into an array using the `text.split()` method.
2. Use an `if` statement to check whether `n` is positive, `n>0`.
3. If `n` is positive:

- use a `for` loop to loop through the `textArr` `n` times.

- get the first element in the array using `txtArr[0]`

- Remove the first array element using `txtArr.shift()`

- Add the first array element to the end of the aaray using `txtArr.push(firstel)`

4.If `n` is negative:

- use a `for` loop to loop through the `textArr` `n` times.
      
- get the last element in the array using `txtArr[txtArr.length - 1]`

- Remove the last array element using `txtArr.pop()`

- Add the last array element to the beginning of the aaray using `txtArr.unshift(lastel)`

5.If `n` is equal to 0, return it as it is

## Conclusion
That's all for this article. Hope you learn a thing or two. See you in the next one :)
100 Days of Code: The Complete Python Pro Bootcamp for 2022 - Day 16 (Object Oriented Programming)
Published: 2022-05-22 09:10:29

- I imported the code as provided by the course and all I needed to do was complete this project using OOP instead of Procedural Programming. This was a carry on or next step for the original Coffee Machine Maker for Day 15

```python
from menu import Menu, MenuItem
from coffe_maker import CoffeeMaker
from money_machine import MoneyMachine

menu = Menu()
menu_item = MenuItem('name', 'water', 'milk', 'coffee', 'cost')
coffee_maker = CoffeeMaker()
money_machine = MoneyMachine()
is_on = True

while is_on:
    options = menu.get_items()
    choice = input(f"What would you like? ({options}): ")
    if choice == "off":
        is_on = False
    elif choice == "report":
        coffee_maker.report()
        money_machine.report()
    else:
        drink = menu.find_drink(choice)
        if coffee_maker.is_resource_sufficient(drink) and money_machine.make_payment(drink.cost):
            coffee_maker.make_coffee(drink)
```
Javascript tips
Tags: javascript, webdev, programming, css
Published: 2022-05-22 09:05:08

Below are some of the tips in javascript and html.


html select
`<select>
  <option value="" selected disabled hidden>Choose here</option>
  <option value="1">One</option>
  <option value="2">Two</option>
  <option value="3">Three</option>
  <option value="4">Four</option>
  <option value="5">Five</option>
</select>`

String functions
`key = chart_id.split("_");
chart_name = key[1];
if(char_name.includes("val_"))
{
}`


For loop - alternate elements (even and odd)
`for(var i=0; i< arr.length; i++)
{
   if(i%2 == 0)
   {
   }
   else if(i%2 != 0)
   {
   }
   else
   {
   }
}`
Slice function
`coars.slice(0,val_count);  // not inclusive of the end
`

div updates and removal
`$('#myCharr').update()
$('#myCharr').remove();`

lambda function
`keys = key.map((x) => x);`


Handling Data tables and wildcard query selector
`$(document).ready(function() {
    $('#example').dataTable();
} );
$("table[id^='Table_']")`


Object.keys iterating through dictionary keys and values
`for (var i = 0; i < Object.keys(params).length; i++) {
	count_params[Object.keys(params)[i]] = 0;
}`

Query selector for event listener and accessing value

`$('button[id^="charts_"]').on('click', function (event) {
});
document.getElementById('dataframess').value;`


Sort the array with the index to find out the sorted order
 `function sort_with_index(test)
{
var test_with_index = [];
for (var i in test) {
	var y = test[i];
	if(y=="")
	{
		y="100";
	}
	else
	{
		y= String(y);
		y = y.substring(0, y.length - 1);;
	}
	////alert("y"+y);
    test_with_index.push([parseInt(y), i]);
}`


dynamic url href and clicking on it
`var a = document.createElement('a');
a.download = 'roles_org.png';
a.href = base64_url;
a.click();`	


highlighting the text in a table
						   `$("#display_table").mousedown(function (event) {
mouseXPosition = event.pageX; //register the mouse down position
	                       });
$("#display_table").mouseup(function (event)
 {				   
target = event.target.id;							   
var highlighted = false;
var selection = window.getSelection();
 var selectedText = selection.toString();				   alert("selectedText"+selectedText);
							   }`
							

mark for highlighting

`<mark style='color: white; background-color: "+colored+";'>" + selectedTexts + "</mark>`
Linked List
Tags: algorithms, beginners, programming, uz
Published: 2022-05-22 09:00:56

- **Linked Lists** - bu ketma-ketligi xotiradagi joylashuviga bog'liq bo'lmagan `chiziqli` ma'lumotlar `to'plami`.

- Ro'yhatning har-bir elementi keyingi elementga `ishora` qiladi.

- Ma'lumotlar tuzilmasi sifatida LinkeListni bir-biriga `bog'langan tugunlar` ko'rinishida tasavvur qilamiz.

- Har bir tugun o'z `qiymatini` va keyingi element `manzilini` saqlaydi.


![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/yjyrd700do93ye0mr71k.png)
`oxirgi element null`

![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/jpoeay7nifq2oawe19op.png)

- Arrayning - har-bir elementi xotirada ketma ket joylashgan bo'lishi kerak.
- LinkedList - hohlagan bo'sh joyda joylashaveradi , har bir element o'zidan keyingi elementning manzilini saqalaydi.

> Linked Listda biz 4- yoki 5- elementni o'qish uchun biz birinchi elementdat boshlab o'qib chiqishimiz kerak , chunki 4- elementning manzili 3- elementda , 3- niki esa 2- da va hokazo ...



|       | Array | Linked List     |
| :---        |    :----:   |          ---: |
| O'qish      |  O(1)       |    O(n)   |
| Qo'shish   |   O(n)        |    O(1)      |
| O'chirish   |  O(n)        |   O(1)      |

**Arrays vs Linked Lists**


![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/tzn5c0bynyckdbfp1taq.png)

**Linked Lists turlari**

Singly Linked Lists - Bir Tomonlama Ro'yhat

![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/41uqt8ao6wm8lied8pua.png)
Circular Linked Lists - Aylana Ro'yxat

![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/1zejjh2rwncorsitewli.png)
Doubly Linked Lists - Ikki Tomonlama Ro'yhat

![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/kdxc19tqx94357pn7yjo.png)

C# da Linked List dan qanday foydalanish haqida keyingi postda yoritaman.
🐦 JavaScript Twitter Share Url Button
Published: 2022-05-22 08:56:24

The Tweet button allows you to quickly share the webpage you're viewing with all your followers,
clicking the Tweet button provides you with a prepopulated Tweet containing a link to that webpage.

Amazing, but how to add the Tweet button to your website, to share a blog post url for example?


In React you can use [React-Share](https://www.npmjs.com/package/react-share), but if you don't want to use an external package you can achieve the same result in a few lines of code7

### How to use the Tweet button

Very simple
1. When you see the Tweet button on a webpage that you feel like sharing, click it.
2. If you're not already logged in to Twitter, you will be prompted by a pop-up box to log in.
3. A Tweet box will appear for you to post a Tweet linking to the webpage you visited. 
4. When ready, click “Tweet.”

### Implementation

After creating the button all you have to do is associate it a click event that calls this function:

	
	function sharePage() {
        const url = window.location.href;
        window.open('https://twitter.com/intent/tweet?text=' + encodeURIComponent(document.title) + '&url=' + encodeURIComponent(url), '', 'menubar=no,toolbar=no,resizable=yes,scrollbars=yes,height=350,width=600');
        return false;
    };
    

Done!

In this video you can see a simple implementation
[video](https://youtu.be/LefZJ56CcSM) 

have a good day!
👋
OAuth with slack
Published: 2022-05-22 08:21:53

**🤔 What is OAuth? 👇**
OAuth is a protocol that lets your app request authorization to private details.

With slack we can implement OAuth for the required scopes, to access the workspace channels, members, conversations, calls, listen to events, etc...

**Ohh, 🤔 What are scopes then? 👇**
Scopes are used to grant your app permission to perform functionality in Slack like,
 1. Call Web API methods, users.list, channels.read, 
    channels.write, etc...
 2. Receive Events API events like, user joined, channel 
    created, etc...

**Then how to do it? 👉 Follow the below steps**

## Create and Install app to workspace:

1. Create slack workspace, by going to [https://slack.com](url)
2. After that, create an app, by going to [https://api.slack.com/apps](url), choosing respective workspace.
3. After creating app, go to the created app and under `OAuth & permissions` section give the required scopes.
4. After giving scopes you can able to install app to your workspace or publish it to slack open directory.

## Performing OAuth

1. To perform OAuth we need to generate authorization redirect url, to do so navigate to [https://api.slack.com/authentication/sign-in-with-slack](url)
2. The url will look like,   ```
   GET /openid/connect/authorize?
     response_type=code
     &scope=openid%20profile%20email
     &client_id=s6BhdRkqt3
     &state=af0ifjsldkj
     &team=T1234
     &nonce=abcd
     &redirect_uri=https%3A%2F%2Fclient.example.org%2Fcb 
 HTTP/1.1
   Host: https://slack.com
 ```
               
3. The `redirect_uri` in above url, is the request handler for which slack to redirect with temporary access code.
4. With that temporary access code we need to request for access-token using api `slack.com/api/openid.connect.token?code={access_code}&client_id=###&client_secret=###&redirect_uri=###`, for more details about api method, headers and parameter look into [https://api.slack.com/methods/openid.connect.token](url)
5. With the access-token received, you can store it securely and use it whenever required.

**Hurray! It's done 😇**

## Conclusion:

- I have provided basic walkthrough, please do explore [https://api.slack.com/authentication/basics](url), for detailed explanation.
- And explore the Refresh token concept, how to opt for it, refresh the access-token using refresh token.
Django.WTF - discover trending Django packages
Tags: django, python, github
Published: 2022-05-22 08:52:08

[https://django.wtf](https://django.wtf)

I've often used djangopackages.org to explore app I could re-use in my projects. While the site is great, I thought we could build a modern variant with focus on package curation. I've been overwhelmed with the number of categories djangopackages.org offers and the poor categorization. It also includes packages aren't maintained or updated anymore.

Together with a friend, I've built a new site based on the same concept - index popular Django apps, categorize, rank and display the most important information for each package. The site contains fewer categories than djangopackages.org and we curate and categorize projects ourselves.

Since we were scraping Github for package info, we figured we could scrape contributors to Django projects as well ;). The site contains the most prolific contributors to Django projects as well who is trending right now.

If you have any ideas for features we could add to the site, let us know :)
Event Object Properties
Tags: javascript, webdev, beginners, programming
Published: 2022-05-22 08:46:03

JavaScript stores events as Event objects with their related data and functionalities as properties and methods. When an event is triggered, the event object can be passed as an argument to the event handler function.

function eventHandlerFunction(event){
   console.log(event.timeStamp);
}
 
eventTarget.addEventListener('click', eventHandlerFunction);
In the example above, when the 'click' event is triggered on the eventTarget, the eventHandlerFunction receives event, the Event object, which has information related to the 'click' event. Then, we log the time it took for the event to be triggered since the document was loaded by accessing the .timeStamp property of the event object.

There are pre-determined properties associated with event objects. You can call these properties to see information about the event, for example:

the .target property to reference the element that the event is registered to.
the .type property to access the name of the event.
the .timeStamp property to access the number of milliseconds that passed since the document loaded and the event was triggered.