teleren/devto huggingface dataset:
Add Binary
Tags: algorithms, csharp, leetcode, easy
Published: 2022-10-24 03:24:50

_#67.Add Binary_

### Problem statement
Given two binary strings `a` and `b`, return _their sum as a binary string_.

**Example 1**
```
Input: a = "11", b = "1"
Output: "100"
```

**Example 2**
```
Input: a = "1010", b = "1011"
Output: "10101"
```

### Explanation
給定兩個二進位制的字串 `a` 和 `b` ，將他們相加並返回二進位制的結果

### Solution
將兩字串轉換成十進位，接著兩者相加得到總和，總和在轉換成二進位得到答案

```csharp
public string AddBinary(string a, string b)
{
	var x = Convert.ToInt32(a, 2);
	var y = Convert.ToInt32(b, 2);

	var res = x + y;

	return Convert.ToString(res, 2);
}
```

測試沒問題直接提交，得到與上一題 Plus One 相同的錯誤，果然沒這麼簡單！於是我尋思著上一題的解法，這題用相同邏輯應該不會有問題，我朝著這個方向前進，建立一個 `carry` 變數來紀錄是否進位，以及 `sb` 來合併每次執行結果，上一題 Plus One 是對一個數加一，這題是兩個數相加，沒什麼太難的問題，只是有些小細節要注意

```cs
public string AddBinary(string a, string b)
{
	// 將 a,b 補 0 直到相同長度
	int maxLen = a.Length > b.Length ? a.Length : b.Length;
	a = a.PadLeft(maxLen, '0');
	b = b.PadLeft(maxLen, '0');

	// true 表示進位, false 則無
	bool carry = false;
	StringBuilder sb = new StringBuilder();

	int add;

	maxLen--;

	// 依據各種狀況進行相加
	while (maxLen > -1)
	{
		add = a[maxLen] + b[maxLen];

		if (add == 98) // a+b=2
		{
			if (carry)
				sb.Insert(0, '1');
			else
			{
				sb.Insert(0, '0');
				carry = true;
			}
		}
		else if (add == 97) // a+b=1
		{
			if (carry)
				sb.Insert(0, '0');
			else
				sb.Insert(0, '1');
		}
		else // a+b=0
		{
			if (carry)
			{
				sb.Insert(0, '1');
				carry = false;
			}
			else
				sb.Insert(0, '0');
		}

		maxLen--;
	}

	if (carry) sb.Insert(0, '1');

	return sb.ToString();
}
```

