teleren/devto huggingface dataset:
#Day17 - Fastest way to format strings in Python
Tags: 100daysofcode, python, programming, codenewbie
Published: 2021-04-07 03:13:54

There are 3 ways to format strings in Python
- Using the % operator
- Using format()
- Using f strings


![image.png](https://cdn.hashnode.com/res/hashnode/image/upload/v1617759091908/w7h2m8bJb.png)

We have three functions
- **func1** uses the % operator
- **func2** uses  format()
- **func3** uses f strings

We will use the timeit function to measure the time taken by each function


![image.png](https://cdn.hashnode.com/res/hashnode/image/upload/v1617759195401/4tfW4XnvL.png)

We call each function 100 times and calculate the average time taken for the function call. The average time is stored in a list.


![image.png](https://cdn.hashnode.com/res/hashnode/image/upload/v1617759450337/cW62DYeeY.png)

Below are the comparisons of the 3 functions

![download.png](https://cdn.hashnode.com/res/hashnode/image/upload/v1617760269541/uPWKvmEh5.png)


As you can see, f strings are faster as compared to format() and the % operator.

### if.....else with f strings
```python
num = 2
print(f"{num} is an {'even' if num%2 ==0 else 'odd'} number")

num = 3
print(f"{num} is an {'even' if num%2 ==0 else 'odd'} number")
```

### Aligning strings
- Left-aligned: {variable :> number}
- Center-aligned: {variable :^ number}
- Right-aligned: {variable :< number}

```python
text = "string"
print(f'{text:>20}')
print(f'{text:^10}')
print(f'{text:<30}')

'''
OUTPUT
              string
  string  
string  
'''
```

### Round floating points
```python
num =  20.012345783
print(f'{num:0.3f}')

'''
OUTPUT
20.012
'''
```
### Pad Zeroes
```python
x = 10
print(f'{x:0}') #10
print(f'{x:02}') #10
print(f'{x:03}') #010
print(f'{x:04}') # 0010
```
If you want to pad n zeroes to a y digit number, it should be 
```python
print(f'{x:0n+y}')
```
FM Whatsapp 8.85 APK Free Download 2021
Tags: whatsapp, fmwhatsapp, update, download
Published: 2021-04-07 02:58:16

Modifying application FMWhatsapp has launched new version v8.85 APK with many modifications and upgrades compared to the old version. Especially the application has been optimized for the latest android version 11.
![Alt Text](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/ota168gr5x3ayphupl51.jpg)
Mod features v8.85:
• Added: New options for downloading stories (copy captions, share, etc.)
• Added: Dark / light mode in FMThemes Store automatically
• Added an option to hide privacy policy notifications (Universal> Hide Privacy msg).
• Added translation for Voice Changer options
• Moved / fixed "Copy caption" error from long press to download options
• Fix bugs in store items
• Fixed contact name not clearly visible in comments! mention
• Fixed theme wallpapers do not apply on some phones
• Fixed full backup not working on Android 11+
• Other translations improved
• Other bug fixes and improvements

Download Link: https://techbigs.com/fmwhatsapp.html
Dynamically getting objects from an assembly in C#
Tags: csharp, dotnet, reflection
Published: 2021-04-07 02:35:12

To avoid those repetitive codes that 'registers' types of a class or interface you can use a bit of reflection and dynamically find and instantiate those.

First, list all the types ([GetTypes]) from the current assembly ([GetExecutingAssembly]):

```cs
var types = Assembly.GetExecutingAssembly().GetTypes();
```

Then filter by whatever type you want with [IsAssignableFrom]:

```cs
var filteredTypes = types.Where(t => typeof(MyType).IsAssignableFrom(t));
```

And lastly instantiate those with the good old [Activator.CreateInstance]:

```cs
var instances = filteredTypes.Select(t => (MyType)Activator.CreateInstance(t));
```
[GetTypes]: https://docs.microsoft.com/dotnet/api/System.Reflection.Assembly.GetTypes
[GetExecutingAssembly]: https://docs.microsoft.com/dotnet/api/System.Reflection.Assembly.GetExecutingAssembly
[IsAssignableFrom]: https://docs.microsoft.com/dotnet/api/System.Type.IsAssignableFrom
[Activator.CreateInstance]: https://docs.microsoft.com/dotnet/api/System.Activator.Createinstance

Below goes a working example of such approach. Note that there are many potential edge cases in play here, patch the code accordingly to your needs.

```cs
using System;
using System.Linq;
using System.Reflection;

// No "class Program" or "static void Main"
// C# 9 top-level statements!

// Watch out for some potential pitfalls of using Activator.CreateInstance such as:
// - runtime error when class doesn't have a parameterless constructor
// - can be a costly method call
static T Instantiate<T>(Type t) => (T)Activator.CreateInstance(t);

static bool IsGreeter(Type t) => typeof(IGreeter).IsAssignableFrom(t) && t.IsClass;

// Use AppDomain.CurrentDomain.GetAssemblies() for other assemblies than the current one
var types = Assembly.GetExecutingAssembly().GetTypes().Where(IsGreeter);
var instances = types.Select(Instantiate<IGreeter>);

// Prints:
// "Hello, I'm Anna."
// "Hi, Joe here."
// "Woof!"
foreach (var i in instances)
    i.Greeting();

public interface IGreeter
{
    void Greeting();
}

public class Anna : IGreeter
{
    public void Greeting() => Console.WriteLine("Hello, I'm Anna.");
}

public class Joe : IGreeter
{
    public void Greeting() => Console.WriteLine("Hi, Joe here.");
}

public class Dog : IGreeter
{
    public void Greeting() => Console.WriteLine("Woof!");
}
```
What is Currying in JavaScript?
Tags: webdev, javascript, programming, codenewbie
Published: 2021-04-07 02:29:13


Currying is a technique of evaluating function with multiple arguments, into sequence of function with single argument. 

Currying is a transformation of function that translates a function from callable as `f(a, b, c)` into callable as f(a)(b)(c). 

```javascript
function curry(f) {
    return function(a) {
        return function(b) {
            return f(a,b); 
        }; 
    }; 
}
function sum(a, b) {
    return a + b; 
}
 let curriedSum = curry(sum); 
 curriedSum(1)(2); 

 // 3
```


## Why is it Useful? 

- Currying helps you to avoid passing the same variable again and again.
- Little pieces can be configured and reused  with ease. 

#### How to convert an existing function to curried version? 

The curry function does not exist in native JavaScript. But libraries like lodash makes it easier to convert a function to curried one.

```javascript
let add = function(a, b, c) {
    return a+ b + c; 
}; 
let curried = _.curry(add); 
let addByTwo = curried(2); 

console.log(addByTwo(0, 0)); //2
console.log(add(2, 1, 1)); // 4
console.log(curried(4)(5)(6)); // 15
```


--- 

🚀Thanks For Reading | Happy Coding🏗
Rust no_std template
Tags: rust, tutorial, os, embedded
Published: 2021-04-07 01:48:41

There are [many](https://fasterthanli.me/series/making-our-own-executable-packer/part-12) [in-depth](https://docs.rust-embedded.org/book/intro/no-std.html) [tutorials](https://os.phil-opp.com/freestanding-rust-binary/) that explain how to write a `#![no_std]` binary. This is just a simple, reusable bare-bones template that works for me.

In your `src/main.rs`:

```rust
#![no_std]
#![no_main]

use core::panic::PanicInfo;

#[panic_handler]
fn panic(_info: &PanicInfo) -> ! {
    loop {}
}

#[no_mangle]
pub extern "C" fn _start() -> ! {
    loop {}
}
```

In your `Cargo.toml`:

```yaml
[profile.dev]
panic = "abort"

[profile.release]
panic = "abort"
```

Instead of simply running `cargo build` to generate a binary like usual, you need to jump through some hoops to generate a binary.

If you are compiling this binary for Linux, you can run:

`cargo rustc -- -C link-arg=-nostartfiles`

For Windows:

`cargo rustc -- -C link-args="/ENTRY:_start /SUBSYSTEM:console"`

For macOS: 

`cargo rustc -- -C link-args="-e __start -static -nostartfiles"`

<hr>

All of this is useful if you plan on running the resulting binary on bare metal. If you're compiling Rust to WebAssembly, none of this is _necessary_ - simply _not_ using the `std` library is enough for that use case. 

If you're targeting the [WebAssembly System Interface](https://github.com/bytecodealliance/wasmtime/blob/main/docs/WASI-documents.md), it's more simple and you can even use Rust's `std` library for that use case.
Confusing JS Explained
Tags: javascript, webdev, tutorial, beginners
Published: 2021-04-07 01:29:21


JavaScript, often abbreviated as JS, is a programming language that conforms to the ECMAScript specification. JavaScript is high-level, often just-in-time compiled, and multi-paradigm. It has curly-bracket syntax, dynamic typing, prototype-based object orientation, and first-class functions.

# Some confusing parts

```js
(([]+{})[1]+'mg').toUpperCase()  // outputs  OMG

```

But how is this happening

We will go into a little depth on how JS interprets stuff

> I am using chrome console to test all of this
_______________


## Let's Explain the line above first


   * the '+' sign converts the parameters to strings by using the 'toPrimitive' method

   *  so, toString([]) returns an empty string ''
   *  and toString({}) returns to this '[object Object]'
   *  then the result is '' + '[object Object]' = '[object Object]'
   * the rest is simple, I am picking the character at index 1 'o' and just adding the 'mg' and converting all to upper case
   * Drum roll ........
   * We get "OMG"

_______________
# ToPrimitive:

> ToPrimitive(input, PreferredType?)

The optional parameter PreferredType is either Number or String. It only expresses a preference, the result can always be any primitive value. If PreferredType is Number, the following steps are performed to convert a value input (§9.1):

1. If the input is primitive, return it as is.
2. Otherwise, input is an object. Call obj.valueOf(). If the result is primitive, return it.
3. Otherwise, call obj.toString(). If the result is primitive, return it.
4. Otherwise, throw a TypeError.

If PreferredType is String, steps 2 and 3 are swapped. If PreferredType is missing then it is set to Number for any numeric values and to string for all other values.

```js

1 + 1       //    2    <= Number
1 + 1 + '1' //   '21'  <= String
1 + 1 + []  //    '2'  <= String

```

There are some unique examples that behave differently

```js
{} + 1  // 1 <= Number

// JS treats the '{}' in this case as its own line 

({});+1 = 1

({})+1 = '[object Object]1'


```



Now you can apply this principle to any addition in JS and always know the answer without being confused

_______________
###references:

[JSInfo](https://javascript.info/object-toprimitive)
[MDN](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Symbol/toPrimitive)
그누보드5 최신글 반영하기
Published: 2021-04-07 01:03:39

**그누보드5**를 설치하고 특정 게시판의 최신글을 원하는 페이지에 반영하여 보자.

## 확인사항

1) 최신글 라이브러리
최신글을 처리하는 라이브러리는 **/lib/latest.lib.php** 파일이다.
이 파일을 열어보면 특정 게시판의 최신글을 어떻게 불러와서 처리하는지 알 수 있다.
이 라이브러리 파일을 최신글 반영하는 페이지 상단에 추가해야 한다.
일반적으로 그누보드5를 설치하면 head.php파일내에 아래와 같이 추가되어 있다.
```php
include_once(G5_LIB_PATH.'/latest.lib.php');
```
직접 페이지를 만들어 사용할 경우, 이 부분을 확인하여 없다면 추가해 주어야 한다.

2) 특정 위치에 최신글 반영하기
해당 페이지 상단에 최신글 라이브러리 파일을 추가했다면 이제 원하는 위치에 최신글을 반영할 수 있다.
```php
echo latest('스킨명', '게시판아이디', 출력라인수, 제목글자수);
```
- 스킨명은 /skin/latest아래에 있거나 테마를 적용한다면 /theme/테마명/skin/latest/아래에 해당 폴더형태로 존재한다.
배포판을 기본 설치하면 basic이라는 스킨과 최근 추가된 pic_block, notice, pic_list 등을 볼 수 있다.
- 게시판아이디는 관리자화면>게시판관리자에서 만든 게시판 아이디이다. 게시판 주소 **/bbs/board.php?bo_table=free**형식에서 **free**가 게시판 아이디이다.
- 출력라인수는 최신글을 화면에 보여줄 때 몇 개의 게시판 글을 가져올 것인지 결정하는 것이다.
- 제목글자수는 게시판에 등록된 글의 제목 글자수이다. 긴 제목인 경우, 적절하게 줄여서 보여줄 수 있다.
```php
echo latest('pic_list', 'free', 4, 23);	
```
이것은 스킨 pic_list을 사용하고 free아이디를 가지는 게시판에서 4개의 글을 가져오는데 제목의 길이는 23자이다.

[그누보드5강좌](https://365ok.co.kr/tj/gnuboard)
Make a chat app with Node JS
Tags: javascript, prisma, node, help
Published: 2021-04-07 00:41:08

I want to make a chat app with react, node, socket.io, and Prisma. I am unable to add direct message (dm) functionality but added group functionality.

My Schema
```ruby
datasource db {
  url      = env("DATABASE_URL")
  provider = "postgresql"
}

generator client {
  provider = "prisma-client-js"
}

model User {
  id        Int      @id @default(autoincrement())
  createdAt DateTime @default(now())
  email     String   @unique
  username  String
  password  String
  sender    Messages @relation("sender")
  receiver  Messages @relation("receiver")
}

model Group {
  id        Int        @id @default(autoincrement())
  messages  Messages[]
  user      Users[]
}

model Messages {
  id          Int     @id @default(autoincrement())
  text        String 
  group       Group   @relation(fields: [groupId], references: [id])
  groupId     Int
  sender      User    @relation("sender", fields: [senderId], references: [id])
  senderId    Int
  reciever    User    @relation("reciever", fields: [recieverId], references: [id])
  recieverId  Int
}
```
CSS Heart Shape
Tags: css, codenewbie, webdev, html
Published: 2021-04-07 00:28:35

in this post, I will tell you how we can make a heart shape in CSS.
**HTML**
![Alt Text](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/b9gdroxx7mnr1azdrl6p.png)

**CSS**
After adding HTML you need to style it with CSS.
1- Style body tag

![Alt Text](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/k6fwz5hs3a8w3x1ls5am.png)
2- style heart class
![Alt Text](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/mw2ajj71ezsydsrqkals.png)

3- Style Pusedo-class  ::after ,::before
 ![Alt Text](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/x5mawaxpvcwidqnk7iww.png)

After it runs into the browser.

I hope you learn from this. if you want a video of this 
video link: {% youtube   jvHcx0hG4kI %}
I Built a Developer Productivity Tool!
Tags: productivity, sideprojects, showdev
Published: 2021-04-07 00:28:04

Hey everyone!

After many failed interviews absolutely nuked my self-confidence and love for programming, I decided I didn't really like the idea of working for someone else on their product. It's not that I never would, but I instead decided to focus on making my own ideas. 

For the past handful of months I've been working on this little thing called [Kanlen](https://kanlen.ca). I'm still figuring out exactly what "it is".

I'm not a fan of wasting too much time on repetitive tasks even though I repeat myself often, but, here we are.

I had an idea one day. What if there was a way, to build our your CLI command using a GUI of sorts? That would take the guesswork out of figuring out the correct syntax for the CLIs you use. For me, it's a lot of CRA.

It might also be nice to know what flags I have available to use in this command. I sure can't remember all that.

I'm going to briefly explain what Kanlen does and maybe from that, an idea of the app will form, but for now let's think of it like a developer's productivity tool.

## What does it do?
Well, we already spoke about the whole CLI thing, so on we go.

### Save Environment Variables
If you're like me, sometimes you get a new development computer and forget to jot down the environment variables you're using. That happened to me while building Reddex. Losing those variables was super annoying.

I thought it might be cool if you could store them somewhere online. Then if you switch machines, it crashes, or spontaneously combusts, you'll have a backup of those variables.

### Save your code like Gists
Perhaps the bread and butter of Kanlen, well, at least the main idea of it since the beginning, was being able to save your favourite functions.

I have a few pieces of code that I like to bring between projects and if I could save them in a spot that's easily accessible, obviously that would be pretty alright.

These pieces of code are sharable and if you download the Kanlen VSCode extension, you can import your saved snippets right into your editor. On the flip-side, if you want to create a snippet, you can do that by selecting a block of code and running a specific command. It's pretty neat in my humble opinion.

## Moving on
Those are a couple things it does, it you're interested in reading more about it, check out the main page [Kanlen](https://kanlen.ca).

This is just a little side project I've been playing with since late 2020. It's still in development, but I love where it's going and maybe it'll help you too someday.
Journey for Full Stack Web Development
Tags: codenewbie, webdev, html, css
Published: 2021-04-07 00:13:38

Hi everyone,
Today I discuss the journey for a full-stack web developer. According to me for beginner first, learn front-end technologies then backend.
 
The following list is the best path for full-stack web development.
1. Html
2. CSS
3. JS
4. Bootstrap/Tailwind 
5. React/Vue/Angular
6. PHP
7. Mysql
8. Laravel
9. Nodejs
10.Git

if you want to add please write your comments below this post.
How to change the ownership of the file synchronously in Node.js?
Tags: node
Published: 2021-04-07 00:00:00

---
  title: How to change the ownership of the file synchronously in Node.js?
  published: true
  tags: Nodejs
  date: Wed Apr 07 2021 05:30:00 GMT+0530 (India Standard Time)
  canonical_url: https://melvingeorge.me/blog/change-ownership-of-file-synchronously-nodejs
  cover_image: https://melvingeorge.me/_next/static/images/main-75bb5d630416429d1af1ff66ff411bb2.jpg
  ---
  [Originally posted here!](https://melvingeorge.me/blog/change-ownership-of-file-synchronously-nodejs)
  
To change the ownership of a file synchronously, you can use the `chownSync()` method from the `fs` (filesystem) module in Node.js.

Let's say I have a file called `myFile.txt` and want to change the owner from me to another user called `Roy`.

For example,

- The user `Roy` has the user-id (or `uid`) of `512`
- and the id of the group (or `gid`) to set ownership is `1000`.

So it can be done like this,

```js
// require fs module
const fs = require("fs");

// Change ownership of file
fs.chownSync("./myFile.txt", 512, 1000);

// Success message
console.log("Ownership of file has changed!");
```

The `fs.chownSync()` synchronous method accepts 3 arguments:

- The first one is the `path` to the file.
- The second one is the user-id (or `uid`) of the user that needs to have ownership of the file.
- The third one is the group-id (or `gid`) that needs to have ownership of the file.

See the above code live in [repl.it](https://replit.com/@melvin2016/change-ownership-of-file-synchronously-nodejs).

### Feel free to share if you found this useful 😃.

---
4 reasons to change code
Tags: practices, git, productivity
Published: 2021-04-10 08:26:53

---
title: 4 reasons to change code
published: true
date: 2021-04-07 00:00:00 UTC
tags: practices, git, productivity
canonical_url: https://jhall.io/archive/2021/04/07/4-reasons-to-change-code/
---

Why do we change code?

In his book, [_Working Effectively with Legacy Code_](https://amzn.to/3fMqhAf), Michael Feathers offers four reasons:

1. Adding a feature
2. Fixing a bug
3. Improving the design
4. Optimizing resource usage

I’ve yet to think of a 5th reason.

So what?

These 4 reasons are the basis for a personal rule when writing code:

**Each pull request must address only one of these reasons.**

Mixing concerns in a single PR can lead to all sorts of problems:

- It makes the PR much harder to understand and review
- It makes deploying the PR more dangerous (if a bug is found, is it due to the new feature, or the refactoring?)
- It makes reverting the PR dangerous (you can’t revert a broken feature without also reverting useful bug fixes)
Simple Music Player UI
Tags: showdev, webdev, javascript, css
Published: 2021-04-06 23:47:49

This is a minimal and simple music player UI design made with HTML, CSS, and JavaScript.

This project was created to practice my frontend dev skills.

## Functionality
* Favorite song button 
* Repeat / Shuffle buttons 
* Play / Pause button and audio _(slider does not currently update in real time with the song)_
* Drag the slider _(will not affect the song)_

![Gif of User Toggling Buttons](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/vqp5cmryv1pzriv6ldr7.gif)

### How to toggle a color change on an SVG

Here's a tutorial on how to the color of an SVG on click.

#### CSS

Create a `.active` ruleset to set the path's fill to the toggled color.

![CSS Code Block](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/sg1wur35zybqb5gqzntc.png)

#### JavaScript

Have a function that gets the `div` element by `id` and toggles an 'active' class.

![JavaScript Code Block](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/i3xl5nyt0p4sx4b9dtp6.png)

#### HTML

Surround the SVG with a div with an `id` and an `onclick` with the JavaScript function. _The div is also used for easier spacing out of elements._

![HTML Code Block](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/jbgd2wpxds6lpt168ns8.png)

## Built With
* HTML5
* CSS3
* JavaScript

## Code
{% github anniedotexe/music-player no-readme %}

## Live Demo
[Music Player](https://musicplayer.anniew.xyz/)

![Screenshot](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/n89k2cr7rbzbgpqzkitu.png)

## Feedback
Any type of feedback is welcome.

![Dancing Pikachu](https://media.giphy.com/media/vnGlErQHuF9BK/giphy.gif)

## Check out some of my other projects below

{% link https://dev.to/anniedotexe/finally-created-my-personal-website-2n6p %}

{% link https://dev.to/anniedotexe/twitter-discord-interactive-mobile-ui-concept-3d4 %}

The end,
annie.exe

---

{% gist https://gist.github.com/anniedotexe/a42e127d321261928104e5b2c0cdf24c %}