teleren/devto huggingface dataset:
Delegates in C#
Tags: beginners, programming, csharp, dotnet
Published: 2023-03-22 11:41:20

Delegates are an important concept in C# programming language. They allow you to define a type-safe function pointer that can reference one or more methods with the same signature. This is useful when you want to pass a method as a parameter to another method, or when you want to store a reference to a method for later use.

In this article, we will cover the basics of delegates in C#, including how to declare, instantiate, and use them in your code.

##What is a delegate?
In C#, a delegate is a reference type that represents a method with a specific signature. A delegate can be thought of as a type-safe function pointer, which means it points to a method with a specific signature and return type. You can pass a delegate to a method as a parameter or store a reference to it for later use.

Here's an example of a simple delegate declaration:

```c#
delegate void MyDelegate(string message);
```
This declaration creates a delegate type called MyDelegate that takes a string parameter and returns void. You can use this delegate to reference any method that matches this signature.

##Creating an instance of a delegate
To create an instance of a delegate, you need to provide it with a reference to a method that matches its signature. You can do this by using the new keyword and passing the name of the method you want to reference:

```c#
MyDelegate del = new MyDelegate(MyMethod);
```
In this example, we create an instance of the MyDelegate delegate and pass it a reference to the MyMethod method. The MyMethod method should have the same signature as the MyDelegate delegate.

##Invoking a delegate
Once you have created an instance of a delegate, you can invoke it just like you would invoke any other method. You can do this by using the name of the delegate and passing any required parameters:

```c#
del("Hello, world!");
```
In this example, we invoke the del delegate and pass it a string parameter. The delegate will then invoke the method that it references, passing the same string parameter.

##Combining delegates
You can also combine multiple delegates into a single delegate using the + operator. This is useful when you want to execute multiple methods at once.

```c#
MyDelegate del1 = new MyDelegate(Method1);
MyDelegate del2 = new MyDelegate(Method2);
MyDelegate del3 = del1 + del2;
```
In this example, we create two instances of the MyDelegate delegate (del1 and del2) and then combine them into a single delegate (del3) using the + operator. When we invoke del3, both Method1 and Method2 will be executed in order.

##Removing delegates
You can also remove a delegate from a multi-cast delegate by using the - operator. This is useful when you want to remove a specific method from a multi-cast delegate.

```c#
del3 = del3 - del1;
```
In this example, we remove the del1 delegate from the del3 multi-cast delegate using the - operator. When we invoke del3 now, only Method2 will be executed.
Resolvendo problemas no HackerRank: Contando divisores de um número inteiro.
Tags: javascript, beginners, programming
Published: 2023-03-22 11:41:14

Olá, seja bem vindo a mais um Resolvendo problemas no HackerRank: No caso de hoje, vamos pegar alguns números que estão dentro de um parâmetro e após separá-los, os dividir pelo valor anterior e ver se as opções definem um resultado igual a 0, que significaria que eles são divisíveis pelo valor original. Confuso? Vejamos agora uma explicação detalhada e vejamos a resolução.

**Find Digits -**

Um inteiro `d` é um divisor de um inteiro `n` se o resto de(n /d = 0). Dado um número inteiro, para cada dígito que compõe o número inteiro, determinemos se ele é um divisor. Conte o número de divisores que ocorrem dentro do inteiro.

Vejamos alguns exemplos:

- n = 124, vamos analisar se 1,2 e 4 são divisíveis por 124 cada um em sua vez individual. Todos eles realmente são divisíveis por 124, logo retornaremos 3 pois é o comprimento de valores que são divisíveis.

- n = 111, todos são os 1s são divisíveis por 111, logo ele retornamos 3 também.

- n = 10, vamos analisar se 1 e 0 são divisíveis por 10, infelizmente 0 não é divisível por 0 (10/0, não é possível dividir 0), mas 1 é. Logo retornaremos apenas 1, pois é que pode ser retornado.


Vejamos a resolução desse código nesse momento:

```
function findDigits(n) {

 return[...n + '']
 .map(n => + n)
 .filter(d => n % d === 0).length;
}
```

No caso acima, a expressão `n + ''` transforma o valor de `n` em uma string, para que seja possível percorrer cada um dos seus dígitos com a função `map()`. O operador (...) spread é utilizado para transformar essa string em um array, de modo que possamos usar a função `map()` sobre cada caractere individualmente.