### Reference
[LeetCode Solution](https://leetcode.com/problems/add-binary/discuss/1310974/C-Solution)

[GitHub Repository](https://github.com/FakeStandard/LeetCode-CSharp/tree/main/Solution/0067.Add-binary)

---

Thanks for reading the article :tulip: :sunflower: :blossom:

If you like it, please don't hesitate to click heart button :heart:
or click like on my Leetcode solution
or follow my [GitHub](https://github.com/FakeStandard) :star:
or buy me a coffee :arrow_down: I'd appreciate it.

[![Buy-me-a-coffee][1]][2]

[1]: https://dev-to-uploads.s3.amazonaws.com/uploads/articles/h077sxd0vx1hix4t7lw8.png
[2]: https://www.buymeacoffee.com/FakeStandard

---
Creating an Indie Game -- Week 2
Published: 2022-10-24 02:22:26

Hello!

I'm back for the second update of making an Indie Game. If you're just joining us, here was the post for week one: [Creating an Indie Game -- Week 1](https://dev.to/stcollier/creating-an-indie-game-week-1-j4c)

Here's an overview of what I did over the week:

- Expanded the map a bit
- Tweaked the rendering of the map in order to prepare for the bigger world I'll soon be drafting
- Created two tree sprites (a regular tree and a tall tree)
- Imported the trees into the game and added falling leaves.
- Refactored a lot of code
- Added a basic interaction system

Here's some screenshots!!

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

This week was quite busy, so I didn't get as much done as possible. However, I hope to keep chipping away at this project, even if I don't get much done. Stay tuned for week 3, and follow me so you don't miss it!

{% user stcollier %}
In the future people don't wanna play rock paper scissors with hands we are there with a digital rock paper scissors
Tags: showdev, productivity, python, computerscience
Published: 2022-10-24 01:58:36

In this we are introducing our all new rock paper scissors made with pure python basics.If you are beginner you can try the source code so that you can learn more!

Source code:-  https://drive.google.com/drive/folders/1TM0VN0iPgWATqP9bSbIRq5OmyJKJGs_Y?usp=sharing

Follow us for more updates with  python!
Handling Errors in Ruby
Tags: ruby, rails
Published: 2022-10-24 01:25:24

When working with Active Record within Ruby, utilizing CRUD operations can yield a multitude of errors. Some common errors are `ActiveRecord::RecordNotFound`, `ActiveRecord::RecordInvalid`, and `ActiveRecord::InvalidForeignKey` among others. In this blog, we're going to go over some ways in which you can handle these errors in order to give the user more information about the errors they receive.

## Utilizing `rescue_from`

A recommended way for error handling is utilizing Ruby's built in `rescue_from` instance public method. Able to be placed right in your ApplicationController or in any specific class controller, `rescue_from` in combination with a trailing `:with` option allows for you to create a private method to handle errors.

```
class ApplicationController < ActionController::Base
  rescue_from User::RecordNotFound, with: :not_found

  private
  
  def not_found
    render json: {error: "Record not found"}
  end
end
```

This will render an error message to the user indicating that the record they were searching for does not exist. This can take care of some errors with `#show` and `#destroy` methods. But what if we're creating a new instance but our user does not pass our data validations? Wouldn't it be nice to tell our user what validations were not passed? Let's explore how we can handle that in our next section

## Handling Validations Errors

There's an important decision you have to make when creating data, and that's whether you want to use `create` or `create!`. Comparing the two, `create` returns the object created by the user, while `create!` returns a `RecordInvalid` error.

### `create`

```
class InstanceController < ApplicationController

  def create
    instance = InstanceClass.create(instance_params)
    if instance.valid?
      render json: instance, status: :created
    else
      render json: {errors: instance.errors }, status: :unprocessable_entity
      end
  end
end
```

Using `create` allows for a user to access the errors key to display all the errors associated with the object.

### `create!`

```
class InstanceController < ApplicationController

  rescue_from ActiveRecord::RecordInvalid, with: :invalid

  def create
    instance = Instance.create!(instance_params)
    render json: instance, status: :created
  end

  private

  def invalid errors
    render json: {errors: errors}, status: :unprocessable_entity
  end
end
```
Here we can see that `create!` will raise a `RecordInvalid` error, and that will be rendered for each invalid option. So that takes care of `#create` errors in terms of validation.

Using this guide, play around with Active Record and Postman and see if you can generate and debug your own errors. Happy Coding!
How to choose the right EC2 for your AWS workloads
Tags: aws, devops, cloud, architecture
Published: 2022-10-24 01:09:48

Before we start choosing the right EC2, there are currently more than 550 instance types, so we will look at the current available instance types.

### Instance naming
The name of the EC2 is separated into two main parts by a dot, as shown in the below image; the second part is the size, the first part is the family, and which consists of letters and a digit; before this digit, there are one or more than one letters and this part is defining the category, the digit is for the generation, then after the digit, there are one or more letters each one defines a specific capability.

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

The available capabilities are :


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



The bellow table shows the instance types for the current generations




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

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

### Instance type selection
Now let's try to select the right instance, there are 2 rules that you can start with them.

1- Select the latest generation, usually latest generation is better in performance and cheaper.

2- If you don't have a specific requirement, start with T families.

What attributes do you need?
try to get answer to these questions:

Do you need a specific processor type?
Can you take advantage of burstable performance?
Can you take advantage of ARM processors?
How much total memory do you need (min/max)?
What is your required vCPU:memory ratio?
What are your network performance requirements?
Do you need accelerated computing options? GPU? FPGA?

After getting answers for the above question, then you can find you candidate instance from the above table.

### EC2 Instance Discovery

AWS provides an easy way to discover, locate, and compare EC2 instances.

Go to the console then EC2 > Instances Types > Instance Types

![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/90qqoffaaqcpuzsmqrzd.png)
Is c++ getting old ? What to do now ?
Published: 2022-10-24 01:01:36

All of us know that C/C++ are the machine or lower level programming languages. But as time is evolving so Google has released a new superset of C++ and Rust languages ie Carbon language. 

A bunch of articles are out there over the internet about carbon language.

Carbon is the super set of c++ language as well as open source language by Google.

GitHub url: [https://github.com/carbon-language/carbon-lang](https://github.com/carbon-language/carbon-lang)
TicTacToe game using python
Tags: python
Published: 2022-10-24 00:50:22

Hello world, in this article you will learn how to build a simple tic, tac, toe game using python programming language.

Watch this awesome tutorial from codewithharry (in Hindi): [https://youtu.be/E8fmDDtaHLU](https://youtu.be/E8fmDDtaHLU)

```python
def sum(a, b, c):
  return a + b + c


def printBoard(xState, zState):
  zero = 'X' if xState[0] else ('O' if zState[0] else 0)
  one = 'X' if xState[1] else ('O' if zState[1] else 1)
  two = 'X' if xState[2] else ('O' if zState[2] else 2)
  three = 'X' if xState[3] else ('O' if zState[3] else 3)
  four = 'X' if xState[4] else ('O' if zState[4] else 4)
  five = 'X' if xState[5] else ('O' if zState[5] else 5)
  six = 'X' if xState[6] else ('O' if zState[6] else 6)
  seven = 'X' if xState[7] else ('O' if zState[7] else 7)
  eight = 'X' if xState[8] else ('O' if zState[8] else 8)
  print(f"{zero} | {one} | {two} ")
  print(f"--|---|---")
  print(f"{three} | {four} | {five} ")
  print(f"--|---|---")
  print(f"{six} | {seven} | {eight} ")


def checkWin(xState, zState):
  wins = [[0, 1, 2], [3, 4, 5], [6, 7, 8], [0, 3, 6], [1, 4, 7], [2, 5, 8],
          [0, 4, 8], [2, 4, 6]]
  for win in wins:
    if (sum(xState[win[0]], xState[win[1]], xState[win[2]]) == 3):
      print("X Won the match")
      return 1
    if (sum(zState[win[0]], zState[win[1]], zState[win[2]]) == 3):
      print("O Won the match")
      return 0
  return -1


if __name__ == "__main__":
  xState = [0, 0, 0, 0, 0, 0, 0, 0, 0]
  zState = [0, 0, 0, 0, 0, 0, 0, 0, 0]
  turn = 1  # 1 for X and 0 for O
  print("Welcome to Tic Tac Toe")
  while (True):
    printBoard(xState, zState)
    if (turn == 1):
      print("X's Chance")
      value = int(input("Please enter a value: "))
      xState[value] = 1
    else:
      print("O's Chance")
      value = int(input("Please enter a value: "))
      zState[value] = 1
    cwin = checkWin(xState, zState)
    if (cwin != -1):
      print("Match over")
      break

    turn = 1 - turn
```
Rails generators
Tags: rails, tutorial
Published: 2022-10-24 00:24:19

## What are rails generators
It is one of the ready to use tools that made rails so popular. Generators allow you to easily invoke actions to add and remove components such as models and controllers.


## Why do we use generators

- Allows to develop via the command line
- Less time consuming because you don’t have to manually create each file individually
- Can help prevent errors and bugs by using the principle of convention over configuration 


## The Different types of generators 

- Model - Generates a model and migration file
- Controller - Generates a controller
- Migration - Generates a new migration this lets you add or modify tables
- Resource -  Generates a model, controller, migration, views directory and optionally routes

There are many more generators, If you type `rails g` or `rails generator` in your console the whole list of all the generators are there.



## Generator Syntax
The syntax you have to follow when using a generator is
 `rails g <name of generator><options> --no-test-framework`
The no test framework at the end is optional but if you don't want the extra files then you can use that tag to avoid it.
Zero to SaaS - Falling in love with the process
Tags: tutorial, beginners, webdev, javascript
Published: 2022-10-24 00:14:39

I’ve been a developer for 5 years . I don’t enjoy writing code anymore. 

I have ambitions of products, apps that I want to build, but lack the discipline or motivation to follow through on these ideas. 

Part of the problem, I think, is the overwhelming amount of pressure to build something, market it, ship it and, hopefully, make money from it. 

When I’m faced with an idea I want to execute on, it feels like standing at the foot of a mountain with a boulder I need to push.

![Illustration of person pushing large rock up large mountain](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/5pcx2e9y2ehjjnsqm7py.png)

Everyone says the way to get over this type of fear is to “Just start!” or “Just do it!”. But that doesn’t stop the anxiety and eventual feeling of overwhelm from creeping in. So how do we expose and solve the real problem here?

Here’s a few questions to ask yourself:

- Do I have ideas I want to execute on?
- Am I afraid I don’t have enough knowledge/experience to do this thing?
- Am I afraid of failing?
- Am I afraid of judgement?

The answer to these questions is likely yes. If so, how do we work around them? I think the answer is to remove expectation.

The expectation that what you build will be good enough, look cool enough, do enough and… make enough (money).

I think the only way to get past that mental block that will take you from Zero to SaaS is to expect nothing of yourself.

So I’m going to put my money where my mouth is. I’m going to keep an ideas journal and regularly use it. Then take one idea and; build it, ship it and document it with no expectations of making money or even being used.

This way, any success that does come from any of these projects will be fuel added to the fire and by the end of this experiment I’ll have all the confidence and ability to execute on ideas without hesitation! and maybe make a buck or two.

If that sounds interesting to you, follow along and join the journey.
Comparing: Binary Search vs Logarithmic Search
Published: 2022-10-23 23:34:05

Searching in algorithm is a tactical or methodical approach to sorting and searching through data. There are two major ways of doing this: linear search and binary search. Binary search is sometimes called logarithmic search. But logarithmic search is just a method of doing binary search, not the binary search itself.
**Binary Search**
Say we have a group of data and we are looking for a particular values in it. Binary search is a search algorithm that finds the position of a target value within a sorted array . It involves sorting the data, and then constantly comparing the target value against the middle value. When this is done, the data is cut in half and the range where the data cannot be found, is eliminated, and the process is repeated again for the remaining portion of data until the target value is all that is left. Binary search is faster than linear
search except for small arrays. However, the array must be sorted first to be able to apply binary search.
**Logarithmic Search**
Logarithmic search is based on the o(log n) time complexity where n is the number of iterations. It is mostly found in recursive functions. Algorithms for which the running time is logarithmic are those where processing discards a large quantity of values in each iterations like in the binary search.
**How they compare**
As I mentioned before, Binary search is also called logarithmic search. This is because you can do it with a recursive function, recursive functions have a logarithmic time complexity. You can also perform a binary search by just iterations which is called an iterative method. Logarithmic algorithm can be used other things other than the binary search.
Python libraries for data Visualization and preprocessing Comparison
Tags: pandas, matplotlib, seaborn
Published: 2022-10-23 23:56:03



1. 
**Seaborn**
It is used for basic graph plotting like line charts,  bar graphs, etc.
**Matplotlib**
It is mainly used for statistics visualization and can perform complex visualizations with fewer commands.

2. 
**Seaborn**
It mainly works with datasets and arrays.
**Matplotlib**
It works with entire datasets.

3. 
**Seaborn**
Seaborn is considerably more organized and functional than Matplotlib and treats the entire dataset as a solitary unit.
**Matplotlib**
Matplotlib acts productively with data arrays and frames. It regards the aces and figures as objects.

4. 
**Seaborn**
Seaborn has more inbuilt themes and is mainly used for statistical analysis.
**Matplotlib**
Matplotlib is more customizable and pairs well with Pandas and Numpy for Exploratory Data Analysis.
Data Visualization with VScode, Jupyter Notebooks and Python.
Tags: 30daysofdatascience, python, vscode, jupyter
Published: 2022-10-23 23:49:37

When working with data, it can be challenging to fully comprehend your data if it is just presented in tabular form. We must visualize or represent our data visually in order to fully comprehend what it means, to properly clean it, and to choose the best models for it. This makes patterns, correlations, and trends more obvious that cannot be seen in data that is presented as a table or CSV file.

Data visualization is the act of using visual representations of our data to identify trends and relationships. We can utilize a variety of Python data visualization libraries, like Matplotlib, Seaborn, Plotly, etc., to do data visualization.We will go over how to use some of these modules for data visualization in Python and go into great detail about the following subjects in this post, The Complete Guide to Data Visualization in Python.

What is Data Visualization?
Data Visualization in Python
Matplotlib and Seaborn
Line Charts
Bar Graphs
Histograms
Scatter Plots
Heat Maps
Below is the link to the different types of data visualization(https://github.com/jvicmaina/Vscode-Jupyter-python)
Introduction to Node Js HTTP
Published: 2022-10-23 23:40:12

Http is is the primary procedure that dictates the formation of messages or how messages are formatted as they are transmitted across the web. HyperText Transfer Protocol (HTTP) is mainly used for transmitting multimedia documents ,and improve collaborative and distributed features of an application.
Routes are specific URLs to which you make an HTTP Request. If you load a website the web browser sends a request to the web server to get the html that defines the website you are loading. Developed as a client-server protocol, the
application initiates the request and the server is informed about the request. When the web server receives this request, it will send a response: 'ok' and then proceed to serve the html to the browser where it will be rendered. The server decodes the HTTP request and sends it to the corresponding application or server for further processing. Making an http request is basically making a request to your web browser to get a data. This request is called ‘GET’. There are different types of http requests that can be made depending on what the user wants to do: the basic operations that a user may look to perform are to Create a record, Read a record, Update a record or Delete a record.
You can Create a record by making a POST or PUT request. The difference between PUT and POST is that PUT will create a new record (as with POST) if no such record exists, or, it will replace an existing record if the record already exists within that aforementioned data structure. You can Update a record by making a PATCH request. While PUT completely replaces an existing record, PATCH updates something having to do with a specific aspect or property of the record. There is one last fundamental operation and it’s called Delete. As you would expect, the name of such an HTTP Request is “DELETE”, and it works much the same as PATCH, it requires the record to be deleted to be provided in a path or route.
As mentioned before, after making an HTTP Request, we’ll receive a response. Earlier, we said that when your web browser requests to “GET" the HTML from the web server, it’ll respond with “OK”. That is known as an HTTP Status Code, more specifically, HTTP 200 OK.
O que significa o dia da Ada Lovelace?
Tags: braziliandevs, womenintech, devrel
Published: 2022-10-23 23:25:33

## Quando comemoramos o dia da Ada Lovelace e por quê?
Desde 2009, toda segunda terça-feira do mês de outubro, celebramos o dia da Ada Lovelace. Uma homenagem para comemorar as conquistas, encorajar e incentivar meninas e mulheres na STEM.

### O que significa STEM:
- S: Science (Ciência);
- T: Technology (Tecnologia);
- E: Engineering (Engenharia);
- M: Mathematics (Matemática).

## E quem é a Ada Lovelace?
Britânica, nasceu em 10 de dezembro de 1815. Seu pai, Lord Byron, foi um dos principais poetas da Inglaterra, sua mãe, chamada Annabella, era uma grande estudiosa da matemática.
Foi abandonada pelo pai, o que fez com que sua mãe a incentivasse a ter uma vida direcionada para a matemática e não apenas para a poesia.

### Especialidades da Ada:
- Matemática;
- Poetisa;
- Cientista da computação;
- Inventora;
- Tradutora;
- Escritora;
- Engenheira.

Aos 27 anos, ela iniciou uma parceria com Charles Babbage. Ele estava construindo uma máquina analítica, que seria considerado o primeiro "computador" da sua época.
Ada apoiava seu trabalho de diversas formas. Uma delas, na tradução. Enquanto fazia sua parte, ela começou a perceber que aquela máquina iria muito além do que todas as outras pessoas enxergavam: números.
Com isso, escreveu o primeiro algoritmo para esse equipamento.

## E a Ada foi reconhecida pelo seu trabalho?
Infelizmente, só houve reconhecimento um século depois. Mas hoje, ela é conhecida como a primeira pessoa programadora e também a primeira pessoa a identificar um erro. Sua representatividade tem grande importância em toda a tecnologia, mas principalmente nas comunidades de pessoas desenvolvedoras e comunidades de pessoas que trabalham com qualidade de sistemas.

## E a linguagem de programação Ada?
O Departamento de Defesa dos Estados Unidos estava criando uma nova linguagem de programação para substituir todas as outras que estavam usando e nomeou essa linguagem com em homenagem a Ada Lovelace.

---

E você, já conhecia essa parte da história? O que achou? Conta pra mim aqui nos comentários. E fique à vontade para deixar o registro de como a Ada Lovelace te inspira.

Obrigada por ter lido o artigo e deixo o canal aberto para troca de ideias e feedbacks.
LettrLabs - B2B marketing company that creates handwritten direct mail
Tags: marketing, robotics
Published: 2022-10-23 23:08:39

LettrLabs is a marketing company that helps organizations scale their business and retain clients through the power of handwritten letters. We've developed our own robotics to create handwritten mail using a real pen. The result is an authentic note that will wow your clients and grab the attention of new prospects.

[https://lettrlabs.com](https://lettrlabs.com)