teleren/devto huggingface dataset:
F# Tutorial (1) - Intro
Tags: fsharp
Published: 2023-01-03 02:35:36

**※ 이 시리즈는 코딩을 처음 하는 사람을 대상으로 하지 않습니다. 이미 기본적인 전산학 및 코딩, 특히 C#과 OOP에 대해서는 이미 알고 있다고 가정하고 진행합니다.**<br/><br/>

닷넷하면 보통 C#을 떠올리기 마련이지만, (그리고 실제로도 C#이 주가 되는 환경이기는 하지만) 닷넷 위에서 동작하는 언어가 C#만 있는 것은 아닙니다. Delphi.NET이나 C++/CLI 같은 원본이 따로 있는 언어를 제외하면, VB.NET과 F#이 있습니다. 그리고 이 시리즈에서 살펴볼 언어는 F#입니다.

F#은 그 이름답게 Functional Programming(FP)을 위한 언어입니다.
그러니 F#을 사용하다 보면 FP 역시 알게 될 수 밖에 없습니다. 마치 C#을 하다보면 OOP를 알게 되는 것처럼요.

물론 함수형 언어가 F#만 있는 것은 아닙니다. LISP과 여기서 파생된 Scheme, 순수 함수형 언어로 유명한 Haskell, JVM 위에서 돌아가게 만든 Clojure 등등 종류가 생각보다 다양합니다. 이런 언어들과 비교하면 F#은 순수한 함수형 언어는 아닙니다. 함수형 패러다임이 주가 되기는 하지만, 닷넷 및 C#과의 호환성을 위해 class나 mutable, loop 등 순수한 함수형 언어에선 찾아볼 수 없는 문법들이 많죠. 이런 식으로 OOP와 FP를 섞어놓은 언어는 F# 외에도 Scala, Kotlin, Javascript (많은 사람들이 잘 모르지만 Javascript는 multi-paradigm 언어입니다. React에서 쓰는 Functional Component를 생각해보시면 됩니다.) 등이 있습니다. 하지만 이들 언어는 OOP 베이스에 FP를 약간 섞은 식이라면, Scala와 F#은 FP 베이스에 OOP를 약간 섞은 느낌입니다.

여기서는 FP로써의 F#을 알아볼 것이기 때문에 (얼마 안되지만) OOP적인 요소는 최대한 배제하겠습니다. 그러면 Haskell을 사용하지 왜 F#을 쓰냐고요? 저는 닷넷의 지원을 받는다는게 굉장히 큰 장점이라고 생각합니다. 결국 C#과 F# 모두 CIL로 컴파일되기 때문에 C#과 F#의 상호호환이 상당히 쉽게 가능하고, 무엇보다 F# 또한 패키지 매니저로 nuget을 사용하기 때문에 C#을 해보셨던 분이라면 쉽게 적응할 수 있거든요.

그러면 C#만 쓰지 왜 F#을 같이 쓰냐고 물을 수 있습니다. FP 언어는 OOP 언어엔 없는 몇 가지 특징들이 있습니다. 추후에 자세히 다루겠지만, FP 언어는 기본적으로 불변성(Immutability)을 지향하며, 함수 그 자체가 일급 객체이기 때문에 코드를 간략하게 쓰기 용이합니다. 또한 언어 자체적으로 Lazy evaluation을 지원하죠. 이러한 특징들 덕에 FP 언어는 유지보수가 쉬우며, 코드를 간략하게 쓰기 용이합니다.

간단한 예시를 통해 비교해 보죠. 아래 코드는 Quicksort를 수행하는 C#코드입니다.
```csharp
public class QuickSortHelper
{
    public static List<T> QuickSort<T>(List<T> values) where T : IComparable
    {
        if (values.Count == 0)      
            return new List<T>();     
        T firstElement = values[0];
        
        var smallerElements = new List<T>();
        var largerElements = new List<T>();
        for (int i = 1; i < values.Count; i++)
        {
            var elem = values[i];
            if (elem.CompareTo(firstElement) < 0)         
                smallerElements.Add(elem);         
            else         
                largerElements.Add(elem);         
        }
        
        var result = new List<T>();
        result.AddRange(QuickSort(smallerElements.ToList()));
        result.Add(firstElement);
        result.AddRange(QuickSort(largerElements.ToList()));
        return result;
    }
}
```