Suponhamos que o valor dentro dele fosse 10, no caso acima a expressão `n + ''` seria como 10 + '', fazendo 10 se tornar uma string( "10"), o fazendo percorrer o `.map, porém como o spread vem antes disso, ele separa individualmente os valors para cada caractere indiviual. Sendoa assim, o 10, se tornaria "[1]" e "[0]".

A função `.map` retorna cada parâmetro dentro de `n` ( que no exemplo rápido atrás seria "[1]" e "[0]" que foram desmembrados e separados em arrays próprios. O operador + é utilizado para transformar cada um desses dígitos de volta em um número. Sendo assim, agora seria [1] e [0].

Ao finalizar, fazemos um `filter` visto que nós queremos pegar o valor deles ali dividido pelo seu valor original de `n`e ver se ele é igual a 0. A função filter() é usada para filtrar apenas os números que são divisíveis por n sem deixar resto. Esses números são armazenados em um novo array. E depois pegamos o comprimento do valor final que é o que desejamos.

O resultado será:
1 e 2 são divisíveis por 12, logo retornamos 2. Já 1,0,1 e 2, somente 1,1 e 2 são divisíveis por 1012, retornamos 3.



Assim, concluímos mais um _Resolvendo problemas no HackerRank:_ até a próxima.
Programação funcional: o que são funções puras, determinísticas e que não provocam efeitos colaterais
Tags: javascript, programming, computerscience, braziliandevs
Published: 2023-03-22 11:38:27

**Programação funcional** é um paradigma de construção e desenvolvimento de um software baseado em funções. Essas funções podem ser puras, que não provocam efeitos colaterais, ou impuras. 


## Funções Puras


É uma função que dada a mesma entrada (parâmetros), sempre retornará a mesma saída. Por conta disso, também são conhecidas como funções **determinísticas**.

A função a seguir, responsável por somar 2 valores, sempre retorna a mesma saída quando a mesma entrada é informada:

```javascript
function sum (num1, num2) {
  return num1 + num2
}

sum(1,2) // sempre vai retornar 3
sum(2,2) // sempre vai retornar 4

```

Além disso, funções puras também são conhecidas por não provocarem **mutação de estado** ou **efeitos colaterais**. Isso significa que uma dependência externa (e.g variável) nunca pode ser alterada.

A seguir, vamos conhecer alguns exemplos de funções impuras.

## Funções Impuras

Analise o seguinte trecho de código:


```javascript
let message =  'Hello'

function showMessage (newMessage = message) {
  message = newMessage
  alert(message)
}

showMessage() // o alerta exibe o texto 'Hello'
console.log(message) // Hello

showMessage('Bye, Bye') // o alerta exibe o texto 'Bye, Bye'
console.log(message) // Bye, Bye
```

A função `showMessage` provoca um efeito colateral ao alterar o estado de uma variável externa: `message`. Logo, esta função é considerada impura.

> Se uma função tem dependência de uma ou mais variáveis que podem ser alteradas, a função é considerada impura.

---

Lembra que as funções puras retornam sempre o mesmo valor ao passar como parâmetro a mesma entrada?

Pois bem, nas funções impuras isto não acontece.

As funções impuras podem retornar diferentes valores para a mesma entrada. No exemplo a seguir, a função `multiplication` pode retornar um valor diferente a cada chamada:


```javascript

let multiplicationTable = 2;
function multiplication(num) {
  return num * multiplicationTable
}

```

Neste caso, a função `multiplication ` tem uma dependência externa, a variável `multiplicationTable`. Ao chamar a função `multiplication` passando o valor 5 como parâmetro o retorno é 10:

```javascript
multiplication(5) // retorna 10
```


Mas, se o valor da variável `multiplicationTable` for alterado em outro momento no código, ao acionar a função `multiplication` mesmo passando o valor 5 como parâmetro, a função vai ter um retorno diferente:

 ```javascript
multiplicationTable = 3

