teleren/devto huggingface dataset:
Idris2+WebGL: Hiatus
Tags: idris, webgl
Published: 2021-10-28 14:35:33

---
title: Idris2+WebGL: Hiatus
series: Idris2 and WebGL
tags: #Idris, #webgl
published: true
canonical_url: https://drbearhands.com/idris-webgl/part18/
---

I'm putting my WebGL in Idris project on hiatus. 
I started this project to get a feeling for how far I could take type-safety using dependent typing. Unfortunately, I am no longer constrained by dependent typing in general, but by Idris in particular. I might continue once significant progress has been made on the Idris compiler.

I've spent days debugging problems that turned out to be compiler problems. Error messages are extremely unhelpful. The prelude sometimes gets in the way. The syntax can be hard to read. Linear types exist but are not well-supported. The compiler code base is hard to get in to. Documentation is quite basic. In short, using Idris "in anger" is a pain in the butt, and if your problem requires Idris' particular feature set, you are probably already very angry. One doesn't typically use quantitive type theory to increment a counter. Although that is exactly whet I did in the last entry.

I'm not blaming Idris' devs for these problems. Their scope is large and time limited. Working in academia probably also forces a focus onto e.g. publications rather than nice error messages.

I don't like ending this project, because I hoped it could unify my love for type-safety with my love for 3D graphics, but after months of development I still only have a spinning white trianle, while I'm considering how supermonads qualified with dependently-typed destructors might allow monadic error handling for linear values if I can get idris to auto-construct destructors for values derived from function application. Needless to say my love for 3D graphics isn't particularly fulfilled.

However, I did sort-of get my answer.

I'm sold on dependent typing. It is actually *easier* to use dependent types. At some point there will be something you wish to express that is easy with dependent types, but quite complex otherwise. Dependent types are just doing to types what you are already doing in terms. Not conceptually difficult, just a different way of doing things that takes some "unlearning".

Linear types on the other hand are an entirely new thing. More research is needed to make them fun to use in practice, but they are already damned useful.
Re-schooling with Scrimba 
Tags: javascript, programming
Published: 2021-10-28 14:32:37

In my past life I worked as a front-end web developer holding many jobs in a variety of industries (media, non-profit, grassroots, start-up tech). I even taught Ruby on Rails (including HTML & CSS) to adult beginners in my favorite gig. Now, after a 4 year break to raise a small human, I scoured the internet for online web design and development courses that would bring me up to speed. 