그리고 이 코드와 동일한 일을 하는 F#코드는 다음과 같습니다.

```fsharp
let rec quicksort = function
    | [] -> []
    | first::rest ->
        let smaller,larger = List.partition ((>=) first) rest
        List.concat [quicksort smaller; [first]; quicksort larger]
```

27줄짜리 코드가 5줄로 줄어들었습니다.

F#은 이처럼 닷넷에서 사용 가능한 유일한 FP 언어라는 점에서 충분히 매력적인 언어라고 생각합니다. 다음 글에서부터 본격적으로 F#의 문법 및 FP에 대해 알아보겠습니다.
How to Install React in 5 minutes
Published: 2023-01-03 01:53:24

Heard a lot about React!! Looking to give it a try on your computer but unsure as to how you can set up your development environment. No worries we got you covered.

Firstly let's ensure you have NodeJS installed on your machine.
We will install nvm (node version manager) which will in turn let us install multiple versions of NodeJS, so we can choose whichever one we need to run.

Type the below command to get the latest
```
nvm install node
```
If you don't have nvm than you can first try installing nvm.

```
curl -o- https://raw.githubusercontent.com/nvm-sh/nvm/v0.39.3/install.sh | bash
```


We will install a React Application and have it configured with Visual Studio Code (VS Code) which will allow you to edit, and create new react apps.