multiplication(5) // retorna 15
```

## Conclusão

Um software construído com base no paradigma funcional é composto tanto por funções puras e impuras. O ideal é construir uma aplicação através do desenvolvimento do maior número possível de funções determinísticas.

As funções puras são mais fáceis de testar, debugar e de fazer manutenção. Além do mais, é altamente recomendável que seu código tenha uma alta cobertura de casos de testes para funções puras.
Wednesday Links - Edition 2023-03-22
Tags: java, jvm, spring, postgres
Published: 2023-03-22 11:38:10

The Arrival of Java 20! (9 min)🎉
https://inside.java/2023/03/21/the-arrival-of-java-20/

JDK 20 G1/Parallel/Serial GC changes (8 min)🗑️
https://tschatzl.github.io/2023/03/14/jdk20-g1-parallel-gc-changes.html

Spring Data JPA introduces query parser! (3 min)🔪
https://spring.io/blog/2023/03/21/spring-data-jpa-introduces-query-parser

From a Fan: On the Ascendance of PostgreSQL (6 min)🐘
https://thenewstack.io/from-a-fan-on-the-ascendance-of-postgresql/

Web fingerprinting is worse than I thought (5 min)🖐️
https://www.bitestring.com/posts/2023-03-19-web-fingerprinting-is-worse-than-I-thought.html
Encryption/decryption specialist
Tags: blockchain, crypt, seed, key
Published: 2023-03-22 11:31:50

Hi,

I'm a CAD designer/physical prototyper not a software specialist. I'd like to communicate privately with a programmer that has expertise in crypto, blockchain, encryption/decryption, private/public keys, etc. If kind enough to respond, please be patient if I lack specialist knowledge of what you do or if I am ignorant of technologies that already exist. My only experience of coding was with Basic 30-40 years ago!

Many thanks,

John
Trig.JS - The easy way to create CSS animations that react to the element's position on screen.
Tags: animation, javascript, webdev, productivity
Published: 2023-03-22 11:27:47

Hi all,

You know these fancy animations Apple made a few years ago that moves as you scroll down and then as you scroll back up again? No? Well they look pretty cool.

I looked into this and maybe I wasn't looking in the right places but all I could find was frameworks that require JS to be wrote to achieve.

I had a think and wondered if CSS variables could actually make this a simple effect to achieve. My idea worked and actually turned out to be incredibly simple and lightweight but highly effective!

You can check it out in the documentation here: 
[https://idev-games.github.io/Trig-JS/](https://idev-games.github.io/Trig-JS/)

Github: [https://github.com/iDev-Games/Trig-JS](https://github.com/iDev-Games/Trig-JS)
NPM: [https://www.npmjs.com/package/trig-js](https://www.npmjs.com/package/trig-js)
Mastering Agile development as a beginner
Tags: programming, javascript, scrum, agile
Published: 2023-03-22 11:18:05

Agile development is a popular approach to software development that emphasizes collaboration, flexibility, and responsiveness to change. Here are some tips for mastering [Agile](https://stiffcranks.com/) development as a beginner:

**Learn the Agile Manifesto**: The Agile Manifesto is the foundation of the Agile approach. It outlines the values and principles that guide Agile development. It is important to understand the values and principles in the Agile Manifesto so that you can apply them to your work.

**Familiarize yourself with Agile methodologies**: There are several Agile methodologies, including Scrum, Kanban, and Extreme Programming. Each methodology has its own set of practices and guidelines. It is important to understand the differences between these methodologies so that you can choose the one that works best for your team.

**Embrace iteration and continuous improvement**: Agile development is all about continuous improvement. Embrace the idea of [iteration](http://highpotent.com/) and focus on making small, incremental improvements to your processes and products.

**Prioritize collaboration and communication**: Agile development emphasizes collaboration and communication between team members. Make sure that you are communicating effectively with your team members and stakeholders.

**Use Agile tools**: There are many Agile tools available to help you manage your projects, including project management software, communication tools, and collaboration platforms. Familiarize yourself with these tools and use them to streamline your workflow.

**Practice Agile values and principles**: Agile development is more than just a methodology, it's a mindset. Practice the Agile values and principles in your daily work and strive to create a culture of collaboration, transparency, and continuous improvement.

**Learn from experience**: Agile development is an iterative process, so it's important to learn from your experiences and use that knowledge to improve your work. Reflect on your successes and failures and use that information to make improvements to your processes and products.
Making of Among Us in Discord - DEVBLOG 3 - Help Section and Help me...?
Tags: 100daysofcode, python, gamedev, discord
Published: 2023-03-22 11:12:44

{% embed https://twitter.com/MrStiK101/status/1638496254496849921?s=20 %}

{% embed https://twitter.com/MrStiK101/status/1638606636573925408?s=20 %}

Heya, This is Mr.StiK, again, again (again)

So today's progress was all on Help Section for the Bot (like I planned, I'll work on it). And I did a bit of it...

**PART 1:**

But I had a *small tiny issue*…which you can see in the twitter post's 1st image, the message had *2 embeds*… which was something I didn't wanted, I tried to check code, nothing. Re-type it, nothing. **DELETE THE CODE**, and still the message comes... somewhat I would say, `stuck-code`. That embed message was the one I was working on, but then, my laptop was out of charge, and the whole token thing had some issue, I don't know, didn't notice, and that was the reason. I realized this when I asked my dear discord.py server, and one guy said 'Have you tried resetting the token?'

I tried... **it worked!** You can see the result on Image 2 (go to the 1st original original tweet to see it completely)…

So yeah, lesson truly learnt!

And I wasted 4 hours on this...



...




**B R U H**


**PART 2:**

SO it's night, but I completed the help section!!! with ephemeral messages too!!! Worth the night :) .

Anyways, I'm tired, going to hit the sack.

Toodles.
Secure SSO with Drupal
Published: 2023-03-22 10:53:11

SimpleSAMLphp in Drupal is great, but documentation around a _secure_ setup is lacking. So, here's that.

tldr;
	
1. Set a `SIMPLESAMLPHP_CONFIG_DIR` environment variable to point to a committed config directory (typically, I set it to `config/simplesaml/config`).
2. In that config directory, copy the the appropriate template config files with the sensitive data set to look at environment variables (e.g. Replace the original `saml20-idp-remote.php` hash value with `getenv('SIMEPLE_SAML_METADATA_CERT_KEY')`).
3. supply saml.crt and saml.pem SSL uncommitted certs to the certdir configured in config/simplesamlphp/config/config.php.
SearQ: A RESTful search engine
Tags: showdev, ruby, rails, api
Published: 2023-03-22 10:40:38

Hello everyone!!! 

Today I want to tell you about my personal Rails project, [SearQ](https://searq.org), a search engine based on RSS feeds that I developed myself as an open source REST API.

SearQ was born from the idea of creating a fast and scalable search engine that can handle a vast amount of information from different sources. 

Using RSS feeds, SearQ is able to extract the information needed for searches, making it an attractive option for those looking to integrate a search engine into their projects.

SearQ also offers two additional tools: **Export** and **Flow**.


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

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

Export allows users to extract a query in CSV format, while Flow enables the creation of a custom JSON endpoint based on a query.

These tools provide even more flexibility and customization for developers working with SearQ. It's great to see that you are constantly updating and improving the project, and are open to suggestions and collaborations.

But the most interesting thing about SearQ is the REST API I developed to allow developers to integrate the search engine into their applications. Thanks to this API, SearQ becomes extremely flexible and customizable, adapting to the needs of individual projects.

To develop SearQ, I used Ruby with [Meilisearch](https://www.meilisearch.com) an open-source, lightning-fast, and hyper-relevant search engine that fits effortlessly into your apps, websites, and workflow...and several open source libraries. 

But the real strength of SearQ is the ability to customize the search experience. Through the use of RSS feeds, it is possible to choose the sources from which to extract information, giving the ability to create thematic and specialized search engines.

SearQ is an evolving project, and I am constantly striving to update and improve it. I am always open to suggestions and collaborations, and I am sure that SearQ can become an interesting option for those looking to integrate a search engine into their projects.

{% embed https://github.com/searq/searq.org %}

If you are a developer looking for a REST API for search, I encourage you to take a look at SearQ. You will find an open source project that can offer many customization options and a fast and scalable search experience.
GETTING STARTED WITH SENTIMENTAL ANALYSIS
Published: 2023-03-22 10:33:04

Sentiment analysis, also known as opinion mining, is a subfield of natural language processing that involves the identification and extraction of subjective information from text. This type of analysis can be incredibly useful for businesses, social media platforms, and other organizations that need to understand how people feel about their products, services, or ideas. In this article, we will cover the basics of getting started with sentiment analysis in machine learning.

Step 1: Gather Data

The first step in any machine learning project is to gather the data you will use to train your model. In the case of sentiment analysis, you will need a large dataset of text that has been labeled with its corresponding sentiment. There are several sources of this type of data, including social media platforms, online review sites, and customer feedback forms.

Step 2: Preprocess the Data

Once you have gathered your data, you will need to preprocess it to make it suitable for machine learning. This may include tasks such as removing stop words (common words like "the" and "and" that don't carry much meaning), stemming (reducing words to their root form), and converting text to lowercase.

Step 3: Choose a Machine Learning Algorithm

There are several machine learning algorithms that can be used for sentiment analysis, including Naive Bayes, Support Vector Machines (SVMs), and Recurrent Neural Networks (RNNs). Each algorithm has its own strengths and weaknesses, and the choice will depend on the specifics of your project. Naive Bayes and SVMs are often used for smaller datasets, while RNNs are better suited for larger datasets with more complex patterns.

Step 4: Train Your Model

Once you have chosen your algorithm, you can begin training your model. This involves splitting your dataset into training and testing sets, and then using the training set to teach your model how to recognize sentiment in text. You will need to fine-tune the parameters of your algorithm to achieve the best performance on the testing set.

Step 5: Evaluate Your Model

After training your model, you will need to evaluate its performance on a separate dataset that it has not seen before. This will give you an idea of how well your model will perform in the real world. There are several metrics that can be used to evaluate the performance of a sentiment analysis model, including accuracy, precision, recall, and F1 score.

Step 6: Deploy Your Model

Finally, once you are satisfied with the performance of your model, you can deploy it in a real-world application. This may involve integrating it into an existing platform or building a new application around it.

Conclusion

Sentiment analysis is a powerful tool for understanding how people feel about a particular topic or product. By following the steps outlined in this article, you can get started with sentiment analysis in machine learning and build your own model that can analyze text and identify sentiment with high accuracy.
Creating users in airflow
Published: 2023-03-22 10:12:34

Log into the webserver container and run the commands below

su airflow

```
airflow users create \
    --username tom \
    --firstname Tom \
    --lastname Ford \
    --role Admin \
    --email tom@example.com \
    --password 2SAX63dccFW4cmtdMrc