Right away [Scrimba](https://www.scrimba.com) captured my attention as a great starting point for brushing up on skills. Not only do they have a ton of excellent courses (and plenty free ones), their unique video format (they call them "scrims") allows interaction with the screen so you can program right along with the instructor, copy/paste and run their **actual** code, and the resolution is crystal clear - a welcome change from squinting at YouTube videos and trying to quickly type out the code. 

So far I've taken 2 courses: *Build a Color Tool in Vanilla JavaScript* (which scratched my design itch) and *Learn Javascript for Free* (which was great for basic DOM manipulation). Both used the same teaching style: demonstrating the code or concept, then allowing the student to try it out. For the practice exercises I coded right in the screencast but for the larger projects I coded in my own editor (Brackets at the moment) so I could more easily debug and own a copy of the code.

Here are some of the projects I built:
* [Lighten/Darken Color Tool](https://codepen.io/Narwhalicorn79/pen/YzxKRwy)
* [Subway Counter](https://codepen.io/Narwhalicorn79/pen/BadKxEp)
* [Blackjack](https://codepen.io/Narwhalicorn79/pen/ZEJBeGG)

I also built a Leads Tracker Chrome Extension which was interesting and super fun. I can't wait to create my own Chrome Extensions in the future!

Scrimba is my new favorite thing to talk incessantly about (apologies to my wife) because it's not only a place to learn it's also a vibrant community. I've joined Scrimba Discord server and connected with students of all ages all over the world! There are channels like: announcements, weekly challenges, help channels, study buddies, i-built-this, i-got-hired, career chat, and my favorites for accountability: today-i-will and today-i-did. 

Next I (re-)dive into the world of React and brush up my single page application chops! Stay tuned...
How to prevent duplicate count value for inner join
Tags: tsql, query, mssql
Published: 2021-10-28 14:19:54

> When you join two tables and you want to count only the first table, you can use the **distinct** command. 

```sql
select a.OrderID, count(distinct a.Id) as Total from tblOrder a 
inner join tblOrderDetail b on a.OrderID = b.OrderID
```
Build Universal Web Components with LitElement
Tags: javascript, webdev, tutorial, html
Published: 2021-10-28 14:13:10

Written by Lior Ben David.

---


It feels like every day a new web framework appears fighting for your attention. With all these different frameworks, however, you might find yourself rewriting code to get your components working right on a new framework.

If you're looking to create a universal component library, look no further than [LitElement](https://lit-element.polymer-project.org/guide), a simple base class for creating cross-library components with their own embedded styling and javascript.

In this tutorial, I'll be showing you how to create your first LitElement component and render it in a vanilla HTML file.

---

###Setup

To get started, we're going to create a new npm project with

`npm init`

We are then going to install lit-element and Polymer with:

`npm i lit-element polymer`

Polymer isn't 100% necessary, but will just allow us to test this component easily.

Finally, let's create an `index.html` and a `card.js`

`touch index.html card.js`

###Code

Our `index.html` can be as simple as:

{% gist https://gist.github.com/LiorB-D/b6bb98e41e999b2209604b8a02b429ba %}

Note that all we need is the inclusion of the script tags to our custom component, as well as the component itself of course.

Our `Card.js` can then look as follows:

{% gist https://gist.github.com/LiorB-D/5307e6d8cdbbbb97e2a409270fcae6c3 %}

And that's all it takes! We can then serve this page live with:

`polymer server`

And lo and behold:

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

---

###Using Lit Element Anywhere

We can then use this exact same LitElement class in React, Vue, Angular, or whatever web framework you or your fellow developers prefer. All that needs to be done is to install Litelement and then access the custom tag you created.

So what do you think? Do you see a benefit of using LitElement, or is this just an extraneous layer? Let us know down below.

As always, happy coding from your friends at [Codesphere](https://link.codesphere.com/EZ), the most intuitive cloud provider on the market.
How to call C code from Rust
Tags: rust, c, ffi
Published: 2021-10-28 14:05:47

---
title: How to call C code from Rust
published: true
description: How FFI works for calling C functions from Rust, and how to link the libraries
tags: Rust, C, FFI
//cover_image: https://direct_url_to_image.jpg
---

Calling C code from Rust falls under FFI (Foreign Function Interface) and is unsafe by nature, as it's crossing Rust boundary and all the checks that comes with it.

The syntax itself is pretty simple, so create a project and:
```rust
// src/main.rs
extern "C" {
    fn print_num(num: i32);
}

fn main() {
    println!("[rust] start");
    unsafe { print_num(50) }
}
```

We are defining an external function which uses C ABI convention - which has got to do with the way stack and registers are arranged, when making a call to another function.

And for our C library:

```C
// src/num.c
#include <stdio.h>

void print_num(int num) {
    printf("[  c ] num is %d", num);
}
```

But if we `cargo run` here, we'd get `main.rs:8: undefined reference to print_num`, meaning compiler is not finding our C function so we need to link the library:

```bash
$ # in root of project 
$ cc -c src/num.c
$ cc -shared num.o -o libnum.so
```

First `cc` would generate `lib.o` but `rustc` needs a shared obejct, which is generated from that and starts its name with `lib`. Now we can link it to our Rust code (omit the `lib` at start):

```bash
$ rustc -l num -L . src/main.rs
```

Which looks for `(lib)num.so` in current `.` path. This should compile and give you the `main` binary, which can't be executed:

```bash
$ ./main
./main: error while loading shared libraries: libnum.so: cannot open shared object file: No such file or directory

$ ldd main
	…
	libnum.so => not found
``` 

Because you've used a dynamic library, and `ldd` can't find it, you can't run your binary. You can either install `libnum.so` in appropriate path or use a static library:

```bash
$ ar rcs libnum.a num.o
$ rustc -l static=num -L. src/main.rs  
$ ./main
[rust] start
[  c ] num is 50
```

Perfect! Let's simplify our workflow, create `build.rs` in root of project:

```rust
fn main() {
    println!("cargo:rustc-link-search=.");
    println!("cargo:rustc-link-lib=static=num");
}
```

And now we can use `cargo run` and `cargo build` the usual way. We can also declare the name of library where it's being used so instead of `println!("cargo:rustc-link-lib=static=num");` in `build.rs`:

```rust
// src/main.rs
#[link(name = "num", kind = "static")]
extern "C" {
    fn print_num(num: i32);
}
```

which links `libnum.a` and if we remove the `kind` part defaults to dynamic versin `libnum.so`.

Finally if you're not interested in handling the compilation of library files yourself, there's `cc` crate which takes care of that for you:

```toml
// Cargo.toml
…
[build-dependencies]
cc = "1.0"
```

And your `build.rs`:

```rust
// build.rs
fn main() {
    cc::Build::new()
        .file("src/num.c")
        .compile("anything");
}
```

And that's all!
Day 2 of 100 days of code
Tags: beginners, node, 100daysofcode
Published: 2021-10-28 14:04:01

I decided that my first project for this would be a rework of one of my openClassrooms project: the social media site ([link](https://github.com/Nicolas-Leveque/Groupomania-OpenClassrooms) if you're interested )

Yesterday I created a postgres database in Heroku and modified some of my code to connect with it via sequelize, nothing big but I noticed a problem: I initially made the decision to put pictures ( user's avatar and posts ) in the database using the blob type. Well PostgreSQL doesn't support Blob format and even if it did, the size of the database hosted on the free tier of Heroku is limited, and I'm still quite poor at the moment so in this version, pictures will go in a folder on the backend.

As I don't have a lot of time today, my goal will be to evaluate the damage and take note of all the file I need to modify to make this work.

I already made some changes in my multer config to create a destination folder and added a middleware to check if the file is an image and rename it.

First the models: to use the BLOB type I added 3 fields in the database:

```
imageType: {

	type: Sequelize.STRING,

	defaultValue: 'image/jpeg'

},

imageName: {

	type: Sequelize.STRING,

	defaultValue: 'avatar.jpg'

},

imageData: {

	type: Sequelize.BLOB('long'),

}

```

Since the pictures will be stored on the server for now on, this won't be needed anymore and a simple string with the URL of the pictures will do. This is true for the users and posts models.

```
imageUrl: {
	type: Sequelize.STRING
}
```

Then, the user.controller file: this is where I put the functions that Create, Read, Update or Delete users ( see what I did there? CRUD... nevermind ).
Initially the user couldn't select an avatar during the signup  and modify processes and there was a route dedicated to the avatar ( also a react component but I'll deal with the front-end later ). 
Since the pictures are only stored in the db as URL I should be able to do add it in the signup and modifyUser functions and get rid of the uploadAvatar function (note to myself: do not forget to delete the user's avatar when the user is deleted ).

Last (for now anyway ) but not least, the post.controller file. There is 2 functions that create posts: one for text post and another for picture post, again using URL I should be able to reduce that to one, also this would simplify the front-end as well and allow the user to add text to a picture ( again I'll deal with that later anyway ).
I'll also need to modify the SQL requests inside my get functions as they use imageType and imageData. 

Well that wasn't as bad as I initially thought, I plan to do all those modifications and will be wirting unit and integration tests using Jest as I go during the next weeks and then do the same with the front-end.
O que eu aprendi depois de 150 palestras
Tags: video, career, events
Published: 2022-02-16 21:39:44

---
title: O que eu aprendi depois de 150 palestras
published: true
date: 2021-10-28 13:55:00 UTC
tags: video,career,events
canonical_url: https://blog.lsantos.dev/150-palestras/
cover_image: https://raw.githubusercontent.com/khaosdoctor/blog-assets/master/images/2021/10/thumb.png
---

{% embed https://www.youtube.com/watch?v=FrEavuadZP0 %}

Depois de quase 6 anos criando conteúdo, eu achei que estava na hora de passar um pouco do conhecimento que eu adquiri nesse meio tempo para frente. E por isso resolvi montar essa série de vídeos sobre eventos de tecnologia.

Se você ainda não viu o primeiro vídeo da série, é só [clicar aqui](https://dev.to/khaosdoctor/5-coisas-pra-voce-saber-antes-de-palestrar-call-for-papers-50im-temp-slug-7635124) pra ter as principais dicas de call for papers que vão se alinhar muito bem com o que tem no vídeo de hoje!

## Links comentados

- [Lista de posts da Nina Zakharenko sobre palestras internacionais](https://nnja.medium.com/the-ultimate-guide-to-memorable-tech-talks-part-1-an-introduction-771811787338)
Hactoberfest and me!😀
Tags: hacktoberfest
Published: 2021-10-28 13:54:12

I completed the Hactoberfest, 2nd year in a row!!
With the arrival of the October, being able to be driven into scouring through Github to find a repo that suits me is kind of fun!!

Every year, there are new repos and along come opportunities for more learning, It really does change our community of open source! Thanks to @digitalocean_staff && @thepracticaldev for the whole experience!!
Published my first EBook on the Gang of Four Design Patterns in Java!
Tags: java, designpatterns, gangoffour, programming
Published: 2021-10-28 13:49:32


The Gang of Four Design Patterns are often hard to get .

Most of the articles on the internet are generic or too complicated to understand. I wrote a book which solves this by providing an easier explanation of all the 23 design patterns with use cases implemented in Java and with link to GitHub.

Every design pattern is presented with an use case , the solution in java and the link to Github.


Once you finish this book , you will gain more confidence about implementing design patterns in your day to day programming.

Link to the book : [The Gang of Four Design Patterns Simplified](https://vijaysrj.gumroad.com/l/designpatterns)

Topics covered:


**Creational :**

Deals with how to create objects.

Singleton – Create a single instance of an object.

Prototype– Use an existing object by cloning it.

Factory Method – Delegate creation of an object to another object.

Abstract Factory – Delegate creation of a group of related objects to another object.

Builder – Delegate creation of a complex object to another object.

**Structural:**

Deals with how to structure objects.

Adapter – Make two incompatible interfaces work together.

Bridge – Separate abstraction and implementation.

Composite – Treat part-whole hierarchy the same way.

Decorator – Add responsibilities to an object dynamically.

Facade – Provide a single interface for a group of related operations.

Flyweight – Reuse objects than creating new ones.

Proxy – Protect access to an object.

**Behavioral**

Deals with how to communicate between objects.

Chain of Responsibility – Allow different objects to carry out a responsibility.

Command – Encapsulate requests as separate objects.

Mediator – Act as a broker for communication between objects.

Template – Provide basic template of an algorithm to implement.

Strategy – Encapsulate different algorithms using separate objects which can be chosen at run time.

State – Encapsulate state specific behavior in a separate object.

Observer – Intimate group of objects when a change occurs.

Memento – Allow to revert an object’s state.

Iterator – Provide a generic way to iterate through collection of objects.

Interpreter – Represent a grammar using an object.

Visitor – Add new responsibilities to an object without changing its existing behavior.


Note : The original book by the Gang of Four was referred for these posts.


**About the author:**

I am Vijay , a full stack developer and a Tech Manager working in a multi national IT company. I have over 13 years of experience in the IT industry and have spent major part of my career working on Java and related technologies. In this book, I have tried to present the design patterns by the Gang of Four in a simplistic way yet not compromising on the quality of the content.
My Hacktober contributions in 2021
Tags: hacktoberfest
Published: 2021-10-28 13:48:35

---
title: My Hacktober contributions in 2021
published: true
description: A summary of my Hacktoberfest 2021 contributions
tags: hacktoberfest
---

<p>&nbsp;</p>
<p>&nbsp;</p>
<p>&nbsp;</p>
<p>&nbsp;</p>
<p>&nbsp;</p>
<p>&nbsp;</p>
<p>&nbsp;</p>
<p>&nbsp;</p>
<p>&nbsp;</p>
<p>&nbsp;</p>
<p>&nbsp;</p>
<p>&nbsp;</p>
<p>&nbsp;</p>
<p>&nbsp;</p>
<p>&nbsp;</p>
<p>&nbsp;</p>
<p>&nbsp;</p>
<p>&nbsp;</p>
<p>&nbsp;</p>
<p>&nbsp;</p>
<p>&nbsp;</p>
<p>&nbsp;</p>
<p>&nbsp;</p>
<p>&nbsp;</p>
<p>&nbsp;</p>

----

I wasn't too active at Hacktoberfest this year :S
🤯Aprende a fácilmente a programar para la web con estos 2 sitios
Published: 2021-10-28 13:42:22

---
title: 🤯Aprende a fácilmente a programar para la web con estos 2 sitios 
published: true
description: 
tags: 
cover_image: https://i.postimg.cc/T32JpY4q/Screenshot-2021-10-28-083139.png
---

Para quienes se están preguntando, ¿cómo puedo empezar a programar para web? quiero compartirles estos dos sitios bastante útiles:

En este sitio pueden encontrar amplia cantidad de tutoriales y lo mejor, organizado y con casos prácticos, mi sugerencia es que inicien por la sección "Programación Web"
https://www.tutorialesprogramacionya.com/

Otra herramienta muy útil es W3 School, en inglés, pero con un contenido organizado, lleno de casos prácticos y fácil para tener como guía de referencia.
https://www.w3schools.com/

Si conocen algún otro sitio que recomienden, por favor, coméntenlo para que así otras personas puedan obtener este valioso conocimiento. #programacion
Pancake Sort
Tags: algorithms, programming
Published: 2021-10-28 13:32:31

Pancake sort is a sorting algorithm that focuses on decreasing number of reversals instead of decreasing the number of comparisons which is done by traditional sorting techniques. 


It's called pancake sort as it seems like we are flipping pancakes with a spatula, thus, what we can do to sort an array is to use ***flip*** function. 


##Pancake sort algorithm: 

####flip(): 
Reverse all values from the beginning of the unsorted array till the specified index. 
####find_max(): 
Find index of maximum number within the specified range of an unsorted array. 

####pancake_sort(): 
![Unsorted Array](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/8ne29l78h8xjku5ch1vc.png)
Iteratively, decrease **current_size** of the array, knowing for a fact that array is sorted in a bottom-up manner. 
- Get the index of maximum value in the unsorted array within specified **current_size**, checks if index of maximum value doesn't equal **current_size - 1**, then we can ***flip(index of maximum value)*** and finally ***flip(current_size - 1)***

![PancakeSort 1](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/fit3cvg9d5fcgbxr097w.png)

![PancakeSort 2](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/0ils96uwbepg4gf8aqm7.png)

```python
def flip(arr, i): 
    start = 0 
    while start < i: 
        arr[start], arr[i] = arr[i], arr[start]
        start += 1 
        i -= 1 

def find_max(arr, current_size): 
    mi = 0 
    for i in range(0, current_size): 
        if arr[i] > arr[mi]: 
            mi = i
    return mi 

def pancake_sort(arr): 
    current_size = len(arr) 
    while current_size > 1: 
        mi = find_max(arr, current_size)
        if mi != current_size - 1: 
            flip(arr, mi)
            flip(arr, current_size - 1)
        current_size -= 1
    return arr


arr = [40, 20, 28, 8, 60, 33]
print(pancake_sort(arr))
```

####Time complexity:

Complexity | value
--- | ---
*Best* | **O(n)**
*Worst* | **O(n^2)**
Handling platform differences in Ansible playbooks and roles
Tags: ansible, automation, ansibleplaybooks
Published: 2021-10-28 13:18:58

If we want to use Ansible to deploy things on different targets, we need to handle differences between our targets. Thankfully, Ansible provides different language constructs for conditionally enabling certain parts of the playbook or role. 

The most basic tool is the [when] (https://docs.ansible.com/ansible/latest/user_guide/playbooks_conditionals.html) keyword that we can use to disable a task execution based on some criterion. And if we have more than one target-specific tasks to execute, we can group them into a [block] (https://docs.ansible.com/ansible/latest/user_guide/playbooks_blocks.html) and conditionally execute the whole sequence. 

But adding too many conditionals can turn readable Ansible playbooks into a giant mess. This is where [dynamic reuse] (https://docs.ansible.com/ansible/latest/user_guide/playbooks_reuse.html#includes-dynamic-re-use) comes into play (pun intended 😉). Various include statements allow us to place the platform-specific contents into separate files. And with some creative file naming, we can get rid of most of the conditionals and replace them with [parameterized includes] (https://github.com/sensu/sensu-go-ansible/blob/6b70c2e80bc74ca557854d8e473bc14c847ac813/roles/install/tasks/repositories.yml). 


*If you found these tips useful, you are welcome to subscribe to [our monthly newsletter] (https://steampunk.si/blog/) and get more tips & tricks on Ansible Collections.*
Input Form Covered In Darkness
Tags: codepen, showdev, webdev, javascript
Published: 2021-10-28 13:08:48

<h1>Input Form Covered In Darkness</h1>

<h2>Description</h2>

<p>This time, because it should be  the combination of all the pens I did for this month, I tried to combine the concepts of them all.</p>

<p>Although I didn't include the pen as it is, I took few assets from my past pens this month, and added those here.</p>

<p>In addition, I really didn't want to do this, but I couldn't think anything that is a scary UI/UX, so I made it scary because of the bad UX.</p>

<p>The main point of this pen is the darkness. User have to find the input form to be sent.</p>

<p>I created the UI of checkboxes and radio buttons using HTML and CSS.</p>

<p>Beware of flying stones! (Though it will not hit you)</p>

<h2>Resources</h2>

<p>I used <a href="https://fonts.google.com/specimen/Creepster">Creepster</a> as the font. I think this font is so scary.</p>

<p>I used <a href="https://greensock.com/">GreenSock</a> as my animation library. It is really fun to use this library.</p>

<p>Although it is an import from my previous pen, I used <a href="https://www.aseprite.org">Aseprite</a> to create the asset (Just a single stone).</p>

{% codepen https://codepen.io/takaneichinose/pen/PoKjmdX %}