teleren/devto huggingface dataset:
SwiftUI's Multiline Text Alignment Guide
Tags: swift, swiftui
Published: 2023-10-26 02:40:30

---
title: SwiftUI's Multiline Text Alignment Guide
published: true
date: 2022-12-22 09:05:40 UTC
tags: Swift,SwiftUI
canonical_url: https://swift.my.id/mengatur-text-alignment-pada-multiline-text-view/
---

![SwiftUI's Multiline Text Alignment Guide](https://swift.my.id/content/images/2022/12/Screenshot-2022-12-22-at-15.57.12.jpg)

When using Text views in [**SwiftUI**](https://swift.my.id/mengatur-text-alignment-pada-multiline-text-view) that consist of multiple words or sentences, by default, the Text view will be displayed with **left-aligned** text that wraps across several lines. If you want to change this **alignment** , you can use a specific modifier called `multilineTextAlignment`.

```
func multilineTextAlignment(_ alignment: TextAlignment) -> some View
```

Where the values for `TextAlignment` can be center, leading, or trailing. Here's an example of [how to adjust text alignment in a Text](https://swift.my.id/mengatur-text-alignment-pada-multiline-text-view) view with multiple lines:

```
import SwiftUI

struct ContentView: View {
    var body: some View {
        Text("Lorem ipsum dolor sit amet, consectetur adipiscing elit. Nullam vitae elementum lorem, id pharetra metus.")
            .multilineTextAlignment(.center)
            .padding()
    }
}

```

![SwiftUI's Multiline Text Alignment Guide](https://swift.my.id/content/images/2022/12/image-4.png)

If you want to limit the maximum number of lines that can be displayed, then you can add the `lineLimit` modifier as well.

```
func lineLimit(_ number: Int?) -> some View


import SwiftUI

struct ContentView: View {
    var body: some View {
        Text("Lorem ipsum dolor sit amet, consectetur adipiscing elit. Nullam vitae elementum lorem, id pharetra metus.")
            .multilineTextAlignment(.center)
            .lineLimit(2)
            .padding()
    }
}

```

![SwiftUI's Multiline Text Alignment Guide](https://swift.my.id/content/images/2022/12/image-5.png)

By adding the `lineLimit`, if the number of lines exceeds the limit, the text will automatically be displayed with an ellipsis (`...`).

Here is an example of implementing the [`multilineTextAlignment`](https://swift.my.id/mengatur-text-alignment-pada-multiline-text-view) modifier:

![SwiftUI's Multiline Text Alignment Guide](https://swift.my.id/content/images/2023/10/Screen-Recording-2022-12-22-at-15.59.36.gif)

That's all for this tips and tricks. Give it a try, and hopefully, this little insight proves to be useful.

[

GitHub - meshwara/SwiftUI-MultilineTextAlignment

Contribute to meshwara/SwiftUI-MultilineTextAlignment development by creating an account on GitHub.

 ![SwiftUI's Multiline Text Alignment Guide](https://github.com/fluidicon.png)GitHubmeshwara

 ![SwiftUI's Multiline Text Alignment Guide](https://opengraph.githubassets.com/dbdbfaaa507b59a3cc7a297091aa287de7de7ceb24fb9f88104315b032f68c11/meshwara/SwiftUI-MultilineTextAlignment)
](https://github.com/meshwara/SwiftUI-MultilineTextAlignment?ref=swift.my.id)
Fix your external IP address for your VM using GCP
Tags: googlecloud
Published: 2022-12-22 09:03:36

Why are we doing?
Actually every time you stop your VM, you lose your external IP address and a new is generated. Thus we are solving this issue.

You can make some changes to fix your external IP addresses. For that, go to you VPC and then you may see something like this

![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/wspp5p78co6g3156v7me.png)
Note: Once you create a VM, a VPC is created for you.

So now we will reserve a static IP address to fix it.


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


Now give it a name and choose if you want to use the premium or standard network.

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

Note: Choose the same region your VM has already been launched.Otherwise it will not work for your VM.


Also you can choose the IP version and type . The type should be Region here as we are focusing to solve VM issue which is launched in a region.

Then press reserve.

So, this is what we created:

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

Now to attach it with our VM to use it, press this Change button:

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

![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/24gud39xnciav4wcst9k.png)
Now choose your VM from the list

Note: You can not find your VM if this VPC and Vm is not in the same region.

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


So, after attaching it, the earlier VPC which was created by default is gone (For which your external IP IP .


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


Now this becomes your external IP address and won't change in case the VM is stopped.


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


![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/2jadv5sh7dgzusq0l5gk.png)
Here we stopped the VM but you can still find your External IP address.


Problem Solved!

Tips: Once you are finished working with your VM, once you delete it, don't forget to delete the Static IP address you just created in your VPC.

Because it charges still when you are not using it.
Create an SQL Report API in 5 minutes
Tags: sql, lowcode, database, beginners
Published: 2022-12-22 09:02:32

In addition to generating CRUD APIs, [Aista Magic Cloud](https://aista.com) also allows you to generate API endpoints using nothing but SQL. The generator will take care of stuff such as authorisation, logging, generating the boiler plate code, etc. All you need to worry about is your SQL.

![SQL report API created declaratively](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/qkcoivqnnh62nu22sjy5.jpg)

The whole point about [Hyperlambda](https://aista.com/hyperlambda/) is that it's a _declarative programming language_. When you have a declarative programming language, the computer can automatically generate a large portion of your code, through a process that's similar to how you do it as you copy and paste code from [StackOverflow](https://stackoverflow.com). This implies that even though you can't code in anything but SQL, you can still create Web API endpoints - Because Magic does everything for you, as long as you provide some SQL to it.

In the video below I am demonstrating the whole process. If you want to reproduce what I'm doing, [signup at Hub](https://hub.aista.com) and create your own cloudlet.

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

The code that Magic produces can be found below.

```
/*
 * Template for custom SQL HTTP request.
 * This file was automatically generated using Magic's CRUDifier.
 */
.arguments
   filter:string
.type:sql

// Opening up a database connection
data.connect:chinook
   database-type:sqlite

   // Parametrizing [data.select].
   add:x:./*/data.select
      get-nodes:x:@.arguments/*

   // Evaluating [xxx.select] slot.
   data.select:"\n/*\n * Script to aggregate records for each artist in chinook database.\n * Make sure you select the chinook database before execxuting the script.\n */\nselect ar.Name, count(*) as count\n  from Album al, Artist ar where al.ArtistId = ar.ArtistId and ar.Name like @filter\n  group by al.ArtistId\n  order by count desc\n  limit 25\n"
      database-type:sqlite

   /*
    * Checking if we should return a list of items, or only a
    * single item.
    */
   if
      .is-list:bool:true
      .lambda

         // Returning a list of items to caller.
         return-nodes:x:@data.select/*

   // Returning a single result to caller.
   return-nodes:x:@data.select/*/*
```

Thank you for reading :)
How does my GitHub readme look like?🍧
Tags: discuss, github
Published: 2022-12-22 09:00:35

Hello. 👋
Yesterday I decided to create a [GitHub readme](https://github.com/atenadadkhah/atenadadkhah) for my profile. Before creating it, I read many tutorials and saw lots of perfect examples.
Now I want to know whether I was successful or not?
Is that a good readme? 
Thank you so much.😉💙
My Journey in Open Source - event-emitter
Tags: javascript, opensource, github, typescript
Published: 2022-12-22 09:00:00

[Link to the repo](https://github.com/Cadienvan/event-emitter)

## What is this?

This is a function which returns a simple EventEmitter.  
It is a simpler implementation of the EventEmitter class from NodeJS.  
It is not meant to be a replacement for the NodeJS EventEmitter, but rather a simple alternative for those who don't want to use the NodeJS EventEmitter.  
It is also a good way to learn how Event Emitting works as a concept.

## How do I install it?

You can install it by using the following command:

```bash
npm install @cadienvan/event-emitter
```

## How to use it?

Simply import the module and start using it as follows:

```js
import { makeEE } from '@cadienvan/event-emitter';
const myObject = Object.assign({}, makeEE());
function listener(data) {
  console.log(data);
}
myObject.$on('event', listener);
myObject.$emit('event', {});
```

### Why did I choose to call it makeEE?

I chose to call it makeEE because it is a function which returns an EventEmitter and I didn't want it to conflict with the NodeJS EventEmitter, allowing you to use both in the same project depending on the use case.

## How does this work?

The `makeEE` function returns an object with the following properties:

---

### $on

The `$on` function takes two arguments: the event name and the listener function.

```js
myObject.$on('event', listener);
```

---

### $off

The `$off` function takes two arguments: the event name and the listener function.

```js
myObject.$off('event', listener);
```

---

### $emit

The `$emit` function takes two arguments: the event name and the data to be passed to the listener function.

```js
myObject.$emit('event', data);
```

---

### $once

The `$once` function takes two arguments: the event name and the listener function.

```js
myObject.$once('event', listener);
```

## Tests

You can run the tests by using the following command:

```bash
npm test
```

## Scaffolding

This project was generated using Cadienvan's own [npm-package-ts-scaffolding](https://github.com/Cadienvan/npm-package-ts-scaffolding) so it has all the necessary tools to develop, test and publish a TypeScript package importable both via CommonJS and ES Modules.
Speedtest in Terminal
Published: 2022-12-22 08:51:28


![The HomeBrew Logo](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/nnrtkusli5lq1n1x7icm.png)


I use [HomeBrew](https://brew.sh/) to download all packages

Open up your terminal

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

I use the [iTerm.app](https://iterm2.com/downloads.html) it's super customizable 

Run

`/bin/bash -c "$(curl -fsSL https://raw.githubusercontent.com/Homebrew/install/HEAD/install.sh)"`

To install [HomeBrew](https://brew.sh/) 


After it's finished installing, run `clear` to clean up your terminal

To install the `speedtest-cli` you'll need to run


`brew install speedtest --force speedtest-cli`

Run `clear` to clean up your terminal again..

Then run

`speedtest-cli`

You'll be left with results sort of like this,

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

If you're on **WIFI**
make sure you switch over to your _5G_ connection if you have one

I hope I helped. Thanks for stopping by!
How create a new field based on other numerical fields in a Pandas Dataframe
Tags: pandas, python, jupyter, datascience
Published: 2022-12-22 08:31:39

To create a new field based on other numerical fields in a pandas DataFrame, you can use the pandas.DataFrame.assign() method. This method allows you to specify a new column name and the values for the column, which can be derived from one or more existing columns in the DataFrame.

For example, suppose you have a DataFrame with columns A, B, and C, and you want to create a new column called D that is equal to the sum of columns A and B. You can use the following code to do that:

```
import pandas as pd

df = pd.DataFrame({'A': [1, 2, 3], 'B': [4, 5, 6], 'C': [7, 8, 9]})

df = df.assign(D = df['A'] + df['B'])

print(df)
```
This code will create a new column D in the DataFrame with the values from columns A and B added together. The resulting DataFrame will look like this:

```
   A  B  C  D
0  1  4  7  5
1  2  5  8  7
2  3  6  9  9
```
Alternatively, you could also use the pandas.DataFrame.apply() method to apply a custom function to each row of the DataFrame, and create the new column based on the output of that function. For example, the following code would accomplish the same task as the code above:

```
import pandas as pd

df = pd.DataFrame({'A': [1, 2, 3], 'B': [4, 5, 6], 'C': [7, 8, 9]})

def sum_columns(row):
    return row['A'] + row['B']

df = df.assign(D = df.apply(sum_columns, axis=1))

print(df)
```
This code will also create a new column D in the DataFrame with the values from columns A and B added together. The resulting DataFrame will be the same as the one shown above.
TIL: The easiest way to handle index overflow...
Tags: javascript, todayilearned, testing
Published: 2022-12-22 08:25:49

## TLDR;

You can use the modulo operator in conjunction with the length of the array. This requires you to set you position after every change.

```JS
handleOverflow(options, chosen) {
 return (options.length + chosen) % options.length
}
```

Recently, I was working on a search input with an autocomplete feature. One of the requirements was that users should be able to cycle through the options by pressing arrow keys. Additionally, if you were at the last item and pressed `down` it should jump to the first item in the list. Similarly, if you were at the first element and pressed `up` it should jump to the last item. 

## First Solution
### The Mental Model

1. I have an array of options
1. I have a numerical value to access one element of that array, the index
  1. In order to get the next element I increase the index.
  1. In order to get the previous element I decrease the index.
1. If the index gets below `0` I need to jump to the end
1. If the index gets bigger than the index of the last element, I need to jump to first element.

### Solution

```JS
handleOverflow(options, chosen) {
  let next = chosen;

  if (next > options.length - 1) {
    next = min;
  }

  if (next < 0) {
    next = max;
  }

  return next;
}
```

### What I did not like about the implementation

1. It is verbose
1. I have to reset a value inside of the function

## 'Improving' the solution

What basically happens is that I need to access an element in a list with a known size. So basically, I only need to worry about the size of the array and the position I am at.

So, if I am at position 5 (meaning the 6th element) in an array with 6 elements and I want to go to the next element I go to index 6. Unfortunately, that does not exist so I go back to the start which is at index 0. I know that `6 % 6` equals `0`. Hence, accessing the array by `index % array.length` would work for positive numbers. 

With negative numbers, that does not work unfortunately as `-1 % array.length` equals `-1` so even by removing the `-` I would land at the first element, not the last. This forces me to add the length of the array to the result of the modulo operation and BAM, we have the solution:

```JS
handleOverflow(options, chosen) {
 return (options.length + chosen) % options.length
}
```

What do you think about this solution? 
Is it better or worse than the first?
How would you handle this problem?

Best and Happy Holidays!
10 Golden Rules for Solving a Coding Question in an Interview :
Tags: programming, productivity, beginners, career
Published: 2022-12-22 08:22:11

1. If we are dealing with **top/maximum/minimum/closest** 'K' elements among 'N' elements, we will be using a **Heap**.

2. If the given input is a **sorted array** or a list, we will either be using **Binary Search** or the **Two Pointers** strategy.

3. If we need to try all **combinations** (or permutations) of the input, we can either use **Backtracking** or **Breadth First Search**.

4. Most of the questions related to **Trees** or **Graphs** can be solved either through **Breadth First Search** or **Depth First Search**.

5. Every **recursive** solution can be converted to an **iterative** solution using a **Stack**.

6. For a problem involving arrays, if there exists a solution in **O(n^2) time** and **O(1) space**, there must exist two other solutions: 
(1) Using a **HashMap** or a **Set** for O(n) time and O(n) space.
(2) Using **sorting** for O(n log n) time and O(1) space.

7. If a problem is asking for **optimization** (e.g., maximization or minimization), we will be using **Dynamic Programming**.

8. If we need to find some common **substring** among a set of strings, we will be using a **HashMap** or a **Trie**.

9. If we need to **search/manipulate** a bunch of strings, **Trie** will be the best data structure.

10. If the problem is related to a **LinkedList** and we can't use extra space, then use the **Fast & Slow** **Pointer** approach.
How to use the Azure SDK for Python to retrieve a list of Azure Resources
Tags: azure, python, pandas, howto
Published: 2022-12-22 08:19:52

## Introduction

The [Azure SDK for Python](https://learn.microsoft.com/en-us/azure/developer/python/sdk/azure-sdk-overview) [1] is one of many ways to connect to Azure REST APIs and extract information. Here is an example on how to retrieve all resources from an Azure subscription, put the data into a [Pandas DataFrame](https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.html) [2] and plot a simple pie chart using [matplotlib](https://matplotlib.org/) [3].

### Import Libraries

We need to import the following libraries.

```python
# Import libraries
from azure.identity import AzureCliCredential
from azure.mgmt.resource import ResourceManagementClient
import pandas as pd
import matplotlib
```

### Acquire Credentials and obtain the Management Object

When using `AzureCliCredential()`, Python will use the Azure CLI context of the currently logged-in user for executing the queries.

```python
# Acquire credential
credential = AzureCliCredential()

# Define Scope
subscription_id = "subscription_id"

# Obtain the management object for resources.
resource_client = ResourceManagementClient(credential, subscription_id)
```

### Create and Populate a Dictionary

Using `resource_client.resources.list()` through the resource client will retrieve an interable object with all Azure resources in the given subscription. We can now populate a Python dictionary with the resources and add them to a Pandas DataFrame.

```python
resources = resource_client.resources.list()
dict = []
for resource in resources:
    dict.append(resource.as_dict())
```

### Create a DataFrame from the Dictionary

```python
df = pd.DataFrame.from_dict(dict)
```

### Select only the Top 10 rows based on the Resource Type Count

```python
type_df = df['type'].value_counts()
type_df_top = type_df.head(10)
```

### Finally plot the Pie Chart

```python
plot = type_df_top.plot.pie(figsize=(10, 10), autopct= lambda x: '{:.0f}'.format(x*type_df_top.sum()/100))
```

... which might look like something along these lines.
![Pie Chart](https://github.com/holgerjs/az-sdk-py-samples/raw/main/images/pie-chart.png)

## Summary

This short article has scratched the surface on what is possible when using the Azure SDK for Python since it allows as to combine the power of Python with the capabilities of the Azure REST API.
We have extracted a list of Azure resources based on a given context, added them to a Pandas DataFrame and plotted a simple pie chart based on the top 10 resource count.

## References

| # | Title | URL |
| --- | --- | --- |
| 1 | Use the Azure libraries (SDK) for Python | https://learn.microsoft.com/en-us/azure/developer/python/sdk/azure-sdk-overview |
| 2 | pandas.DataFrame | https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.html |
| 3 | Matplotlib: Visualization with Python | https://matplotlib.org/ |
NB-IoT-based Architecture of Smart Street Lamps
Tags: iot
Published: 2022-12-22 08:11:28

The intelligent street light system can realize the intelligent monitoring and management of the urban lighting Internet of Things. From the control center, it can monitor and intelligently perceive all the equipment used in the system (including power supply transformers, lighting distribution boxes, power supply cables, single lighting electrical equipment, lighting power savers Equipment, etc.) working parameters and working status, to realize the digitalization of urban lighting equipment, refined monitoring and management, to realize the digital control and management of urban lighting energy, to avoid the waste of lighting energy, and to save lighting energy to the greatest extent.
The intelligent street light system consists of a central management system, a communication transmission system and a single light controller.
**(1) Center management system**
The central management system is the core of the entire intelligent street lamp system, including functions such as data analysis, summary storage, and release of control commands, as well as the specific functions of street lamp inspection, street lamp equipment management, street lamp operation and maintenance management, and related operation reports. The central management system is composed of communication server, database server workstation and related network equipment.
**(2) Communication transmission system**
The communication transmission system is an Internet of Things communication platform for building a large-area platform to realize the interconnection of lighting equipment within the city. NB-IoT, [GPRS](https://www.ru-ebyte.com/Module-4GNBGPRSGPSCAN), LTE and other cellular networks are used to control terminal equipment from the central management system to the pressure-resistant power distribution cabinet (transformer, power saver).
**(3) Single lamp controller**
The single lamp controller can control street lamp switch, brightness adjustment, current collection, voltage collection, calculation of power and power factor, etc., and can add functions such as temperature collection and lamp pole tilt monitoring.