```


airflow users list
IncludeMembers in AutoMapper for mapping relations
Tags: automapper, csharp
Published: 2023-03-22 10:11:20

Sometimes you need to grab a value from a relations table, as in this case the sortorder of the specific relation between a "list" and an "item".

Using Automapper i have always had issues with this and usually just been lazy and mapped the other properties manually or used the AfterMap feature.

But today i found out about the IncludeMembers method. It's super simple and you just include the inner property and automapper will treat it just like it's "merged" with the actual source.

```csharp
CreateMap<ListItemRelation, ItemForCustomList>()
   .IncludeMembers(s => s.Item)
   .ForMember(dest => dest.SortOrder, o => o.MapFrom(src => src.Sortorder)));
```
Instance and Non-instance properties
Tags: webdev, javascript, beginners, programming
Published: 2023-03-22 09:57:30

In JavaScript, instance properties are properties that belong to an instance of a class or an object, while non-instance properties are properties that belong to the class or the object itself.

- **Instance properties** are defined inside the class constructor using the "this" keyword, and they can be accessed and modified using the dot notation on an instance of the class:

```
class Person {
  constructor(name, age) {
    this.name = name; // instance property
    this.age = age;   // instance property
  }
}

const john = new Person("John", 30);
console.log(john.name); // "John"
john.age = 31;
console.log(john.age); // 31
```

- **Non-instance properties**, on the other hand, are defined outside the class constructor or object literal using the class name or object name, respectively. They can be accessed and modified using the dot notation on the class or object itself:

```
// Class example
class Person {
  static species = "Homo sapiens"; // non-instance property
}

console.log(Person.species); // "Homo sapiens"

// Object example
const person = {
  name: "John",
  age: 30,
};

person.gender = "Male"; // non-instance property
console.log(person.gender); // "Male"
```
In the above example, Person.species is a non-instance property of the Person class, while person.gender is a non-instance property of the person object. Non-instance properties are typically used to define values that are shared among all instances of a class or all objects of a certain type.