- Install VS code by going to the side VS Code Site [here](https://code.visualstudio.com/)
- Once installed, open VS code, and open an Integrated Terminal within VS Code. You can do this by `Use the View > Terminal or Terminal > New Terminal menu commands.
`
- Now go to this Integrated Terminal and ensure that you are in the space where you want to create your project. So if you want to create your project in documents just type.
```
cd Documents 
```
- Once you are in the location, that you want to create your code folder, type the following command below. So in the command below where I have `nameOfYourAppHere` you can put any name for your app, so whatever you like.
```
npx create-react-app nameOfYourAppHere
```
- Once this is done you should have React and all of it's package dependencies installed
- Now let's start you React Application by typing 
```
cd nameOfYourAppHere
npm start
```
- In your browser go to `http://localhost:3000`
- You will see the react logo spinning and that is your application.
rudol - A data quality platform for all enterprise needs
Tags: engineering
Published: 2023-01-03 01:37:22

Unify your data catalog, reduce communication overhead and enable quality control to any member of your company, all without deploying or installing anything. rudol is a data quality platform that helps companies understand all their data sources, no matter where they come from; reduces excessive communication in reporting processes or urgencies; and enables data quality diagnosing and issue prevention to all the company, through easy steps

With rudol, each organization is able to add data sources from a growing list of providers and BI tools with a standardized structure, including MySQL, PostgreSQL, Airflow, Redshift, Snowflake, Kafka, S3*, BigQuery*, MongoDB*, Tableau*, PowerBI*, Looker* (* in development). So, regardless of where it’s coming from, people can understand where and how the data is stored, read and collaborate with its documentation, or easily contact data owners using our integrations.

rudol also helps teams communicate less and better, by providing activity logs, to make it easy to audit structural changes, even for interested parties who don’t have direct access to every data source used by the organization, and subscription capabilities, so people are immediately informed when changes are detected through their preferred channels, which takes out responsibility from data owners on reporting changes to every interested party

rudol also helps you understand data transformation processes and prevent problems with very little effort, using no-code, easy-to-configure validation rules. These rules allow interested roles to validate anything they need about a data source, whether it’s about inconsistencies, validation of business rules, volume, or speed, without the need to have direct access to the data source or even understand its infrastructure technology.

No matter your role, what credentials you have on the data sources, or your development knowledge, with rudol, you will always be able to know your whole company data structure, its universe of stakeholders, and all dependencies on other sources and people. All while massively reducing communication needs and facilitating quality control for everyone.

Try rudol now for free, and start democratizing data in your organization.

[https://rudol.ai](https://rudol.ai)
Roman to Integer problem using Java
Published: 2023-01-03 01:32:45

Hi, this is Day 3 of my LeetCode journey. Today, I did Roman to Integer problem using Java.


Time complexity: O(n)
```
class Solution{
  public int romanToInt(String s){
    HashMap<String, Integer> map = new HashMap<>();
    map.put("I", 1);
    map.put("V", 5);
    map.put("X", 10);
    map.put("L", 50);
    map.put("C", 100);
    map.put("D", 500);
    map.put("M", 1000);
    int answer = 0;
    int curr = 0;
    int temp = 0;
    String[] arr = s.split("");
    for(int i=0;i<arr.length;i++){
      curr = map.get(arr[i]);
      if(arr.length-1 != i) && (curr < map.get(arr[i+1]))){
        temp = map.get(arr[i+1]) - curr;
        answer += temp;
      }else{
        answer += curr;
      }
    }
    return answer;
  }
}
```
La agencia de marketing
Published: 2023-01-03 01:29:23

En concreto, el programa Kit Digital, que forma parte del Plan de Digitalización de Pymes 2021-2025 y de la Agenda España Digital 2025, dispone de 3.067 millones de euros provenientes de fondos Next Generation EU, para la concesión de bonos que estimulen la digitalización de empresas, entrepreneurs y trabajadores por cuenta propia. El plazo para solicitar estas subvenciones se ha ampliado, en una segunda convocatoria, hasta septiembre de 2023.

Anunciado el 25 de noviembre del pasado año, esta iniciativa del Gobierno de España pretende subvencionar el grado de digitalización del tejido empresarial. Con ello, se espera contribuir a la creación de puestos de trabajo y a la internacionalización de productos y desarrollos con sello español.
[https://www.enlineanoticias.mx/](https://www.enlineanoticias.mx/)

[https://www.riodejaneiro-24h.com/](https://www.riodejaneiro-24h.com/)
[https://www.acordasalvador.com/](https://www.acordasalvador.com/)
Satoshi Spain: La solución a la minería de criptomonedas después del merge
Published: 2023-01-03 01:28:21

Una empresa española, SATOSHI SPAIN, ofrece una solución para todos los mineros de criptomonedas con rig de minería. Actualmente la minería con gpu después del merge de Ethereum, no es rentable. Miles de rigs y tarjetas gráficas se encuentran apagados en espera de que el mercado y la minería mejore. Esta empresa ofrece la oportunidad a todos los mineros de aportar sus tarjetas gráficas o gpu, para realizar servicios gpu cloud para empresas que requieren de esa computacional
La minería 2.0: La solución a la minería de criptomonedas
Una empresa española, SATOSHI SPAIN, ofrece una solución para todos los mineros de criptomonedas con rig de minería. Actualmente, la minería con gpu después del merge de Ethereum, no es rentable. Miles de rigs y tarjetas gráficas se encuentran apagados en espera de que el mercado y la minería mejore. Esta empresa ofrece la oportunidad a todos los mineros de aportar sus tarjetas gráficas o gpu, para realizar servicios gpu cloud para empresas que requieren de esa potencia computacional. 

Primero de todo, ¿qué es la minería de criptomonedas y la GPU cloud? ¿Tienen algunas similitudes?

En términos simples, la minería de criptomonedas implica utilizar servidores con potentes tarjetas gráficas (GPU) para verificar y validar transacciones en una red de criptomonedas. Los mineros reciben una recompensa en la criptomoneda en cuestión a cambio de su trabajo o potencia computacional.
Por otro lado, la GPU cloud es un servicio que ofrece acceso a servidores con GPU a través de Internet. Esto permite a los usuarios y empresas utilizar la potencia computacional de estas GPU sin tener que adquirir y mantener su propio hardware. Los usuarios y empresas pagan por el uso de estos servidores con GPU a través de un modelo de suscripción o por el uso.
[https://www.enlineanoticias.mx/](https://www.enlineanoticias.mx/)
[https://www.riodejaneiro-24h.com/](https://www.riodejaneiro-24h.com/)
[https://www.acordasalvador.com/](https://www.acordasalvador.com/)
Customizing AutoFixture to simplify our tests setups
Tags: csharp, testing, autofixture, dotnet
Published: 2023-01-03 01:08:17

On a [previous post](https://dev.to/pedrostc/til-you-can-register-the-desired-implementation-of-an-interface-in-autofixture-3bl) I've showed how to register an implementation for an interface to be used by AutoFixture. We can simplify that a bit by adding customizations to our AutoFixture instance.

Let's say that we have the following test method:

```csharp
public void TestOne()
{
    var fixture = new Fixture();

    // registering our interface implementation.
    fixture.Register<IConverter<Type1, Type2>>(() => new T1toT2Converter());

    var sut = fixture.Create<ServicyMcServiceFace>();
}
```

We can an AutoFixture customization by implementing the `ICustomization` interface and passing said implementation to our fixture object.

Let's create a customization that will register our `IConverter` implementation for us so we don't need to do that on the test:

```csharp
// Our customization
public class ConverterCustomization : ICustomization
{
    // the method declared by the ICustomization interface
    public void Customize(IFixture fixture)
    {
        fixture.Register<IConverter<Type1, Type2>>(() => new T1toT2Converter());
    }
}
```

Now we can refactor our test method to use that customization.

```csharp
public void TestOne()
{
    var fixture = new Fixture().Customize(new ConverterCustomization());
    
    var sut = fixture.Create<ServicyMcServiceFace>();
}
```

Because of our customization every time we use that fixture instance to create an object that needs an instance of `IConverter<Type1, Type2>`, said object will receive an instance of `T1toT2Converter`, the same as before.

This pattern can be very useful for complex domains with lots of interfaces or if we want to provide some rules for the creation of our objects in a clean and easily reusable manner.
Code Smell 190 - Unnecessary Properties
Tags: webdev, beginners, programming, python
Published: 2023-01-03 00:47:02

*Stop thinking of data as attributes. They are only needed to back your behavior*

> TL;DR: Don't focus on accidental properties. You won't need many of them.

# Problems

- Anemic Models

- Properties bloating

- YAGNI violation

# Solutions

- Create attributes only to support your methods (behavior).

# Context

Whenever they want to model a person or an employee, junior programmers or students add an attribute *'id'* or *'name'* without thinking if they are really going to need them.

We need to add attributes 'on-demand' when there's enough evidence. Objects are not 'data holders'.

# Sample Code

## Wrong

[Gist Url]: # (https://gist.github.com/mcsee/f3a9f762f2781017247f5acf6cf281a1)

```ruby

class PersonInQueue

  attr_accessor :name, :job

  def initialize(name, job)
    @name = name
    @job = job
  end

end

``` 

## Right

[Gist Url]: # (https://gist.github.com/mcsee/53d1777f204e64f5746a9a148ada934a)

```ruby

class PersonInQueue

  def moveForwardOnePosition
    # implement protocol
  end
end

``` 

# Detection

[X] Semi-Automatic

We can detect unused attributes. 

But in many cases, we need an excellent designer to validate the actual need.

# Tags

- Anemic

# Conclusion

Start designing your objects from the protocol. 

Add attributes only when needed.

# Relations

{% post https://dev.to/mcsee/code-smell-144-fungible-objects-3h87 %}

{% post https://dev.to/mcsee/code-smell-01-anemic-models-4dg2 %}

{% post https://dev.to/mcsee/code-smell-40-dtos-4426 %}

{% post https://dev.to/mcsee/code-smell-109-automatic-properties-f40 %}

# Credits

Photo by [Melanie Pongratz](https://unsplash.com/@melanie_sophie) on [Unsplash](https://unsplash.com/photos/SsBI9pweAeA)
 
---

> Object thinking focuses our attention on the problem space rather than the solution space.

_David West_

{% post https://dev.to/mcsee/software-engineering-great-quotes-26ci %} 

---

This article is part of the CodeSmell Series.

{% post https://dev.to/mcsee/how-to-find-the-stinky-parts-of-your-code-1dbc %}
Backend API development using Go
Tags: api, go, gin, beginners
Published: 2023-01-03 00:41:21

Here is the link to the youtube playlist which i have been creating to build a production ready API using Go. We will be using Gin framework.

We will be covering following things are we go along. Things like
1. Dependency Injection
2. Rate limiting
3. Addressing OWASP top 10
4. Authentication and Authorization
5. Database connection
and more..

Subscribe for more

https://www.youtube.com/playlist?list=PLV0yQTl_q4iwPiGFf9wO0F63Gs_qnVMdh
Securing Endpoints Using Vulnerability Profiles
Tags: cybersecurity, socanalyst, tech
Published: 2023-01-03 00:00:30


In this lab, I was able to secure an endpoint by blocking a PDF file with a Custom Vulnerability Object and Vulnerability Protection Profile. Palo Alto Networks Firewalls support the use
of Custom Vulnerability Signatures that can be written with expression patterns to identify vulnerability exploits. Vulnerability Protection Profiles will stop any attempt to
exploit system flaws so that unauthorized access cannot be gained to a targeted system.  
{% embed https://youtu.be/M1OGNSRerc8 %}
In this video:
**• Install the latest Dynamic Updates of Antivirus**
Dynamic Updates ensure policy enforcement on a Palo Alto Networks Firewall of new threat signatures and applications.
**• Install Manual Update of Applications and Threats**
There are times when the Firewall may not have Internet access to perform a Dynamic Update. Applications and Threats will be updated via file that has been downloaded from the Palo Alto Networks Customer Support Portal.
**• Create a Custom Vulnerability Signature**
Palo Alto Network Firewalls use Custom Vulnerability Signature to identify vulnerability exploits by writing a custom regular expression. The Firewall then looks for the custom-defined pattern within the network traffic and takes the necessary action to identify and stop the vulnerability exploit.
**• Clone a Vulnerability Protection Profile**
Creating a customized profile, I'm able to maximize vulnerability-checking for traffic between trusted security zones, and maximize protection for traffic received from untrusted zones, such as the Internet. The strict profile shows the block response to all client and server critical, high, and medium severity events and uses the Default Action for low and informational vulnerability protection events.
**• Apply Custom Vulnerability Protection Profile to a Security Policy**
Using Allow-Any security policy for enforcement on Custom Vulnerability Protection Profile and PDF Vulnerability Protection.
**• Commit and Test Vulnerability Protection**
Attempting to download an infected PDF file and test the Vulnerability Protection. Next, verify in the Threat Logs of the Palo Alto Networks Firewall.
_*** The site can't be reached because the connection was reset by the Firewall to stop the exploit.***_
Simple bullet spread for AI
Tags: gamedev, unrealengine, programming
Published: 2023-04-25 12:01:24

---
title: Simple bullet spread for AI
published: true
date: 2023-01-03 00:00:00 UTC
tags: gamedev, unrealengine, programming
canonical_url: https://tinygame.dev/posts/Simple-bullet-spread-for-AI/
---

## Good AI is not fun AI

It's easy to make your AI bots accurate. Target minus source and you have your aim vector. But where's the fun in being shot by the AI with every bullet? Here's a simple suggestion for improving this by making the AI less accurate.

The idea is to generate random projectile paths within a circle of controllable size around the perfect target location. We do this as follows:
1. Find the perfect projectile direction
2. Aim n units above the perfect target and find the direction vector. We call these n units our MaxBulletSpread and expose it to the editor so it can be tweaked easily.
3. Find the angle between the perfect projectile direction vector and the one pointing above the target.
4. Randomize a number (or two) between -angle and angle and add these to the pitch and yaw of the perfect projectile direction.

The above gives us random trajectories inside a circle of radius MaxBulletSpread around the target. This can then be modified based on AI skill level, distance to target, etc. to have some control over just how inaccurate the AI is.

See example code for UE5 below.

```cpp
// variable for the size of our spread. expose this to the editor for easier tweaking
float MaxBulletSpread = 100.f;

// calculate perfect projectile direction
FVector MuzzleLocation = Character->GetMesh()->GetSocketLocation(SocketName);
FVector ProjectileDirection = TargetActor->GetActorLocation() - MuzzleLocation;

// calculate the direction of the projectile if we were to fire it above the target at max spread value
FVector ActorLocationWithSpread = TargetActor->GetActorLocation();
ActorLocationWithSpread.Z += MaxBulletSpread;
FVector ProjectileDirectionWithSpread = ActorLocationWithSpread - MuzzleLocation;

// find what the angle is for this max spread
ProjectileDirectionWithSpread.Normalize();
ProjectileDirection.Normalize();
const float MaxSpreadAngle = FMath::RadiansToDegrees(FMath::Acos(FVector::DotProduct(ProjectileDirection, ProjectileDirectionWithSpread)));

// create a new rotation to act as the direction of the projectile by randomizing an increase/decrease in pitch and yaw based on the max spread angle
FRotator NewProjectileRotation = ProjectileDirection.Rotation();
NewProjectileRotation.Pitch += FMath::RandRange(-MaxSpreadAngle, MaxSpreadAngle);
NewProjectileRotation.Yaw += FMath::RandRange(-MaxSpreadAngle, MaxSpreadAngle);

// spawn projectile
FActorSpawnParameters Params;
Params.SpawnCollisionHandlingOverride = ESpawnActorCollisionHandlingMethod::AlwaysSpawn;
Params.Instigator = Character;
GetWorld()->SpawnActor<AActor>(ProjectileClass, MuzzleLocation, NewProjectileRotation, Params);
```
Diário de Bordo #1
Tags: javascript, webdev, programming, productivity
Published: 2023-01-02 23:44:18

Essa é uma documentação diária do meu processo de estudos e evolução como desenvolvedora Front-End. Os objetivos deste diário é trazer a tona os principais fatores que será preciso melhorar para que o proveito dos meus estudos sejam amplificados, além de trazer um breve resumo direto ao ponto e simplificado de cada tópico estudado ou de qualquer coisa que eu aprenda de novo e que tenha me pego de surpresa xD.

Para iniciar meu diário, resolvi trazer algumas coisas que eu pude identificar através de uma observação do meu desempenho como Desenvolvedora e descobri tais coisas:

1. É necessário ter um desenvolvimento detalhado dos projetos/exercícios que eu gradativamente desenvolva.

2. Mais treino de Lógica, resolução de diversos problemas, desde o mais simples ao mais avançado que eu puder resolver e análise do problema em questão e análise.

3. Compartilhamento do que é aprendido.


Bom, como podem ver esses são três tópicos que atualmente eu preciso desenvolver e melhorar, e irei fazer um breve comentário sobre eles agora. Em relação ao primeiro tópico, eu resolvi utilizar diagramas para detalhar melhor cada problemas que eu irei resolver daqui pra frente, então vocês verão alguns diagramas que eu criarei nos próximos diários de bordo. Segundo tópico, eu percebi pois estou tendo alguns problemas nas resoluções de exercícios, acredito que deve ser pelo fato do conteúdo ainda não ter sido fixado corretamente, além da melhoria que preciso ter em meu pensamento lógico, logo, pegarei diversos exercícios para resolver utilizando JavaScript, não importa se eu demore 1h, 2h, 3h ou 1 dia para resolver, será feito 100% com base nos meus conhecimentos adquiridos gradativamente. E terceiro e último tópico, irá ser trabalhado junto com o segundo, pois servira como uma forma de fixar melhor o que eu for aprendendo, para não esquecer no dia seguinte xD (o que é normal quando se aprende algo novo e não tem nenhum tipo de convivência com ele). 


Por fim, para não deixar esse diário só na introdução, vou trazer um resumo do que eu aprendi de JavaScript nessas semanas (alguns dos tópicos a serem inseridos eu já tinha aprendido antes, mas aproveitei o tempo para revisar).

- Sintaxe Básica.

- Manipulação do DOM.

- Funções.

- Vetores/Arrays.

- Condições e Loops.

- Includes, endsWith e startsWith.

- Spreat Operator.

- Rest Operator.

- Desconstrução de Objetos e Arrays.
 
Além disso eu pretendo estudar mais sobre funções e objetos, Fetch API/Ajax, mais do ES6+, entender alguns conceitos de Hoisting, Event Bubbling, Scope, Prototype, Shadow DOM e strict, um pouco de NodeJS e JSON, modularização e RegEx. Assim que passar dessa etapa e ficar ferinha em JavaScript, irei focar 100% em ReactJS para aproveitar o máximo do meu foco, depois disso irei decidir entre aprender Styled Components ou TypeScript(Já tenho uma vivência breve com essa linguagem).

Por enquanto é isso, até mais!