teleren/devto huggingface dataset:
DAY7: Python day 10
Published: 2023-12-02 14:24:13

**Functions with Outputs**

- `return` keyword to output and store the result

-docstrings: right after the def line; `"""description of function"""`

**End of the lesson project: Calculator**
```
from art import logo
print(logo)

#Calculator


#Add
def add(n1, n2):
    return n1 + n2


#Subtract
def subtract(n1, n2):
    return n1 - n2


#Multiply
def multiply(n1, n2):
    return n1 * n2


#Divide
def divide(n1, n2):
    return n1 / n2



operations = {"+": add, "-": subtract, "*": multiply, "/": divide}

def calculator():
  
  num1 = float(input("What's the first number?: "))
  
  for item in operations:
      print(item)
  
  should_continue = True
  while should_continue == True:
      operation_symbol = input("Pick an operation: ")
      num2 = float(input("What's the next number?: "))
  
      calculation_function = operations[operation_symbol]
      answer = calculation_function(num1, num2)
  
      print(f"{num1} {operation_symbol} {num2} = {answer}")
    
      if input(f"Type 'y' to continue calculating with {answer}, or type 'n' to start a new calculation: ") == "y":
          num1 = answer
      else:
        should_continue = False
        calculator()

calculator()
```
Rank 2904 🚀 in Leetcode Contest
Tags: programming, career, coding, softwaredevelopment
Published: 2023-12-02 14:20:50

"Hey there! (ਸਤਿ ਸ੍ਰੀ ਅਕਾਲ)

Quick update as of December 2, 2023,

I'm knee-deep in university exams, but I took a break for some fun on Leetcode. Did a virtual contest and cracked **2** out of 4 problems. Super stoked to share I landed at **2904** out of **14880** participants 🚀, my best score yet!

Back to hitting the books now. Bye!

Cheers,
Abhishek 😉"

![Leetcode contest screenshot](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/khixjwhfz8glxjgg6ojx.png)
How I messed up using Git-Annex
Tags: syncthing, gitannex, filesync, git
Published: 2023-12-02 14:19:23

I have been using Syncthing for quite a while. There are good reasons for its rapidly gained userbase.

What ever frustrated me was wanting to:
* have it on a Haiku OS machine
* have it easily configurable without the WebUI on older machines where I only had Seamonkey usable
* being able to properly manage the safeguard-versioning
* not have weird conflicts mess things up resulting in there silently being no sync until I'd look at the UI
* be able to easily access even encrypted synchronized-without-trust files

So I ended up both creating a repo in my original Syncthing-active directory with all files unlocked and annex.thin set, and adding the directory as a directory importtree&exporttree special remote in Git-annex. I juggled both of these ways trying to achieve what I wanted, synchronizing it with another proper repo as a temporary duplicate.

That worked for a while, I had a workflow for managing file changes manually post-factum. Until at some point I did something, or not, and suddenly realized all my devices have gotten all files purged from the Syncthing-active directory, and I only have the files in my new proper repo directory.

And now I am no longer a user of Syncthing. I got migrated. By force — of a mistake of mine.

I am just still having to figure out the ways of the assistant and the webapp, especially the how to manage the webapp.

This occurence made me backtrack on some of my prior choices, however. A major problem for me was always not wanting to keep git commiting every small change in a small plaintext-source thing I would be publishing, while wanting it to be in sync as part of a larger bundle of things that I would have. For years already I was resolving to just having such kind of stuff in directories in Syncthing.

I am now realizing that I should find ways to:
* automatically do commits with git, considering I already now let git-annex do that with its assistant (or at least, I intend to). Or at least bundle it up in really properly handy aliases
* start using submodules with git-annex in a way that would have me get that synced between by devices

And let's hope the next time I sit down to a Haiku OS desktop, git-annex will turn out to be packaged or otherwise easy to build.
Advent of Code 2023 - December 2nd
Tags: advent, adventofcode, python, december
Published: 2023-12-02 14:09:40

---
title: Advent of Code 2023 - December 2nd
published: true
description: My progress with the 2023 version of Advent of Code
tags: advent, adventofcode, python, december
cover_image: https://dev-to-uploads.s3.amazonaws.com/uploads/articles/36qayk14ewje7rvykeg5.jpg
series: Advent of Code 2023
# published_at: 2023-12-01 17:41 +0000
---

