teleren/devto huggingface dataset:
T-SQL: How To Write A CROSS JOIN and Why
Tags: sql, tutorial, database
Published: 2021-08-06 10:14:26

When we look at data, we will sometimes want to look at all data points relative to all other data points. We discussed this when we talked about CROSS APPLY, but we must remember that CROSS APPLY pertains to SQL Server only. In many SQL languages we can use CROSS JOINs. From this functionality, we can look at every record relative to every other record - for instance, if we have data for 12 months, we look at each month relative to all months (including itself). In the video, [SQL Basics: How To Use A CROSS JOIN and Why](https://www.youtube.com/watch?v=H3Stc86AoNs&list=PLHHm85xMQAYNScEs-nu9gzi2uoQ9JCCYA&index=9), we look at an example of using this functionality.

Some questions that are answered in the video:

- Note the tables that we're using and what values are identical based on the column names and what values differ based on the column names. We'll be using these tables throughout these videos. As a note on aliasing tables - the first table always gets a "t1" while the second table always gets a "t2" and so on and so forth (the 5th table would get a "t5"). Finally, consider that some SQL languages may not support the JOINs that we discuss.
- As a quick reminder, not all SQL languages may support the exact syntax shown.
- We've discussed CROSS APPLY and while this may be similar to CROSS JOIN, there are differences (I highlight these toward the end of the video).
- CROSS JOIN, unlike CROSS APPLY, is supported in more SQL languages than SQL Server. While it does have the "multiple" result set that we can see in CROSS APPLY, it does not take in parameters like CROSS APPLY (as an example), so it is still restricted in use. It does however result in a multiple result set as we see.
- Consider scenarios where we may want to use this functionality

In the example, we CROSS JOIN our two tables, which only have 2 overlapping values between tables. A large percent of the time, we'll use CROSS JOIN on a table itself, but it's useful to use CROSS JOIN on two tables because we'll sometimes do this. Also, we don't filter; for instance, if I had filtered where values equal, our result set would be different. Keep this in mind when you CROSS JOIN two tables where you need to filter strictly because of the values that you're comparing - for instance, if we want to compare a month's data to every other month, then we need to filter accordingly (for instance, on the first table we may only select one value and compare to every other value). For more SQL lessons, you can continue to watch the [SQL Basics](https://www.youtube.com/watch?v=Ied5YaCu_-0&list=PLHHm85xMQAYNScEs-nu9gzi2uoQ9JCCYA&index=1) series.
State in React for dummies
Tags: react, javascript, state
Published: 2021-08-06 09:42:08

Well, things can become really complicated in React and there's no reason for that. At least, as a beginner, you should be able to understand States without falling asleep 💤 💤 by counting a dozen technical slangs.

> So a `State` is an object, just like `props`.

Note: You might want to check **state vs. props** and it may drive you crazy 😵‍💫, so just think that the use of `state` results in significant performance improvements in larger apps. **We need State**. Now relax.🛀

To use a state you need to import the useState, like this:
```jsx
import React, { useState } from "react";
```
State is wonderful to work with; it returns the state value and the function to update that value. 
```jsx
const [item, updateItem] = useState(""); // item=""
```
You can use `updateItem("hello!")` to update `item`. Let's see a real world example with a form component:
```jsx
import React, { useState } from "react";

function AddItemForm() {
  const [item, updateItem] = useState("");

  const valueChangeHandler = (e) => {
    updateItem(e.target.value);
  };

  return (
    <div>
      <form>
        <div className="field">
          <label className="label">Title</label>
          <div className="control">
            <input
              onChange={valueChangeHandler}
              value={item}
              className="input"
              type="text"
              placeholder="Title"
            ></input>
// and so on
``` 

So, we have a form. We introduce a state value (item="") and every time the user inputs something on the input field, we update the `item` value using the `updateItem` function. Notice that we make sure that `value={item}`, so with every `onChange` event, the value of the input is updated. You could use the `item` in any other place ofcourse.

I think that was fairly simple, right? :) 

Now, States are used to chain updates, so it is important to understand that you can submit the form and **pass** data with the `onSubmit` event to the App (or any other component).

To do this, you need to add `props` to the component like this:

```jsx
function AddItemForm(props) {
  const [item, updateItem] = useState("");
```
Then you need to create a function to use for the `onSubmit` event:
```jsx
const submitHandler = (e) => {
    e.preventDefault(); // so that page will not reload
    props.onSubmitData(item); //item *goes up* to the App :)
  };
```

You will call the `submitHandler` like this on your form component:

```jsx
<form onSubmit={submitHandler}>
```
Now you need to perform some changes on the App as well. The above example will only work if a `onSubmitData` prop has been defined for the form component in the App, like this:

```jsx
return (
<AddItemForm onSubmitData={getFormData} /> //AddItemForm is the form component
//and so on
```

Last, you need to **pass** the form data from the form component to the App using a function:

```jsx
const getFormData = (someData) => {
    console.log(someData); // someData will return the value of item
  };
```
 
We passed a form input value (item) from one component to another. Lovely! 💕
Additional Column for Incremental Numbering in SQL
Tags: sql, sqlite, mysql
Published: 2021-08-06 08:52:59

## The Playground Database
I'm using a database from [sqlitetutorial.net](https://www.sqlitetutorial.net/wp-content/uploads/2018/03/chinook.zip) and [SQLite Browser](https://sqlitebrowser.org/). From the database, I will only use one table: let's say it's the `Albums` table.

## The Base Query

```sql
SELECT
    Title
FROM albums
ORDER BY Title
```

The above query will display one column named 'Title' of the albums and ordered by the title itself in ascending. The goal here is to add additional column to the left named `No.` with the incremental numbering.

## The `ROW_NUMBER()` Function

> Thanks to geraldew's comment 😁

There is a function to make incremental or consecutive number called `ROW_NUMBER()`. The detail explanation of the function can be found at [https://www.sqltutorial.org/sql-window-functions/sql-row_number/](https://www.sqltutorial.org/sql-window-functions/sql-row_number/).

But I will make it simple here, We can simple modify the above query by adding this function like this:

```sql
SELECT
   ROW_NUMBER() OVER (ORDER BY Title) AS 'No.',
   Title
FROM albums
```

the result is as we expected, it will numbering to the Titles as ordered in ascending.

From here, we can add the pagination support in SQL like `LIMIT` and `OFFSET`:

applying `LIMIT`:
```sql
SELECT
    ROW_NUMBER() OVER (ORDER BY Title) AS 'No.',
    Title
FROM albums
LIMIT 10
```

applying `LIMIT` and `OFFSET`:
```sql
SELECT
    ROW_NUMBER() OVER (ORDER BY Title) AS 'No.',
    Title
FROM albums
LIMIT 10 OFFSET 10
```
4 Important Dictionary Methods
Tags: python, beginners, codenewbie, programming
Published: 2021-08-06 08:35:53

Hello everybody, I'm [Aya Bouchiha](developer.aya.b@gmail.com), today, we'll talk about 4 important dictionary methods.

## clear()

**clear()**: this method lets you delete all the dictionary's items;

```python
user = {
  "name": "Aya Bouchiha",
  "email":"developer.aya.b@gmail.com",
}

print(len(user)) # 2
user.clear()
print(user) # {}
print(len(user)) # 0
```

## copy()

**copy()**: lets you get a copy of the specified dictionary.

```python
user = {
  "name": "Aya Bouchiha",
  "email":"developer.aya.b@gmail.com",
}

admin = user.copy()
# {'name': 'Aya Bouchiha', 'email': 'developer.aya.b@gmail.com'}
print(admin)
user['name'] = 'John Doe'
# {'name': 'John Doe', 'email': 'developer.aya.b@gmail.com'}
print(user)
# {'name': 'Aya Bouchiha', 'email': 'developer.aya.b@gmail.com'}
print(admin)
```

## setdefault(key, value)

**setdefault(key, value(optional))**: this method returns the value of the given key If It exists, otherwise, It creates a new item with the given key and value and returns its value.

```python
user = {
  "name": "Aya Bouchiha",
  "email":"developer.aya.b@gmail.com",
}


print(user.setdefault('name', 'unknown')) # Aya Bouchiha
print(user.setdefault('is_admin', 'False')) # False

# {'name': 'Aya Bouchiha', 'email': 'developer.aya.b@gmail.com', 'is_admin': 'False'}
print(user)
```

## values()


**values()**: this method returns all the given dictionary's values as a list.

```python
products_prices_in_dollar = {
  "laptop":1000,
  "phone":150,
  "mouse":10,
  "keyboard":7
}
print(products_prices_in_dollar.values()) # dict_values([1000, 150, 10, 7])
   
# converts from dollar to moroccan dirham
# 1000+150+10+7 = 1167$ => 11670 moroccan dirhams
sum_in_dirham = sum(products_prices_in_dollar.values()) * 10

# you have to pay 11670 dirhams
print(you have to pay {sum_in_dirham} dirhams')
```

### Summary

+ **clear()**: deletes all the dictionary's items;
+ **copy()**: returns a copy of the specified dictionary.
+ **setdefault()**:  returns the value of the given key If It exists, otherwise, It create a new item with the given key and value and returns its value.
+ **values()**:returns all the given ditionary's values as a list

## Reference

+ [www.w3schools.com](https://www.w3schools.com/)


## Suggested posts

+ [All You Need To Know About Python JSON Module](https://dev.to/ayabouchiha/all-you-need-to-know-about-python-json-module-5ef0)

+ [5 Helpful Python Random Module Methods](https://dev.to/ayabouchiha/5-helpful-python-math-module-methods-44gf)

+ [5 Helpful Python Math Module Methods](https://dev.to/ayabouchiha/5-helpful-python-math-module-methods-44gf)

+ [5 Useful Python String Methods](https://dev.to/ayabouchiha/5-useful-python-string-methods-4pe7)


To Contact Me:

email: developer.aya.b@gmail.com

telegram: [Aya Bouchiha](https://t.me/AyaBouchiha)

Hope you enjoyed reading this post :)
Creating diagrams for software projects
Tags: software, discuss
Published: 2021-08-06 08:27:00

Hi, i am a web developer and working on MERN stack. I  want to build a web application. For that  i want to follow some software development process. 

https://en.wikipedia.org/wiki/Software_development_process

I want to follow the below steps.

- Requirements analysis resulting in a software requirements specification
- Software design
- Implementation
- Testing
- Integration, if there are multiple subsystems
- Deployment (or Installation)
- Maintenance


But the thing came in my mind is that, should i  follow these steps because they  are time consuming. 

I also looked for tools and technologies used to develop diagrams (DFD), but i did't found anyone.
Día 2 de Proyecto
Published: 2021-08-05 04:27:57

NOTA: No es el día 2 como tal, pero es el día que considero haber hecho un avance decente.

Estuve teniendo dificultades en qué enfoque utilizar para implementar las características de DECAF en el proyecto. Comenzando con las características acordadas por el grupo, comencé a ver sobre la siguiente: num en la declaración de un arreglo debe ser mayor a 0.

Intenté resolverlo desde la gramática (el archivo g4) pero se complicaba o se podían dar problemas al ejecutarlo con Python, por lo que descarté esta idea.

Luego, encontré sobre ErrorListeners y ErrorStrategy en ANTLR, por lo que intenté utilizar esto pero se complicó bastante. No es por decir que no era una solución, pero no era efectiva, además investigando las personas decían que "se debía poseer conocimientos nivel de investigador de compiladores" para hacer un ErrorStrategy apropiado, por lo que opté a ver otra manera.

La última opción, la cual fue la que elegí, fue utilizar el Listener proveído por ANTLR. ANTLR tiene dos maneras de generar el recorrido a través del árbol, una es a través de Listeners y otro es a través de un Walker. La opción que escogí fue la de Listener, así que tengo el control de saber cuándo se está entrando a cierto nodo, por ejemplo, a una declaración de variable, que era lo que justamente necesitaba.

Entonces, con un listener custom, manejo la entrada a la declaración de variable, identifico el número y observo si este es 0, si es así, entonces se añade a la lista de errores y se levanta una excepción.

Considero que es un buen avance, para implementar las otras reglas, seguiré un approach parecido.
Redux project structure
Published: 2021-08-06 07:36:27

---
title: Redux project structure
published: true
description: Need contribution for react redux project structure
tags:
---

 I created a react app with `create-react-app` and i need some contribution from the react-redux developers for better project structure.

  You can fork the repository and create pull requests. 

   ### Here is my repository

  [github repo link](https://github.com/Imlohith/open-contribution)
Best way to learn DSA with Codechef.
Tags: dsa, python, codechef, algorithms
Published: 2021-08-06 07:22:05

Hello guys, welcome so are you a coding beginner?. Are you familiar to codechef? Even if no, Do you want to learn Data structure, Algorithms?. Well you should read this blog.
I am going to introduce you to this Coding and learning platform called Codechef. 

Visit Codechef --> [CodeChef | Competitive Programming | Participate & Learn | CodeChef](https://www.codechef.com/)

So Codechef has this really cool Coding Series/ Competition going on called "DSA Learning Series".
According to me its best way to approach DSA learning it goes from absolute beginner to Advanced problems.

## The competition is divided in 11 parts as follows.

0.Easy Problems to Get Started
1. Complexity Analysis + Basics Warm Up
2. Linear Data Structures
3. Standard Template Library(STL)
4. Divide and Conquer + Binary Search 
5. Mathematics in Competitive Programming
6. Basic optimization techniques Basic Math/Combinatorics Problems
7. Dynamic Programming Basics 
8. Graph Theory Basics
9. Advanced Data Structures
10. Dynamic Programming Advanced
11. Graph Theory Advanced 


## How to use the DSA Learning Series?

- You can use any language of your choice. 

- The best way to learn and solve the problems is by first reading the problem thoroughly. Understanding it.

- then look what input the program ask and what output it desires.

- Its not necessary that you know the direst solution. You can just divide the problem in parts and get to the final output.

- Do not try to skip or Copy/Paste the solutions. 

- Also do not jump to the optimal solution, first use the brute force approach, let your solution get convert into code and then move towards the optimal approach.

- In case you are stuck check out the hints provided for the problems or use stack-overflow or google just the part you stuck on.

- For more detailed explanations check out the live session videos of each topic.

- Do not directly use codechef compiler to solve the solutions use Sublime text or any code editor so you can document your learning clearly.

DSA learning series --> [Contest Page | CodeChef](https://www.codechef.com/LEARNDSA?order=desc&sortBy=successful_submissions)


Here are the solutions for the CODECHEF- DSA learning series (Easy Problems to Get Started)

Link --> [GitHub - unlikelycreator/DSA-learning-series-codechef: This is a DSA learning series by codehcef from begineer to advance](https://github.com/unlikelycreator/DSA-learning-series-codechef)

:warning: **Use the solutions only when needed. The program names are labelled according to Program Code.**

HAPPY CODING :) ❤️
在網頁中使用 JavaScript 進行 MQTT 通訊
Tags: mqtt, javascript
Published: 2021-08-06 07:07:40

MQTT 是非常輕便簡易的通訊協定, 由於大部分的 MQTT broker 都支援 websocket, 因此我們也可以在網頁中使用 MQTT, 以下以 [MQTT.js](https://github.com/mqttjs/MQTT.js) 這個模組為例, 並以 https://test.mosquitto.org/ 提供的 MQTT broker 示範：

```html
<html>
<head>
  <title>test Ws mqtt.js</title>
  <script src="https://unpkg.com/mqtt/dist/mqtt.min.js"></script>
</head>
<body>
<script>
  var client = mqtt.connect("ws://test.mosquitto.org:8080") // you add a ws:// url here
  client.on('connect', ()=>{
    console.log('connected.');
    client.subscribe("mee")
    client.on("message", function (topic, payload) {
      console.log(payload);
      console.log([topic, payload].join(": "));
      // client.end()
    });

    client.publish("mee", "hello");    
  });
</script>
</body>
</html>
```

- 第 4 行是 [MQTT.js 提供的 CDN](https://github.com/mqttjs/MQTT.js#browser), 你也可以儲存一份本機檔使用。

- 第 8 行就是以 websocket 連上 MQTT broker, 在 test.mosquitto.org 的頁面上有說明, 不加密、不認證的測試用 broker 使用 [8080 通訊埠](test.mosquitto.org)。

- 第 9 行就可以向 MQTT broker 訂閱頻道, 並且透過第 11 行註冊 `message` 事件的函式。

- 第 16 行則是在特定頻道發佈訊息。

## 連接支援 wss 的 MQTT broker

在 https 的網頁中並不能使用未加密的 ws 協定連接 MQTT, 必須改用 wss 協定。我們測試的 test.mosquitto.org 網站也提供 wss 協定, 但要改用  8081 埠：

```javascript
var client = mqtt.connect("wss://test.mosquitto.org:8081");
client.on('connect', ()=>{
  console.log('connected.');
  client.subscribe("mee")
  client.on("message", function (topic, payload) {
    console.log(payload);
    console.log([topic, payload].join(": "));
    // client.end()
  });

  client.publish("mee", "hello");    
});
```

可以用 [p5.js Web Editor](https://editor.p5js.org/codemee/sketches/4RjXx5qwz) 測試。

## 連接需要帳號密碼登入的 MQTT broker

如果 MQTT broker 需要帳密登入, 也可以在連接時加上 options 物件指定使用者名稱與密碼。在我們測試用的 test.mosquitto.org 提供有 rw/readwrite 帳密可供測試：

```javascript
let options = {
    username: 'rw',       // 可讀寫的測試帳戶
    password: 'readwrite' // 測試帳戶的密碼
}
var client = mqtt.connect(
    // test.mosquitto.org 的 wss 使用 8081 埠
    "wss://test.mosquitto.org:8081",
    options // 連接時指定選項登入
);
client.on('connect', ()=>{
  console.log('connected.');
  client.subscribe("mee")
  client.on("message", function (topic, payload) {
    console.log(payload);
    console.log([topic, payload].join(": "));
    // client.end()
  });

  client.publish("mee", "hello");    
});
```

可以用 [p5.js Web Editor](https://editor.p5js.org/codemee/sketches/745HI130Z) 測試。

## API 說明

詳細的 [API](https://github.com/mqttjs/MQTT.js#api) 可在網站上查詢。
call vs apply vs bind
Tags: javascript
Published: 2021-08-06 07:01:02

---
title: call vs apply vs bind
published: true
description: 
tags: javascript
//cover_image: https://direct_url_to_image.jpg
---

If you started your career as a javascript developer using frameworks such as vue and angular,  javascript native functions might be unfamiliar to you. If you stumbled upon functions like **call**, **apply**, and **bind** and seems you can’t wrap your head around them, this article is for you.

All these 3 methods allow you to change the *this* context of a function.

Suppose you have the following code:

```javascript
function sayName() {
  console.log(this.name)
}

sayName()
```
The output of this call is **undefined**. Because this refers to Window(if you are running the code in a browser) object and it has no *name* property. Thus, the *undefined*.

The **call()** method

**call()** basically calls a function with the given lexical context as parameter like so:

```javascript
let human = { name: 'JC' }
function sayName() {
  console.log(this.name)
}

sayName.call(human); // Outputs JC
```

Another thing you can do is to supply argument/s to the function like so:

```javascript
let human = { name: 'JC' }
function sayName(greeting) {
  console.log(greeting + ' ' + this.name)
}
sayName.call(human, 'Hi!') // Outputs Hi! JC
```

The **apply()** method

**apply()** is just like **call()** except that it accepts arguments in array like so:

```javascript
let human = { name: ‘JC’ }
function sayName(greeting, city) {
  console.log(greeting + ' ' + this.name + ' from ' + city)
}
sayName.apply(human, ['Hi', 'Taguig']) // Outputs Hi! JC from Taguig
```

with **call()** you have to supply the arguments individually like so:

```javascript
console.log(sayName.call(human, 'Hi!', 'Taguig')) // Outputs Hi! JC from Taguig
```


The **bind()** method

The **bind()** is somewhat special. It is a higher-order function which means it returns another function when you invoke it. The function returned is curried, meaning you can call it multiple times to provide different arguments in each call. It is a complex topic you can read more about it on the internet. For now, let’s apply it on our example:

```javascript
let human = { name: 'JC' }
function sayName(greeting, city) {
   console.log(greeting + ' ' +     this.name + ' from ' + city)
}

let greet = sayName.bind(human)
greet('Hi!', 'Taguig') // Outputs Hi! JC from Taguig
greet('Hello!', 'Makati') // Outputs Hello! JC from Makati
```

That’s it! I hope I was able to demistified these 3 methods for you.  Thanks for reading my article!

Originally posted at [jcfrane.com](https://www.jcfrane.com)
Generic Linear Search/Sequential Search for a sequence in C# .NET
Tags: dotnet, csharp
Published: 2021-08-06 19:36:49

---
title: Generic Linear Search/Sequential Search for a sequence in C# .NET
published: true
date: 2021-08-06 00:00:00 UTC
tags: dotnet, csharp
canonical_url: https://swimburger.net/blog/dotnet/generic-linear-search-sequential-search-for-a-sequence-in-csharp-dotnet
---

Early this year, I decided to brush up on my algorithms and data structure knowledge. I took these great two courses ([1](https://www.pluralsight.com/courses/algorithms-data-structures-part-one), [2](https://www.pluralsight.com/courses/algorithms-data-structures-part-two)) on PluralSight by Robert Horvick.  
To practice what I learned in this course, I decided to create generic versions of the different algorithms and data structures.

What do I mean by generic versions? These types of courses always use integers or strings to demonstrate the algorithms. Instead of using those primitive data types, I'm reimplementing the algorithms and data structures using C#'s [generic type parameters](https://docs.microsoft.com/en-us/dotnet/csharp/programming-guide/generics/generic-type-parameters).

Here's a console application with a generic method `LinearSearchSequence` to perform a linear search looking not for just one T, but a sequence of T:

```csharp
using System;
using System.Collections.Generic;
using System.Linq;

class Program
{
    static void Main(string[] args)
    {
        var numbers = Enumerable.Range(250, 750).ToArray();

        var index = LinearSearchSequence(numbers, new int[] { 500, 501, 502 });
        Console.WriteLine("Linear Search Sequence:");
        Console.WriteLine(index);
    }

    private static int LinearSearchSequence<T>(IEnumerable<T> list, IEnumerable<T> needle) where T : IComparable
    {
        var needleArray = needle.ToArray();
        var needleLength = needleArray.Length;
        var listLength = list.Count();
        for (int i = 0; i <= listLength - needleLength; i++)
        {
            for (int matchIndex = 0; matchIndex < needleLength; matchIndex++)
            {
                var item = list.ElementAt(i + matchIndex);
                var needleItem = needleArray[matchIndex];
                if (item.CompareTo(needleItem) != 0)
                {
                    break;
                }

                if (matchIndex == needleLength - 1)
                {
                    return i;
                }
            }
        }

        return -1;
    }
}
```

By using a generic type parameter with the constraint that the type has to implement the `IComparable` interface, you can perform the linear search algorithm without knowing the exact type you are working with.

If you want to understand the logic behind the quick sort algorithm, I recommend checking out the courses mentioned earlier. There's also a lot of other great resources out there online!

Disclaimer: This code works, but is only developed for the sake of practice. Use at your own risk or just use a sorting library. If you see some room for improvement, there most likely is, I'm all ears~