teleren/devto huggingface dataset:
Raku: Van Eck Sequence Generator
Tags: raku
Published: 2020-09-29 15:26:17

---
title: Raku: Van Eck Sequence Generator
published: true
description: 
tags: raku
---

One of the tasks from [Perl Weekly Challenge #14.1][1] is to write a program to produce Van Eck sequence. I knew I've heard of it, and yes, it's from a Numberphile video: [Numberphile -- Don't Know (the Van Eck Sequence)][4] and [OEIS/A181391][3].

To describe the Van Eck sequence: The first term is 0, and the following terms are defined to be the number of occurrences of the previous term, subtracted by the term index.

    a[1] = 0
    a[n+1] = 0, if a[n] is absent within a[0..n]
    a[n+1] = n - m, Otherwise, where a[m] = a[n] and m < n and m is the largest of such.

By definition, to compute `a[n+1]`, we look backward the entire sequence for `a[n]`.

[~laurent_r][5] offered a loop-based solution:

    use v6;
    
    my @a = 0,;
    for ^20 -> $n {
        my $result = 0;
        for reverse ^$n -> $m {
            $result = $n - $m and last if @a[$m] == @a[$n];
                # Note: $m is always smaller than $n, so $n - $m > 0
        }
        push @a, $result;
    }
    say @a;

Given the infinite nature of this sequence, I would like to make an object that represent this infinite sequence and, of course, lazily evaluated. Here's the result:

```raku
my $vaneck = Seq.new(
    class :: does Iterator {
        has %!seen is default(-1);
        has Int $!term = -1;
        has Int $!pos  = 0;
        method pull-one {
            my $next = %!seen{$!term} == -1 ?? 0 !! $!pos - %!seen{$!term};
            %!seen{$!term} = $!pos++;
            return $!term = $next;
        }
    }.new()
);
```

[Seq][6] and [Iterator][7] are both builtin Types in Raku. `%!seen` is a private variable for recording the position of previous occurrence of numbers.

Here's how you print the beginning 200 terms:

    $vaneck[^200].map({ .say });

... or just keep it printing forever:

    $vaneck.map({ .say });

----

本文為 [Perl6: Van Eck 數列產生器][8] 之英文版。

[1]: https://perlweeklychallenge.org/blog/perl-weekly-challenge-014/
[2]: https://github.com/gugod/bin/blob/master/gen-van-eck-sequence
[3]: https://oeis.org/A181391
[4]: https://www.youtube.com/watch?v=etMJxB-igrc
[5]: http://blogs.perl.org/users/laurent_r/2019/06/perl-weekly-challenge-14-van-ecks-sequence-and-us-states.html
[6]: http://docs.perl6.org/type/Seq
[7]: http://docs.perl6.org/type/Iterator
[8]: https://gugod.org/2019/08/perl6-van-eck-sequence-generator/
Why you should use Framer Motion
Tags: react, javascript, beginners, productivity
Published: 2020-09-29 15:25:48

## What is Framer Motion?

Think of Framer Motion as more of an improvement or reinvention of an existing animation library than a brand new one.

Framer Motion is the successor to [Pose](https://popmotion.io/pose/), which was one of the most popular animation libraries used with React. Like Pose, it’s built upon promotion, which is a low-level, unopinionated animation library, but it provides abstractions to streamline the process.

Framer Motion improves upon and simplifies the API in a way that couldn’t have been done without breaking changes and rewriting. One difference is that whereas Framer Motion only has support for React, Pose has support for React-Native and Vue. If you’re currently using Pose I would recommend updating to Framer Motion because Pose has been depreciated.

## Why use Framer Motion?

1. If most animation libraries use spring-based animations, then, why should you use Framer Motion? For starters, it has a great API that is simple and doesn’t fill your components with extra code. In most cases, you can simply replace your HTML element with a motion element — for example, div with motion.div, which results in the same markup but has additional props for animation.

2. Framer Motion is capable of powering animations in Framer X, a prototyping tool, which makes the hand-off extremely convenient. The majority of designers have suffered a situation when they spend ages perfecting every little detail of design only to have it lost in the development process. Framer Motion lets you use the same animation library both in prototyping and production. This way you don’t need to worry your animations are different from what you’ve intended them to be.

## How do I start?

1. Install the Framer Motion package.

`npm install framer-motion` (if you are using `npm`) 
  or 
`yarn add framer-motion` (if you are using `yarn`)

2. Import the `motion` component in your file.

```
import { motion } from 'framer-motion';
```

3. Try to animate an element using the `animate` attribute. <br />

⚠️ Remember: you are not using more `css` syntax or attributes, they all are from Framer Motion

```
export default function App() {
  return (
    <motion.h2
      animate={{ scale: 1.2 }}
    >
      Yayy, I am animated!!
    </motion.h2>
  )
}
```

  You can notice two important things:

  1. `motion` always comes before the HTML tag (just make sure on the [documentation](https://www.framer.com/api/motion/component) if Framer Motion supports)
  2. `animate` attribute pass an object (like the `style={{}}`)

4. See [my repository](https://github.com/esau-morais/framer-motion) about Framer Motion and learn how it works.

5. See this [playlist](https://www.youtube.com/playlist?list=PL4cUxeGkcC9iHDnQfTHEVVceOEBsOf07i) on YouTube about Framer Motion.

## References

[LogRocket](https://blog.logrocket.com/another-react-animation-library-heres-why-you-should-use-framer-motion/)
[Medium](https://medium.com/better-programming/smooth-animations-with-react-and-framer-motion-c272b6f22f67)
Does Sidecar really matter in Kubernetes?
Tags: kubernetes, opensource, devops, codenewbie
Published: 2020-09-29 15:22:44

Sidecars and Kubernetes have been going hand in hand since a long time now, for they have become an increasingly booming topic in the container world for its functional utility. It is an interestingly essential aspect of the Kubernetes containers that helps skyrocket your business to the next level.<br>
Let's dive into the topic!<br>
![Alt Text](https://dev-to-uploads.s3.amazonaws.com/i/vgmqgom84kwsifs55wow.png "logging with sidecar agent") 
* We would have come across the mastermind of Kubernetes - The Pods. Pods are those single deployments of Kubernetes which consists of the container. Pods can hold multiple containers but these containers run on the shared volume and network.
* Sidecars can be considered a sibling of Pods that help ease the tasks of the container and so use its resources. Though used over a long period, the pattern of sidecars was not supported as the Kubernetes built-in feature. When more containers started embracing the pod, it was only then that the Sidecars pattern was considered.<br>

**Instances of Sidecar Container usage**<br>
* When you need access to the past 24 hours' error logs, you need to lend access to the webserver for a *log-aggregation service*. This shipping process is carried out by the Sidecars, post their deployment. Note that, it deploys two containers to the same pod. Hence, when you target to use the kubectl command, you also target the main Container by default.

* Another established use case of Sidecar is the Proxies in a *Service mesh architecture*. A service mesh can be deployed in two patterns: Per-host Proxy deployment and Sidecar Proxy deployment. When we consider the Sidecar proxy deployment, one sidecar proxy would be deployed per service container which is useful in the case of Kubernetes pods.<br>

**Challenges** 🤯

Container life cycle dependencies are the major challenge for the Sidecar. Since there is no difference between the Pod containers, it is difficult to determine which Container start first and which one wraps up in the last. So the efficient running of the Sidecar container is essential in order to meet the requirements of the main application.<br>
**Take away for today**<br> <span style='font-size:100px;'>&#9997;</span>
* <a href="https://kubernetes.io/docs/tasks/access-application-cluster/communicate-containers-same-pod-shared-volume/"> Official Documentation </a> 
* <a href="https://labs.play-with-k8s.com/"> Free K8s playground</a> 
* <a href="https://training.play-with-kubernetes.com/"> Slack Communities</a>
* <a href="https://www.katacoda.com/courses/kubernetes/playground"> Katacoda Kubernetes playground</a>

<code><p><br>
*Follow our community for more goodies, stickers, t-shirts* <span style='font-size:100px;'>&#128521;</span><br>
<a href="https://twitter.com/GitlabC">Twitter</a><br>
<a href="https://www.meetup.com/GitLab-Meetup-Coimbatore/">Meetup Group</a><br>
<a href="https://www.linkedin.com/groups/8955040/">LinkedIn Group</a><br>
</p></code>
Migrate your Magento eCommerce Store with Latest Version of Magento 2.0
Published: 2020-09-29 15:19:53

Are you running online store in Magento Platform?

Then, it's the right time to upgrade your online store with latest version of Magento 2.0 as the old version is not worked now. Hence, you are advised to upgrade your Magento eCommerce online shop immediately or you may lose the business sale.

Ok, then you might think of how and where can I find the best and affordable Magento service provider? 

Please contact apptomate, a comprehensive eCommerce website development company located in India, USA & Germany have well experienced qualified Magneto eCommerce professionals, Magento 2 Developers, Magento 2 Programmers and Certified Magento 2 Experts who are ready to work for you remotely and hence you can upgrade your online store easily without any hassle.

If you're willing, then hire a dedicated Magento 2 Developer and Certified Magento 2 Expert from apptomate and get upgraded your online store in a short span of time. For further clarifications and other details, please feel free to contact apptomate support team at hello@apptomate.co
Create a log service with PHP and Clickhouse [Part 1]
Tags: php, database, vector, logging
Published: 2020-09-29 15:16:57

I would like to share my experience configuring a very simple logging service with PHP and Clickhouse. I would like to stress that this is by no mean an optimal setup, I simply want to share my experience and I would love to hear feedbacks to improve.

## Requirements
1. A very simple logging service to track all kinds of events such as nginx error or php error internally and externally. I find ELK too complicated to properly setup and guard, and too resource intensive (and thus costly) for my needs.
2. Performant enough to handle tens of millions of logs per day on an average server (I pick the Vultr instance below which has 2 CPU and 4 GB of RAM). I'm handling over tens of million logs per day with this setup and still have resources to spare.

## Tech stacks
1. PHP
2. Clickhouse
3. Vector

**Why PHP?**
Because I'm familiar with it and because why not? I don't want to spend days and weeks trying to learn a new thing just for something really quick that I can do for a 1-2 hour with PHP.

**Why Clickhouse?**
Clickhouse is a very performant, easy-to-setup database designed and optimized for writing data. I have great experience using it to track views and clicks on my website.

**Why Vector?**
I looked at many log collectors such as syslog, syslog-ng, filebeat etc... I'm not a system guy and their documents are terrible, terrible. Filebeat is not so bad but I was not entirely impressed with it (I used it in the past). Then I found Vector and I was blown away by the website (so clean), the documents, the options, and the support.

## Preparation
First, we need to collect the logs. Vector is super simple for collecting logs, you can find the website here with all the documents:

https://vector.dev/

I'm going to share some of my current configs, please do note that I'm a Vector virgin, so please do review before use and please let me know if I can improve anything:

https://gist.github.com/yellow1912/782d53cb97b9de86d4fdb2848cc2e520

You will notice that I'm opting to send the logs to a remote server via http/https protocol. You can choose any other protocol you want. I also pass along an authorization token so my log service can check.

Next time, I will cover Clickhouse database setup.
Projects for beginners to ''practice'' ?
Tags: webdev, beginners, help, codenewbie
Published: 2020-09-29 15:14:55

Hi! I'm new to this website and coding in general, I've been ''studying'' for about 2 weeks. I bought 5 webdev courses on Udemy (Front end bootcamp, Javascript Essentials, CSS, Advanced CSS, Flex, etc.. etc...) with a total of 150 ish hours of lessons.
I'm about 25 hours in and I've mostly just been watching the lessons and copying what they're doing to VS Code on my other screen.

Although I feel like I'm learning it feels like I wouldn't be able to do it on my own without seeing someone else do it first.

Is there a website with cool projects for beginners to practice?
Obviously I would need google and some documentation but I don't wanna just ''copy'' someone because I feel I need to learn to do it on my own, does that make sense?


Thanks!
Angular NgModule System needs one simple change
Tags: angular
Published: 2020-09-29 14:53:12


When the Javascript module system was codified, it was an immediate blow to the Angular NgModule system.

Indeed if we are creating Angular libraries and look at the compiled distribution folder output, all the NgModules collapse. They all point to just one or more Javascript index.js files like this:

```typescript
//One or more exports
✔️ export * from filename.js
```

There is nothing more simple than one or more export statements in an index.js file that define a known ECMA module.  Need more than one module for separation of concerns? Just create another index.js file in another folder. 

The ngModule system is legacy and just needs to be changed. Some may argue in favor of it, for them the feature should stay as is.  For others, that prefer the other way, a simple option should be allowed for every new Component, Directive, Service etc. Instead of specifying an NgModule we should be able to pick an index.js file. 

[I opened a ticket to Angular](https://github.com/angular/angular/issues/38056) on the subject and see other's have too.

JWP2020 Allow Index.ts files in NgModule System.
Matt's Tidbits #82 - An unexpected Mockito limitation
Tags: mattstidbits, android, testing, tidbittuesday
Published: 2020-09-29 14:44:14

[Last week I wrote about the importance of taking vacation.](https://medium.com/@matthew.b.groves/matts-tidbits-81-the-importance-of-vacation-fcff932cda71) This time, I have a story to share about an unexpected Mockito limitation.

Consider this example code:
{% gist https://gist.github.com/mpeng3/99a6b3b1bfe222984652e507523b4adf %}

If you want to mock out the `ListProvider` in your unit tests, it's pretty simple to do the following:
{% gist https://gist.github.com/mpeng3/2911a827d22e810523b9bdae56ea254e %}

Where this gets tricky is when you think about providing a mock implementation for `ListProvider.currentList`. At first, I thought about just doing this:
```kotlin
whenever(mockListProvider.currentList).thenReturn(listSubject.value)
```

The problem with this is that if you post a new value to the `listSubject`, it will not be reflected in future calls to `ListProvider.currentList` because the mock (and by extension, the underlying subject) is evaluated at the time it is defined.

One workaround I came up with was to define a method like this for tests:
{% gist https://gist.github.com/mpeng3/43edf9e9498ea7214e354ca5b5be70a0 %}

Using this instead of the `listSubject` directly allows you to update the mock value for `currentList` simultaneously.

However, this has some limitations - namely, as a coworker pointed out, it's a little bit messy to re-initialize the mock each time.

Thankfully, Mockito provides another option that's a little bit better suited to this - enter the [`thenAnswer()`](https://javadoc.io/static/org.mockito/mockito-core/3.5.13/org/mockito/Mockito.html#answer_stubs) method:
```kotlin
whenever(mockListProvider.currentList).thenAnswer { listSubject.value }
```

Something to be careful of with this method is that it's not type safe - it would be perfectly valid to write `.thenAnswer { 42 }`, and you would only find out when running your tests that you had done something wrong.

One more thing to consider - Mockito isn't the most Kotlin-friendly framework out there, so if the majority of your code is in Kotlin, I would highly encourage you to consider [MockK](https://mockk.io), which lets you write this same code like this:
{% gist https://gist.github.com/mpeng3/56061c36102034e2158e8e5588233634 %}

Do you have any ideas/suggestions for how to further improve on this? Let me know in the comments below! And, please follow me on Medium if you're interested in being notified of future tidbits.

*This tidbit was discovered on June 25, 2020.*
Maintain state in Serverless
Tags: watercooler, news
Published: 2020-09-29 14:42:13

#Workers Durable Objects Beta: A New Approach to Stateful Serverless

##What is a "Durable Object"?

I'm going to be honest: naming this product was hard, because it's not quite like any other cloud technology that is widely-used today. This proverbial bike shed has many layers of paint, but ultimately we settled on "Unique Durable Objects", or "Durable Objects" for short. Let me explain what they are by breaking that down:

**Objects**: Durable Objects are objects in the sense of Object-Oriented Programming. A Durable Object is an instance of a class -- literally, a class definition written in JavaScript (or your language of choice). The class has methods which define its public interface. An object is an instance of this class, combining the code with some private state.

**Unique**: Each object has a globally-unique identifier. That object exists in only one location in the whole world at a time. Any Worker running anywhere in the world that knows the object's ID can send messages to it. All those messages end up delivered to the same place.

**Durable**: Unlike a normal object in JavaScript, Durable Objects can have persistent state stored on disk. Each object's durable state is private to it, which means not only that access to storage is fast, but the object can even safely maintain a consistent copy of the state in memory and operate on it with zero latency. The in-memory object will be shut down when idle and recreated later on-demand.

##What can they do?

Durable Objects have two primary abilities:

**Storage**: Each object has attached durable storage. Because this storage is private to a specific object, the storage is always co-located with the object. This means the storage can be very fast while providing strong, transactional consistency. Durable Objects apply the serverless philosophy to storage, splitting the traditional large monolithic databases up into many small, logical units. In doing so, we get the advantages you've come to expect from serverless: effortless scaling with zero maintenance burden.

**Coordination**: Historically, with Workers, each request would be randomly load-balanced to a Worker instance. Since there was no way to control which instance received a request, there was no way to force two clients to talk to the same Worker, and therefore no way for clients to coordinate through Workers. Durable Objects change that: requests related to the same topic can be forwarded to the same object, which can then coordinate between them, without any need to touch storage. For example, this can be used to facilitate real-time chat, collaborative editing, video conferencing, pub/sub message queues, game sessions, and much more.

How exciting 😁 and just what I needed when I migrated a database and had to reimplement GraphQL service.
Chaining comparison operators
Tags: perl, raku, python3
Published: 2020-09-29 14:40:33

---
title: Chaining comparison operators
published: true
description: 
tags: perl, raku, python3
---

The syntax of chaining multiple comparisons is pretty common in mathmatics, with one expression such as `$a < $b < $c`, the relation of multiple variables are described. [It is not commonly seen in programming languages though.][1]

Raku (formly, Perl6) supports this syntax since the very beginning. As an example program, `num-within`, which is designed to read numbers from STDIN and echo them back if and only if they are within the range `$from...$until`:

    #!/usr/bin/env raku
    ## Usage: num-within <from> <until>

    my ($from, $until) = @*ARGS[0, 1];

    for $*IN.lines() -> $num {
        if $from <= $num < $until {
            say $num
        }
    }

Used like this:

    # bash -c 'while true; do echo $RANDOM; done' | num-within 100 120
    114
    165
    155
    130
    161
    199
    108
    115
    153
    166
    ...

Python3 also supports comparison chaining. Here's the same program in python3:

    #!/usr/bin/env python3
    ## Usage: num-within.py <from> <until>
    
    import sys
    
    num_from  = int(sys.argv[1])
    num_until = int(sys.argv[2])
    
    for line in sys.stdin:
        n = int(line)
        if num_from <= n < num_until:
            print(str(n))

Recently [Perl5 started to partially support comparison chaining since version 5.31.10][2], and latter 5.32.0. Here's `num-within` in Perl5:

    #!/usr/bin/env perl
    ## Usage: num-within.pl <from> <until>
    use v5.31.10;

    my ($from, $until) = @ARGV[0,1];

    while(defined(my $num = <STDIN>)) {
        if ($from <= $num < $until) {
            print $num;
        }
    }

Obviously there are many other usages than just checking the boundary of a given variable. `max3(a,b,c)` would be a good example (take the maximum out of 3 values):

    sub max3($x, $y, $z) {
        return $x if $y <= $x >= $z;
        return $y if $z <= $y >= $z;
        return $z;
    }

However, the implementation in Perl5 at the moment is still less ideal. Considering this expression:

    $a < $b == $c < $d

... express the same meaning in Raku, Python3, and in math, which is:

    ($a < $b) and ($b == $c) and ($c < $d)

On the other hand, in Perl5, it is currently logically equivalent to this:

    ($a < $b) == ($c < $d)

This descrepancy is due to the fact that `==` operator in Perl5 cannot be one part of a comparison chain, which is actually [documented in perlop since perl-5.31.11.][3] (Arguabaly not directly documented, but could be derived from the precedance table.) Perhaps we need to wait a little bit longer.

[1]: https://softwareengineering.stackexchange.com/questions/316969/why-do-most-mainstream-languages-not-support-x-y-z-syntax-for-3-way-boolea
[2]: https://metacpan.org/pod/release/XSAWYERX/perl-5.31.11/pod/perl53110delta.pod#Chained-comparisons-capability
[3]: https://metacpan.org/pod/release/XSAWYERX/perl-5.31.11/pod/perlop.pod#Operator-Precedence-and-Associativity

---
本文為 [連環比較運算式](https://gugod.org/2020/05/chained-comparison/) 一文之英文版。