In this series, I'll share my progress with the 2023 version of [Advent of Code](https://adventofcode.com/2023).

Check the first post for a short intro to this series.

You can also follow my progress [on GitHub](https://github.com/robvanderleek/adventofcode).

## December 2nd

[The puzzle of day 2](https://adventofcode.com/2023/day/2) was not so hard. The one from yesterday made me a bit nervous for what's to come, but it seems the Elves gave me a break today :sweat_smile:

__My pitfall for this puzzle:__ Not really any, programming the solution was pretty straightforward.

{% spoiler Solution here, do not click if you want to solve the puzzle first yourself %}

```python
#!/usr/bin/env python3

valid_games = []
game_powers = []

def is_valid_draw(marbles):
    for marble in marbles:
        [count, color] = marble.split(' ')
        if (color == 'red' and int(count) > 12) or \
           (color == 'green' and int(count) > 13) or \
           (color == 'blue' and int(count) > 14):
            return False
    return True 

def is_valid_game(games):
    for game in games:
        marbles = game.split(', ') 
        if not is_valid_draw(marbles):
            return False
    return True

def game_power(game_marbles):
    red = 0
    green = 0
    blue = 0 
    for marbles in game_marbles:
        for marble in marbles:
            [count, color] = marble.split(' ')
            if (color == 'red' and int(count) > red):
                red = int(count)
            if (color == 'green' and int(count) > green):
                green = int(count)
            if (color == 'blue' and int(count) > blue):
                blue = int(count)
    return red * green * blue

with open('input.txt') as infile:
    lines = infile.readlines()
for line in lines:
    [game_id, all_games] = line.strip().split(': ')
    game_number = int(game_id.split(' ')[1])
    games = all_games.split('; ')
    if is_valid_game(games):
        valid_games.append(game_number)
    game_marbles = [game.split(', ') for game in games]
    game_powers.append(game_power(game_marbles))

print(sum(valid_games))
print(sum(game_powers))
```

{% endspoiler %}

That's it! See you again tomorrow!
Embracing Setbacks: Stories of Resilience in the Face of External Pressures
Tags: codenewbie, mentalhealth
Published: 2023-12-02 13:52:52

| 🔴 **Disclaimer**: This post is enhanced with AI assistance.|
|--------------|

## The Newbie Concerned
> Bard, please guide me on dealing with setbacks.

## Google Bard Replied

```
In the tapestry of life, where voices interweave,
Opinions clash and judgments weave,
Amidst the clamor, the din, the noise,
A resilient spirit finds its voice.

Real-life stories, like beacons bright,
Illuminate the path, banish the night,
Tales of resilience, where setbacks rise,
Transforming challenges into stepping stones, into skies.

External pressures, a relentless tide,
Opinions swirling, where doubts reside,
Yet amidst the storms, the waves that crash,
A steady mind, a resolute dash.

Constructive feedback, a guiding light,
Unveiling flaws, where progress takes flight,
Not to diminish, but to refine,
To polish skills, where talents shine.

Mental well-being, a sanctuary true,
Where self-worth blooms, a radiant hue,
Nurturing resilience, a fortress strong,
Where doubts and fears no longer belong.

A culture of learning, a tapestry grand,
Where knowledge flows, at every command,
Continuous growth, a never-ending quest,
Where minds expand, put to the test.

So let us embrace the stories we hear,
Of resilience, courage, dispelling fear,
Cultivate an environment where minds can soar,
Where growth prevails, forevermore.
```
Once again I wanted to have Emacs be my XML Notepad 2006
Tags: xml, emacs, nonconstructive, rant
Published: 2023-12-02 13:51:38

<p>XML Notepad from Microsoft, popular since as XML Notepad 2006, and since 2016~2020 having kicked off well as an active MIT-licensed open-source project, is a tool amazing in the simplicity of its basic premise.</p>
<p>Since I switched back from Windows altogether, I have been seeking to use it again. There is a Wikipedia article titled "Comparison of XML Editors", where Emacs' psgml and xml-mode are mentioned as having Tree editing, and the row mentioning nxml-mode has a question mark.</p>
<p>Yet nxml-mode has replaced xml-mode in Emacs as a default and not just that, but using the old xml-mode seems hard to do. I had to package-install "psgml" to get that "sgml-show-structure" to be available and it still didn't work.</p>
<p>I am now trying to write my small XML files with C-c C-i|TAB (nxml-balanced-close-start-tag-inline) and C-c /|C-f (nxml-finish-element), but I got very puzzled as to that C-c C-d bound to nxml-dynamic-markup-word, which doesn't seem to work for me. And M-f keeps moving me just onto the closing tag right angle bracket, from where I have to move with C-M-f or C-f.</p>
<p>I should probably muscle-memorize the selecting a whole entry, duplicating it before, and removing the content of the content tag. And set nxml-sexp-element-flag to nil.</p>

A friend has suggested that I use imenu, but it turned out an nxml-mode buffer "cannot use imenu-default-create-index-function".
Mastering JavaScript Screen Capture: Essential Tips for Taking Screenshots | JavaScript Projects
Tags: webdev, javascript, programming, devops
Published: 2023-12-02 13:38:03

{% embed https://www.youtube.com/embed/W2inn5RBTx0?si=LwmqIpVmJ-F77znN %}

The provided text introduces a project or tutorial focused on mastering [JavaScript](https://www.youtube.com/@learnwithdanial417) screen capture, specifically providing essential tips for effectively taking screenshots. Let's break down the key points:

## Objective:

- The main goal is to assist individuals in mastering the process of capturing screens using JavaScript.

## Scope:

- The project or tutorial is expected to cover essential tips, implying a comprehensive guide that goes beyond basic concepts and delves into important nuances of screen capture.

## JavaScript Focus:

- The tutorial is centered around JavaScript, indicating that the primary scripting language used for implementing screen capture functionality is JavaScript. This aligns with the broader category of [JavaScript projects](https://www.youtube.com/@learnwithdanial417).

## Practical Application:

- The mention of "essential tips for taking screenshots" suggests a practical approach, focusing on real-world scenarios and best practices for achieving effective screen captures using JavaScript.

## Skill Enhancement:

- The project is likely aimed at individuals seeking to enhance their skills in JavaScript, particularly in the context of screen capture functionalities.

## JavaScript Projects:

- The inclusion of "[JavaScript Projects](https://www.youtube.com/@learnwithdanial417)" suggests that the tutorial or project falls within the broader category of JavaScript projects, emphasizing hands-on applications and projects related to JavaScript development.


![JavaScript Projects](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/t52m5dvq8s1yhmk1im5y.jpg)

In summary, [this project or tutorial](https://www.youtube.com/@learnwithdanial417) aims to provide a comprehensive guide for mastering JavaScript screen capture, offering essential tips for individuals looking to improve their skills in this specific area of web development. The focus on practical applications and alignment with JavaScript projects suggests a valuable resource for those seeking hands-on experience and expertise in JavaScript-based screen capture functionalities.
Recriando o método lodash partition() em vanilla JS
Tags: javascript, programming, portugues
Published: 2023-12-02 13:21:51

_**Nota:** apenas traduzi o texto abaixo e postei aqui._

Veremos agora como fazer a mesma coisa com o método `_.partition()`.

O método `_.partition()` "split" um array em dois grupos: um para itens que atendem a alguns critérios e o segundo para itens que não atendem.

Para começar, vamos criar uma `partition()` helper function. Aceitaremos dois arguments: o array a ser dividido em dois e a "criteria" pela qual vamos dividi-lo.

```javascript
var partition = function (arr, criteria) {
    // Faça as coisas aqui...
};
```

Dentro da helper function, retornaremos um novo array.

```javascript
var partition = function (arr, criteria) {
    return ;
};
```

Com o método lodash `_.partition()`, o primeiro item no array retornado é um array de itens que "match" à criteria e o segundo são os itens que não "match".

Usaremos o método `Array.filter()` para ambos.

Para o argument `criteria`, aceitaremos uma function para validação. Usaremos isso como está em nossa primeira instância de `Array.filter()` e usaremos um `bang operator (!)` para verificar se há falsidade na segunda.

```javascript
var partition = function (arr, criteria) {
    return [
        arr.filter(function (item) {
            return criteria(item);
        }),
        arr.filter(function (item) {
            return !criteria(item);
        }),
    ];
};
```

E aqui está um exemplo do site lodash, mas usando nosso próprio método `partition()`.

```javascript
var users = [
    {'user': 'barney', 'age': 36, 'active': false},
    {'user': 'fred', 'age': 40, 'active': true},
    {'user': 'pebbles', 'age': 1, 'active': false}
];

// O primeiro array contém "fred"
// O segundo contém "barney" e "pebbles"
partition(users, function (user) {
    return user.active;
});
```

## Fonte

Newsletter de [Go Make Things](https://gomakethings.com/)
The Ultimate Guide to Men's T-Shirts: Styles, Colors and Fabrics
Published: 2023-12-02 13:18:07

Men T Shirts: The Ultimate Guide to Style, Color and Fabric When it comes to men's fashion, t-shirts are a staple item that every man should have in his wardrobe. They are versatile, comfortable, and can be dressed up or down depending on the occasion. However, with so many styles, colors, and fabrics to choose from, it can be overwhelming to know where to start. In this ultimate guide to men's t-shirts, we will break down everything you need to know to find the perfect t-shirt for you. The Different Styles of Men T Shirts The first thing to consider when choosing a t-shirt is the style. There are several different styles to choose from, including crew neck, v-neck, and scoop neck. Each style has its own unique look and can be worn in different ways. For example, a crew neck t-shirt is a classic style that can be worn on its own or layered under a jacket or sweater. A v-neck t-shirt is a more modern style that can be dressed up with a blazer or worn casually with jeans. Choosing the Right Color for Your Men T Shirts Once you have chosen the style of t-shirt you want, the next thing to consider is the color. The color of your t-shirt can have a big impact on your overall look, so it's important to choose wisely. Neutral colors like black, white, and gray are always a safe bet and can be worn with almost anything. However, if you want to add some color to your wardrobe, there are plenty of options to choose from. Bright colors like red, blue, and green can add a pop of color to your outfit, while pastel colors like pink and lavender are perfect for a more subtle look. The Best Fabrics for Men T Shirts Finally, the fabric of your t-shirt is just as important as the style and color. The most common fabrics for t-shirts are cotton, polyester, and blends of the two. Cotton is a natural fiber that is breathable and comfortable to wear, making it a popular choice for t-shirts. Polyester is a synthetic fiber that is durable and wrinkle-resistant, making it a good choice for athletic wear. Blends of cotton and polyester offer the best of both worlds, combining the comfort of cotton with the durability of polyester. In conclusion, choosing the right t-shirt can make all the difference in your overall look and comfort. By considering the style, color, and fabric of your t-shirt, you can find the perfect one for any occasion. Whether you prefer a classic crew neck or a modern v-neck, a neutral color or a bold hue, cotton or polyester, there is a t-shirt out there for everyone. Related Websites: 1\. https://www.gq.com/style 2\. https://www.menshealth.com/style 3\. https://www.fashionbeans.com/category/mens-fashion-trends/

## References

  * [men t shirts](http://sfbaysss.org/shtp2014/?wptouch_switch=mobile&redirect=https://coofandy.com/collections/mens-t-shirt "men t shirts")
Recriando o método lodash inRange() em vanilla JS
Tags: javascript, programming, portugues
Published: 2023-12-02 13:10:28

_**Nota:** apenas traduzi o texto abaixo e postei aqui._

Hoje vamos recriar o método `inRange()` com vanilla JS.

## O que _.inRange() faz

O método lodash `_.inRange()` pega um number e verifica se está entre dois outros numbers.

Você passa o `number`, o `start` do range e o `end` do range como arguments.

```javascript
_.inRange(number, start, end);

// Retorna true
_.inRange(2, 1, 4);

// Retorna false
_.inRange(2, 3, 5);
```

Você também pode pular o `start` e passar apenas o `end`. O método usará 0 como `start` por padrão.

```javascript
// Retorna true
_.inRange(2, 4);
```

Se o `number` for igual ao `start` do range, ele passa. Se for igual ao `end`, ele falha. Pessoalmente, isso me parece estranho.

```javascript
// Retorna true
_.inRange(2, 2, 4);

// Retorna false
// Porque?????
_.inRange(4, 2, 4);
```

Tudo bem, vamos fazer isso.

## Recriando _.inRange() com vanilla JS

Primeiro, vamos configurar nossa _helper function_.

```javascript
var inRange = function (num, start, end) {
    // Faça as coisas...
};
```

A seguir, vamos verificar se nosso number está no range.

Acho que o `end` deve ser inclusivo, assim como o `start`, então faremos as coisas de maneira um pouco diferente do que lodash faz aqui. Verificaremos se `num` é maior ou igual ao `start` e menor ou igual ao `end`. Então, retornaremos o resultado.

```javascript
var inRange = function (num, start, end) {
    return num >= start && num <= end;
};
```

A versão lodash permite "drop" o `start`, se desejar, e o default é 0. Vamos adicionar essa feature.

Verificaremos se `end` existe. Caso contrário, atribuiremos `start` como seu valor. Então, definiremos o `start` como 0.

```javascript
var inRange = function (num, start, end) {
    // Se não houver o end number, use start como end
    if (!end) {
        end = start;
        start = 0;
    }
    return num >= start && num <= end;
};
```

Uma última coisa que lodash faz é "flip" os valores de start e end se o start for maior que o `end`. Isso é feito para suportar valores negativos.

```javascript
// Retorna false
inRange(-2, -1, -4);
```

Neste exemplo, -1 é na verdade maior que -4, porque são números negativos. O número -2 está dentro do range, mas se os números não fossem "flipped", ele falharia.

Pessoalmente, acho que os usuários deveriam passar isso da maneira certa, então não vou apoiar essa feature.

```javascript
// Retorna true
inRange(-2, -4, -1);
```

Então, com isso, terminamos.

## Fonte

Newsletter de [Go Make Things](https://gomakethings.com/)
Boundary value analysis ,Decision table testing,Use Case testing,LCSAJ testing
Published: 2023-12-02 12:54:18

Boundary Value Analysis:
========================
Boundary Value Analysis is based on testing the boundary values of valid and invalid partitions. The behavior at the edge of the equivalence partition is more likely to be incorrect than the behavior within the partition, so boundaries are an area where testing is likely to yield defects.

It checks for the input values near the boundary that have a higher chance of error. Every partition has its maximum and minimum values and these maximum and minimum values are the boundary values of a partition.

Decision Table testing :
========================
Decision tables are used in various engineering fields to represent complex logical relationships. This testing is a very effective tool in testing the software and its requirements management. The output may be dependent on many input conditions and decision tables give a tabular view of various combinations of input conditions and these conditions are in the form of True(T) and False(F). Also, it provides a set of conditions and its corresponding actions required in the testing.

Usecase testing:
================
Use Case Testing is a type of black box testing and that helps developers and testers to identify test scenarios, test strategy ,test estimation ,testbed requirement and testplan .Business experts and developers and testers must have a mutual understanding of the requirement, as it's very difficult to attain.
Use case testing is a kind of functional testing which consists Regressing testing,sanity testing ,Fire and smoke testing and vulnerability testing.
It helps to identify the testing procedures which is belong to individual modules.
It is used to describe testplan and testcases at the initial level .
Use case testing is not testing that is performed to decide the quality of the software.
Although it is a type of end-to-end testing, it won't ensure the entire coverage of the user application.
Use case testing will find out the defects in integration testing.
It is very effective in identifying the gaps in the software that won't be identified by testing individual components in isolation.
Use case-driven analysis that helps manage complexity since it focuses on one specific usage aspect at a time.
The complexity of the test cases will be reduced as the testing team will follow the path given in the use case document.
Usecases are the functional requirements of the system.
They help to identity the integration defects, defects that arise due to incorrect communication between different components.
Use cases are used to hearten designers to outcomes before attempting to specify outcomes, and thereby they help to make requirements more proactive in system development.
Usecase testing helps to identify the gaps in software that might not be identified by testing individual components.
Usecase testing is used to develop test cases at the system level or acceptance level.

LCSAJ testing: 
==============
This topic not yet covered in Manual testing session.