id
int64
5
1.93M
title
stringlengths
0
128
description
stringlengths
0
25.5k
collection_id
int64
0
28.1k
published_timestamp
timestamp[s]
canonical_url
stringlengths
14
581
tag_list
stringlengths
0
120
body_markdown
stringlengths
0
716k
user_username
stringlengths
2
30
795,870
When and how to JOIN a table with itself
“They’re the same table.” Relational databases make it very easy to join data from different...
0
2021-08-18T08:55:53
https://chuniversiteit.nl/programming/when-and-how-to-join-a-table-with-itself
sql
> _“They’re the same table.”_ **Relational databases make it very easy to join data from different tables, but did you know you can also JOIN data within the same table?** Relational databases make it easy to JOIN (combine) data from different tables. However, you can also JOIN a table with itself. This is especially handy when a table already contains all the data you need, but not in the right format. ## References to the same table One of the most common reasons to JOIN a table with itself, is because you have a table that contains a foreign key reference to itself. In the example below we have an `employees` table with employees. The table includes a `manager_id` column that refers to an employee in that same `employees` table. <table> <thead> <tr> <th colSpan="3" style="text-align: center">employees</th> </tr> <tr> <th>id</th> <th>name</th> <th>manager_id</th> </tr> </thead> <tbody> <tr> <td>1</td> <td>Denholm</td> <td></td> </tr> <tr> <td>2</td> <td>Richmond</td> <td></td> </tr> <tr> <td>3</td> <td>Roy</td> <td>5</td> </tr> <tr> <td>4</td> <td>Maurice</td> <td>5</td> </tr> <tr> <td>5</td> <td>Jen</td> <td>1</td> </tr> </tbody> </table> If we want to create an overview that lists the `name` of each employee along with the `name` of their manager, we need to join the `employees` table with itself. When we do this, we need to assign <Note>an alias | Think of these as variable names for your tables!</Note> to one (or both) of them so that the database can distinguish between the two instances. It doesn’t really matter what names you use, as long as they’re unique and make sense to you. Since we have two tables with identical column names, the database no longer understands what you mean when you say you want something like a `name`. You therefore have to explicitly tell it that you want the `name` of some row in the `employees` or the `managers` version of the table. This can be done by prepending column names with a table alias, followed by a `.`: ```sql SELECT employees.id, employees.name, managers.name AS manager -- Note: the “AS” here is optional FROM employees LEFT JOIN -- Use an INNER JOIN to exclude employees without a manager employees AS managers -- Note: this “AS” is optional as well! ON employees.manager_id = managers.id; ``` This query gives us the following result: ```txt +----+----------+---------+ | id | name | manager | +----+----------+---------+ | 1 | Denholm | NULL | | 2 | Richmond | NULL | | 3 | Roy | Jen | | 4 | Maurice | Jen | | 5 | Jen | Denholm | +----+----------+---------+ ``` ## Computing durations between changes Another common reason to use self joins is to calculate some duration or distance between pairs of rows within a table. For example, the `order_state` table below keeps track of state changes that happen to orders at a webshop. Each record in this table includes a reference to the order, the name of the new state, and shows when the order changed to its new state. Can we calculate how long each of these state transitions took? <table> <thead> <tr> <th colSpan="4" style="text-align: center">order_state</th> </tr> <tr> <th>id</th> <th>order_id</th> <th>state</th> <th>created_at</th> </tr> </thead> <tbody> <tr> <td>1</td> <td>1</td> <td>placed</td> <td>2021-06-01 00:01:00</td> </tr> <tr> <td>2</td> <td>1</td> <td>packaged</td> <td>2021-06-01 00:58:00</td> </tr> <tr> <td>3</td> <td>1</td> <td>despatched</td> <td>2021-06-01 02:20:00</td> </tr> <tr> <td>4</td> <td>1</td> <td>delivered</td> <td>2021-06-01 15:20:00</td> </tr> <tr> <td>5</td> <td>2</td> <td>placed</td> <td>2021-06-02 14:10:00</td> </tr> <tr> <td>6</td> <td>2</td> <td>packaged</td> <td>2021-06-02 18:55:00</td> </tr> <tr> <td>7</td> <td>3</td> <td>placed</td> <td>2021-06-02 19:00:00</td> </tr> <tr> <td>8</td> <td>3</td> <td>packaged</td> <td>2021-06-02 20:30:00</td> </tr> <tr> <td>9</td> <td>3</td> <td>despatched</td> <td>2021-06-03 01:40:00</td> </tr> <tr> <td>10</td> <td>2</td> <td>despatched</td> <td>2021-06-03 01:40:00</td> </tr> <tr> <td>11</td> <td>2</td> <td>delivered</td> <td>2021-06-03 08:00:00</td> </tr> <tr> <td>12</td> <td>3</td> <td>delivered</td> <td>2021-06-03 16:10:00</td> </tr> </tbody> </table> Of course we can! The query below shows how. Once again, we have one table, `order_state`, that we want to JOIN with itself. We name one of these `from_state` and the other `to_state`, to represent the collection of states before and after the transition. Obviously, the two states involved in the transition should belong to the same order, so we add the condition that `from_state.order_id` must be equal to `to_state.order_id`. Moreover, the `to_state` should occur later than the `from_state`, so we’ll also add a condition that the `to_state.id` must be higher than `from_state` (*). (*) _In real applications might also or only want to look at the timestamp. Be careful if multiple transitions can happen at the same time, e.g. within the same second!_ Finally, we want to make sure that we only see _direct_ state transitions, like those from `placed` to `packages`, and not indirect ones, like those from `placed` to `delivered`. This is done by first grouping by `from_state.id`, which ensures that the “from” state appears only once in the result, and then JOINING each `from_state` with the closest `to_state` record that exists, i.e. the record with the lowest `to_state.id`. ```sql SELECT from_state.order_id, from_state.state, to_state.state, to_state.created_at AS changed_at, TIMEDIFF(to_state.created_at, from_state.created_at) AS duration FROM order_state from_state INNER JOIN order_state to_state ON 1 -- This “1” here makes it possible to nicely align our JOIN conditions AND from_state.order_id = to_state.order_id AND from_state.id < to_state.id GROUP BY from_state.id HAVING MIN(to_state.id) ORDER BY order_id, from_state.id; ``` ```txt +----------+------------+------------+---------------------+----------+ | order_id | state | state | changed_at | duration | +----------+------------+------------+---------------------+----------+ | 1 | placed | packaged | 2021-06-01 00:58:00 | 00:57:00 | | 1 | packaged | despatched | 2021-06-01 02:20:00 | 01:22:00 | | 1 | despatched | delivered | 2021-06-01 15:20:00 | 13:00:00 | | 2 | placed | packaged | 2021-06-02 18:55:00 | 04:45:00 | | 2 | packaged | despatched | 2021-06-03 01:40:00 | 06:45:00 | | 2 | despatched | delivered | 2021-06-03 08:00:00 | 06:20:00 | | 3 | placed | packaged | 2021-06-02 20:30:00 | 01:30:00 | | 3 | packaged | despatched | 2021-06-03 01:40:00 | 05:10:00 | | 3 | despatched | delivered | 2021-06-03 16:10:00 | 14:30:00 | +----------+------------+------------+---------------------+----------+ ``` ## Creating pairs of data Self joins can also be used to easily create large or unique pairs of data from a relatively small set of data. ### Cartesian product You can join a table with itself without any JOIN conditions to create a result set that includes every possible combination of values within a single table, for instance when you want to know how many possible configurations exist for a product or when you wish to discover which combinations are common or rare. In the example below, we combine multiple instances of a `digit` table to form larger numbers. <table> <thead> <tr> <th style="text-align: center">digit</th> </tr> <tr> <th>id</th> </tr> </thead> <tbody> <tr> <td>0</td> </tr> <tr> <td>1</td> </tr> <tr> <td>2</td> </tr> <tr> <td>3</td> </tr> <tr> <td>4</td> </tr> <tr> <td>5</td> </tr> <tr> <td>6</td> </tr> <tr> <td>7</td> </tr> <tr> <td>8</td> </tr> <tr> <td>9</td> </tr> </tbody> </table> ```sql SELECT CONCAT(B.id, A.id) AS number FROM digit A JOIN digit B; ``` ```txt +--------+ | number | +--------+ | 00 | | 01 | | 02 | | 03 | | 04 | | 05 | | 06 | | 07 | | 08 | | 09 | | 10 | | 11 | | 12 | | 13 | | 14 | | 15 | | 16 | | 17 | | 18 | | 19 | | 20 | | 21 | | 22 | | 23 | | 24 | | 25 | | 26 | | 27 | | 28 | | 29 | | 30 | | 31 | | 32 | | 33 | | 34 | | 35 | | 36 | | 37 | | 38 | | 39 | | 40 | | 41 | | 42 | | 43 | | 44 | | 45 | | 46 | | 47 | | 48 | | 49 | | 50 | | 51 | | 52 | | 53 | | 54 | | 55 | | 56 | | 57 | | 58 | | 59 | | 60 | | 61 | | 62 | | 63 | | 64 | | 65 | | 66 | | 67 | | 68 | | 69 | | 70 | | 71 | | 72 | | 73 | | 74 | | 75 | | 76 | | 77 | | 78 | | 79 | | 80 | | 81 | | 82 | | 83 | | 84 | | 85 | | 86 | | 87 | | 88 | | 89 | | 90 | | 91 | | 92 | | 93 | | 94 | | 95 | | 96 | | 97 | | 98 | | 99 | +--------+ ``` I once used a very similar method to generate lists of dates in a legacy business intelligence application that was built on top of a MySQL database: ```sql SELECT DATE_ADD( CONCAT( YEAR(CURDATE()), -- Get the current year '-01-01' -- Append “-01-01” to it so that we get “2021-01-01” ), INTERVAL CONCAT(B.id, A.id) DAY -- Show 2021-01-01 + x days ) AS date FROM digit A JOIN digit B; ``` ```txt +------------+ | date | +------------+ | 2021-01-01 | | 2021-01-02 | | 2021-01-03 | | 2021-01-04 | | 2021-01-05 | | 2021-01-06 | | 2021-01-07 | | 2021-01-08 | | 2021-01-09 | | 2021-01-10 | | 2021-01-11 | | 2021-01-12 | | 2021-01-13 | | 2021-01-14 | | 2021-01-15 | | 2021-01-16 | | 2021-01-17 | | 2021-01-18 | | 2021-01-19 | | 2021-01-20 | | 2021-01-21 | | 2021-01-22 | | 2021-01-23 | | 2021-01-24 | | 2021-01-25 | | 2021-01-26 | | 2021-01-27 | | 2021-01-28 | | 2021-01-29 | | 2021-01-30 | | 2021-01-31 | | 2021-02-01 | | 2021-02-02 | | 2021-02-03 | | 2021-02-04 | | 2021-02-05 | | 2021-02-06 | | 2021-02-07 | | 2021-02-08 | | 2021-02-09 | | 2021-02-10 | | 2021-02-11 | | 2021-02-12 | | 2021-02-13 | | 2021-02-14 | | 2021-02-15 | | 2021-02-16 | | 2021-02-17 | | 2021-02-18 | | 2021-02-19 | | 2021-02-20 | | 2021-02-21 | | 2021-02-22 | | 2021-02-23 | | 2021-02-24 | | 2021-02-25 | | 2021-02-26 | | 2021-02-27 | | 2021-02-28 | | 2021-03-01 | | 2021-03-02 | | 2021-03-03 | | 2021-03-04 | | 2021-03-05 | | 2021-03-06 | | 2021-03-07 | | 2021-03-08 | | 2021-03-09 | | 2021-03-10 | | 2021-03-11 | | 2021-03-12 | | 2021-03-13 | | 2021-03-14 | | 2021-03-15 | | 2021-03-16 | | 2021-03-17 | | 2021-03-18 | | 2021-03-19 | | 2021-03-20 | | 2021-03-21 | | 2021-03-22 | | 2021-03-23 | | 2021-03-24 | | 2021-03-25 | | 2021-03-26 | | 2021-03-27 | | 2021-03-28 | | 2021-03-29 | | 2021-03-30 | | 2021-03-31 | | 2021-04-01 | | 2021-04-02 | | 2021-04-03 | | 2021-04-04 | | 2021-04-05 | | 2021-04-06 | | 2021-04-07 | | 2021-04-08 | | 2021-04-09 | | 2021-04-10 | +------------+ ``` ### Unique pairs Sometimes you’re only interested in _unique_ combinations. For example when you need to create pairs of people or want to list edges in an undirected graph (**): it doesn’t matter which value is listed first or second – what matters is that the first and second values are listed together exactly once. (**) _Yes, you can store graphs in a relational database!_ The example below shows a simple `person` table that contains the names of six people. <table> <thead> <tr> <th colSpan="2" style="text-align: center">person</th> </tr> <tr> <th>id</th> <th>name</th> </tr> </thead> <tbody> <tr> <td>1</td> <td>Rachel</td> </tr> <tr> <td>2</td> <td>Monica</td> </tr> <tr> <td>3</td> <td>Phoebe</td> </tr> <tr> <td>4</td> <td>Joey</td> </tr> <tr> <td>5</td> <td>Chandler</td> </tr> <tr> <td>6</td> <td>Ross</td> </tr> </tbody> </table> We can create a list of possible pairings by adding a simple condition to the JOIN clause: ```sql SELECT A.name, B.name FROM person A JOIN person B ON A.id < B.id; ``` ```txt +----------+----------+ | name | name | +----------+----------+ | Rachel | Monica | | Rachel | Phoebe | | Rachel | Joey | | Rachel | Chandler | | Rachel | Ross | | Monica | Phoebe | | Monica | Joey | | Monica | Chandler | | Monica | Ross | | Phoebe | Joey | | Phoebe | Chandler | | Phoebe | Ross | | Joey | Chandler | | Joey | Ross | | Chandler | Ross | +----------+----------+ ``` ## Ranking results Self-JOINs can also be used to [compute ranks of query results](https://chuniversiteit.nl/programming/how-do-you-number-select-query-results-using-sql#a-workaround-for-rank), although nowadays there are [much better ways to do this](https://chuniversiteit.nl/programming/how-do-you-number-select-query-results-using-sql#the-recommended-way-to-number-rows).
chuniversiteit
795,937
HNG i8 goals
The HNG internship is a free 8 week training opportunity organized by hotels.ng/zuri training based...
0
2021-08-18T09:39:57
https://dev.to/payn33/hng-i8-goals-eaf
hng
The HNG internship is a free 8 week training opportunity organized by hotels.ng/[zuri training] (https://internship.zuri.team) based in Nigeria and open to both local and international participants. The internship simulates a real world working environment and scenarios with the goal of getting participants acquainted with working in the tech industry, and also provides opportunities for developers to expand their network. As a frontend developer, my goals for joining this internship are to expose myself to new tech, expand my network, and gain more experience. ###Thinking of starting web development? Here are some helpful links * [git] (https://youtu.be/USjZcfj8yxE) * [html and css] (https://youtu.be/QMnv3QrjZoU) * [JavaScript] (https://youtu.be/W6NZfCO5SIk) * [Figma] (https://youtu.be/FTFaQWZBqQ8)
payn33
795,949
Meeting diverse compliances with a single solution: AWS Config.
Enterprise sized organizations regularly allocate multiple AWS accounts to their various teams. In...
0
2021-08-18T10:08:34
https://dev.to/teleglobal/meeting-diverse-compliances-with-a-single-solution-aws-config-2pmn
aws, cloudnative
Enterprise sized organizations regularly allocate multiple AWS accounts to their various teams. In such an environment it can be a big challenge to keep track of all the accounts and ensure they meet different compliances. AWS Config service is indispensable in helping organizations check, and assess configurations of all these diverse AWS resources. By enabling continuous monitoring & recording of the different configurations AWS Config facilitates evaluations, helping organizations confirm to accepted governance norms. Non-Compliance Problems Without continuous compliance, an organization can experience problems such as inability to scale, or conduct thorough assessments, exhaust compliance events, and receive sub-optimal feedback. Scaling Failure Rapid, real-time changes demand rapid scaling. This is one of the prime benefits of a cloud environment. Lack of compliance, or manual compliance approach sabotages ability to scale rapidly. Inaccurate Assessments Changes are another regular feature of cloud-based infrastructures. If these go unnoticed, they could cause violations of policy. If there is no automated and continuous compliance approach, difficulty in assessments is further exacerbated when APIs are used to deploy changes. Wastage of Resources Without continuous compliance process, Organizations expend time and use up significant resources to conduct audits— external and internal—when proving compliance. Incomplete Feedback Without complete feedback, product teams will not be able to ensure change management to updated products. This feedback needs continuous and complete compliance, which manual approaches cannot deliver, as they can only perform partial compliance on individual events during a release lifecycle. AWS Config to the Rescue AWS Config tracks changes and resource inventory and provides assurance that new and existing AWS resources conform to the organization’s operational practice and security policy. AWS Config offers total visibility of all resources related to the various allocated, configurations made different accounts, and subsequent changes. Organizations that allocate multiple AWS accounts to their in-house teams will benefit from using AWS Config in several ways, as follows: Compliance-As-Code AWS Config can be used to automate a rule or enforce policy. Config Rules enables reports on specific controls in a chosen framework. Controls can include encryption, controlled access to resource, usage, and sharing. Config Rules come bundled as standard out-of-the-box functionalities, but allow simple customization. They clearly show a resource’s pass/fail status with regard to a specific compliance. Transparent Reporting Distribution of AWS accounts to various teams could hinder reporting of compliance state. AWS Config offers a comprehensive and customizable record of all changes that have been deployed providing a record of how well the organization’s resources have met compliances. This programmatic-log provides vital data that can be used as a reference during compliance audits. For companies moving to microservices based on CI/CD (Continuous Integration and Continuous Deployment), AWS Config provides a trail of all continuous actions. This enables accurate reporting on internal processes at each CI/CD deployment. Automating problem mitigations With AWS Config enterprises can automate mitigations or fix noncompliant resources automatically, by adding rules via API or console. AWS documents provide instructions in the documents to provide guidelines to different actions as per the state of AWS resources. AWS Config Rules AWS Config Rules provide the settings for desired configurations for AWS resources/accounts. An account that violates the rules is flagged by AWS Config as noncompliant, and it triggers a notification through the Amazon SNS (Simple Notification Service). Config Rules can be customized or used as predetermined. Customizable rules help an org get up and running on the continuous compliance process. New rules are added regularly to cover new practices, technologies, and/or security protocols. Organizations can also create their own customized Config rules specific to the compliance needs of their distributed accounts. Such customized rules allow organizational teams to address compliance deficiencies in AWS accounts and ensure ongoing compliance.
teleglobal
796,001
Anime list reactjs+Jikan API
Fetching Anime List using Jikan API in reactjs LIVE: Anime-suem GitHub...
0
2021-08-18T12:08:36
https://dev.to/sandyabhi/anime-list-reactjs-jikan-api-2njp
react, anime, javascript, html
# Fetching Anime List using Jikan API in reactjs ###LIVE: [Anime-suem](https://anime-suem.netlify.app/) ###GitHub : [Repo](https://github.com/sandyabhi/anime-suem) ###Step 1 create react app using command `npx create-react-app animeseum` ###### After the command create the folders and files like image given below: ![Screenshot (27)](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/tlf0szak0ilogetv2mpa.png ) OR you can change files name as you desire. ### Step 2 ### Read the comments in the code for explanation In **App.js** ``` import { useState, useEffect } from "react"; // importing other components import Header from "./components/Header.js"; import Footer from "./components/Footer.js"; import Home from "./pages/Home.js"; function App() { // Creating state variables using useState Hooks : // "animeList" variable will be used for the searched anime // "topAnime" variable will be used for all the popular anime // "search" variable will be used for search terms const [animeList, setAnimeList] = useState([]); const [topAnime, setTopAnime] = useState([]); const [search, setSearch] = useState(""); // Fetching top anime (by popularity) from jikan API // In place of simple fetch method you can axios library // async function is used so don't to the keyword await const getTopAnime = async () => { const data = await fetch( `https://api.jikan.moe/v3/top/anime/1/bypopularity` ).then((res) => res.json()); setTopAnime(data.top); }; const handleSearch = (e) => { e.preventDefault(); fetchAnime(search); }; // Fetching searched anime from jikan API const fetchAnime = async (anime_name) => { const data = await fetch( `https://api.jikan.moe/v3/search/anime?q=${anime_name}&order_by=title&sort=asc&limit=10` ).then((res) => res.json()); setAnimeList(data.results); }; // get getTopAnime() as the site render useEffect is used useEffect(() => { getTopAnime(); }, []); return ( <> <div className="App" > <Header /> {/* Main Content */} <Home // passing props to the Home Component handleSearch={handleSearch} search={search} setSearch={setSearch} animeList={animeList} topAnime={topAnime} /> <Footer /> </div> </> ); } export default App; ``` In **Home.js** ``` import "../styles/Home.css"; import AnimeCard from "../components/AnimeCard"; // you can get the props "function Home(props)" in this manner /* OR you can destructure it "function Home({handleSearch, search, setSearch, topAnime, animeList })" and use "search" instead of "props.search" */ function Home(props) { return ( <main> <div className="home"> <form className="search-box" onSubmit={props.handleSearch}> <input type="search" placeholder="Search ..." required value={props.search} onChange={(e) => props.setSearch(e.target.value)} /> </form> </div> {/* if there is no text in the search bar it will show top anime(by popularity) and on searching it will show search results use map() function to get all element in the array */} {!props.search ? ( <div className="card-main"> {props.topAnime.map((anime) => ( <AnimeCard anime={anime} key={anime.mal_id} /> ))} </div> ) : ( <div className="card-main"> {props.animeList.map((anime) => ( <AnimeCard anime={anime} key={anime.mal_id} /> ))} </div> )} </main> ); } export default Home; ``` In **AnimeCard.js** ``` import "../styles/AnimeCard.css" /* You can add anime synopsis you can check all elements using "console.log(getTopAnime)" in useEffect (App.js) if you want */ function AnimeCard({anime}) { // Anime Cards return ( <a className="card-body" href={anime.url} alt={anime.title}> <figure className="card-fig"> <img className="card-image" src={anime.image_url} alt="Anime Image" /> </figure> <h3 className="card-title">{anime.title}</h3> </a> ) } export default AnimeCard ``` In **Header.js** ``` import "../styles/Header.css"; function Header() { return ( <header className="header"> <h1 className="title">Anime-Suem</h1> </header> ); } export default Header; ``` In **Footer.js** ``` import "../styles/Footer.css"; import GitHubIcon from "@material-ui/icons/GitHub"; import LinkedInIcon from "@material-ui/icons/LinkedIn"; // I have used material-ui icons you can use whatever you wish // "npm i @material-ui/icons" to install function Footer() { return ( <footer> <div className="footer"> <p>Created by: Sandeep Kumar Patel</p> <a href="https://github.com/sandyabhi/anime-suem" className="foots"> <GitHubIcon /> Github </a> <a href="https://www.linkedin.com/in/sandeep-kumar-patel47/" className="foots"> <LinkedInIcon /> Linkedin </a> </div> </footer> ); } export default Footer; ``` **Done** ### For the CSS part you can go to my [Github Repo.](https://github.com/sandyabhi/anime-suem) OR you can do it yourself or use bootstrap, material ui, semantic ui, Tailwind CSS etc ###Extension (VS CODE) -Prettier -ES7 React/Redux/GraphQL/React-Native snippets -Auto Rename Tag
sandyabhi
796,024
Hey guys i want to ask u something is it possible to learn programming to start your own business and open your startup
A post by Islem Magroun
0
2021-08-18T12:52:15
https://dev.to/islemmagroun/hey-guys-i-want-to-ask-u-something-is-it-possible-to-learn-programming-to-start-your-own-business-and-open-your-startup-4ogf
islemmagroun
796,197
React-query series Part 1: Basic react-query setup
Hey everyone! So after a few years as a frontend developer, I have decided to write my first...
14,234
2021-08-19T07:31:59
https://dev.to/nnajiforemma10/react-query-series-part-1-basic-react-query-setup-12g4
react, javascript, webdev, hooks
Hey everyone! So after a few years as a frontend developer, I have decided to write my first article. You have no idea the fear I had to conquer (or maybe you do), :worried: but there is no point hiding in your shell right ? ## Sections * [Intro](#chapter-0) * [Prerequisite](#chapter-1) * [Bootstrap our project](#chapter-2) * [Setup react-query](#chapter-3) * [Credits](#chapter-4) ## Intro <a name="chapter-0"></a> [React-query](https://react-query.tanstack.com/) is a superlight library for fetching, updating and synchronizing server state. With react-query, you don't have to write your data-fetching logic (Who likes all that setting of loading, error and data state huh ? :woman_shrugging: ), You don't also need global store libraries like redux or zustand to make your server state global or persistent. Even if a global store is used in your application, it is restricted to only client state like user settings etc, thereby reducing your code size by a ton. Although this library has a wonderful documentation, I have found that it can be daunting for beginners and thus, a need for a no-nonsense simple series to get beginners quickly setup to using react-query. You can also skip to the [part two: QueryClient configuration](https://dev.to/nnajiforemma10/react-query-series-part-2-queryclient-configuration-18g6) of this series ## Prerequisite <a name="chapter-1"></a> * Basic knowledge of react and hooks in react ## Bootstrap our project <a name="chapter-2"></a> We bootstrap a basic react app by running `npx create-react-app project-name` ``` npx create-react-app react-query-setup ``` We also install react-query library to our react app by running `npm i react-query`. At the time of writing, [react-query](https://www.npmjs.com/package/react-query) version is at 3.19.6 ``` npm i react-query ``` ## Setup react-query <a name="chapter-3"></a> To setup react-query, we need the `QueryClientProvider`. The `QueryClientProvider` component is used to connect and provide a `QueryClient` to your application; more or less, connect our application to features react-query provides. The `QueryClientProvider` component takes in a `client` prop. This prop is in turn, supplied the `queryClient` instance. You can supply the `queryClient` instance a custom config object as a `param` if you'd like to set your own defaults. You can read about some important defaults that come with react-query [here.](https://react-query.tanstack.com/guides/important-defaults) ```javascript import { QueryClient, QueryClientProvider } from 'react-query'; /*create and use a custom config object.Normally, I'd put this in another file and export */ const queryClientConfig = { defaultOptions: { queries: { retry: 2, refetchOnMount: "always", refetchOnWindowFocus: "always", refetchOnReconnect: "always", cacheTime: 1000*30, //30 seconds refetchInterval: 1000*30, //30 seconds refetchIntervalInBackground: false, suspense: false, staleTime: 1000 * 30, }, mutations: { retry: 2, }, }, const queryClient = new QueryClient(queryClientConfig) function App() { return <QueryClientProvider client={queryClient}>...</QueryClientProvider> } ``` Additionally, you can add the [`ReactQueryDevTools`](https://react-query.tanstack.com/devtools) component to debug and visualize your queries on your development environment. ```javascript import { QueryClient, QueryClientProvider } from 'react-query'; import { ReactQueryDevtools } from 'react-query/devtools'; /*create and use a custom config object.Normally, I'd put this in another file and export */ const queryClientConfig = { defaultOptions: { queries: { retry: 2, refetchOnMount: "always", refetchOnWindowFocus: "always", refetchOnReconnect: "always", cacheTime: 1000*30, //30 seconds refetchInterval: 1000*30, //30 seconds refetchIntervalInBackground: false, suspense: false, staleTime: 1000 * 30, }, mutations: { retry: 2, }, }, const queryClient = new QueryClient(queryClientConfig) function App() { return <QueryClientProvider client={queryClient}> {/* The rest of your application */} <ReactQueryDevtools initialIsOpen={false} /> </QueryClientProvider> } ``` In the [next part](https://dev.to/nnajiforemma10/react-query-series-part-2-queryclient-configuration-18g6) of this series, we will talk more on what each key-value in the `queryClientConfig` object does for queries and mutations. I'd really appreciate a :sparkling_heart: if this article has helped you. Thank you! Follow me on [twitter @NnajioforEmma10 ](https://twitter.com/NnajioforEmma10) ## Credits <a name="chapter-4"></a> Image: [Logrocket: What is new in react-query 3 by Lawrence Eagles](https://blog.logrocket.com/whats-new-in-react-query-3/). [React-query documentation](https://react-query.tanstack.com) ## Sections * [Intro](#chapter-0) * [Prerequisite](#chapter-1) * [Bootstrap our project](#chapter-2) * [Setup react-query](#chapter-3) * [Credits](#chapter-4)
nnajiforemma10
796,208
How to create an inspection checklist using Low-code
Your business is not intangible. It's made up of processes, plants, locations you cover, products and...
0
2021-08-18T14:54:07
https://www.dronahq.com/digitize-paper-based-inspection/
showdev, tutorial, lowcode
<span style="font-weight: 400;">Your business is not intangible. It's made up of processes, plants, locations you cover, products and services you make, and people you engage (customers, employees, external partners). These elements, if left unchecked, may lead to major issues or downtime. If risks are not understood, tracked, and tackled, recovery can get pricey. Companies working with machinery, natural resources, external technology, and a large workforce are always running the risk of unforeseen downtimes, product failure, defective production, exceeding budgets, compliance issues, and more. Each of these negative outcomes is almost always dependent on inadequate monitoring and management of the resources. </span> <span style="font-weight: 400;">To keep employees and the workplace safe and processes working at optimum capacity, using appropriate audits and inspections instruments are a necessity. These inspection checklists when used properly are an assurance that a particular piece of equipment has been inspected. As each item in the checklist gets ticked off, the individual performing the inspection is verifying whether each component of the equipment is in correct working order or not.</span> &nbsp; <h3><b>Building an inspection checklist </b></h3> <span style="font-weight: 400;">DronaHQ enables users to build inspection forms and checklists for many scenarios - like site evaluations, equipment performance assessment, staff safety, vehicle inspection, home audit, and lots more.</span> <span style="font-weight: 400;">You can take your inspection program to the next level using drag &amp; drop checklist builder to add the right form field to your checklist and standardize data collection. It is incorporated with options to implement your custom business rules and get complete control over the data getting collected from the checklist app. Add the exact UI modules you require for taking down the information, use action flows to set up actions on events such as report generation on button click, approval request, database calls,  notifications, assigning of tasks, updating the records, and even triggering events easily in other enterprise systems using API integrations. </span> <span style="font-weight: 400;">In this blog, we will learn how to create an inspection checklist for a </span><b>Vehicle Inspection Checklist </b><span style="font-weight: 400;">on DronaHQ.</span> <span style="font-weight: 400;"> </span><span style="font-weight: 400;">Phase 1: Create the Checklist. We will cover data collection (text and rich media), form field validation, conditional rules and visibility, and </span> <span style="font-weight: 400;">Phase 2: Database Updates - Submit inspection data to database of choice (Google Sheets, Airtable, MongoDB, PostgreSQL, and so on) or DronaHQ Sheets</span> <span style="font-weight: 400;">Phase 3: Email and Notifications to report escalations, update new form submissions </span> <span style="font-weight: 400;">Phase 4: Report Generation - Generate PDF Report automatically </span><span style="font-weight: 400;"> </span> <b>Add a Blank App:</b> <span style="font-weight: 400;"> </span><span style="font-weight: 400;">Login to DronaHQ and head over to App. You can browse through the ready templates to find a suitable one for your use case. In this example, we will be building an inspection checklist from scratch. So we start with a “Blank App”.</span> <span data-preserver-spaces="true"><img class="alignnone wp-image-15602" src="https://www.dronahq.com/wp-content/uploads/2019/12/1.-Login-and-Add-blank-app-1024x487.png" alt="" width="648" height="308" /></span> <b>Add App Description:</b> <span style="font-weight: 200;">At this step we need to enter 3 key details: App name [1], app description [2], and app icon [5]. You can always come back and edit the information you enter here. </span><span style="font-weight: 400;"> </span><span style="font-weight: 400;">Under Pick a Catalogue [3] you can define which catalogue this app is going to be a part of in DronaHQ. This determines which user group will be able to access the app on an end user screen. </span><span style="font-weight: 400;"> </span> </b><img class="alignnone wp-image-15603" src="https://www.dronahq.com/wp-content/uploads/2019/12/2.-App-description-1024x577.png" alt="2. vehicle inspection App description" width="694" height="391" /> <b>Creating the Inspection Checklist:</b> &nbsp; <ol> <li style="font-weight: 400;" aria-level="2"><span style="font-weight: 400;">You can start adding form fields to capture details. </span><i></i><b><b><i><span style="font-weight: 400;"> <img class="alignnone wp-image-15604" src="https://www.dronahq.com/wp-content/uploads/2019/12/3.-Add-Controls-to-blank-screen-1024x485.png" alt="3. Add Controls to blank screen" width="671" height="318" /></span></i></b></b></li> <li style="font-weight: 400;" aria-level="2"><b><i></i></b><span style="font-weight: 400;"><span style="font-weight: 400;">I will break down this inspection checklist to sections so, to start off, I add a heading control to the screen.</span></span><img class="alignnone wp-image-15605" src="https://www.dronahq.com/wp-content/uploads/2019/12/4.-Heading-for-Form-Sections-1024x495.png" alt="4. Heading for Form Sections" width="623" height="301" /></li> <li style="font-weight: 400;" aria-level="2"><span style="font-weight: 400;"><span style="font-weight: 400;">Dropdown control is a handy input control for a checklist</span></span><img class="alignnone wp-image-15626" src="https://www.dronahq.com/wp-content/uploads/2019/12/image26-1024x324.png" alt="" width="668" height="211" />&nbsp;</li> <li style="font-weight: 400;" aria-level="2"><span style="font-weight: 400;">Bind data to the </span><b>dropdown control </b><span style="font-weight: 400;"><span style="font-weight: 400;">(this control supports a bunch of different methods to bind data - static data, from an API or database, or from DronaHQ in-built Sheets. I chose static data as the options were pretty standard. <img class="alignnone wp-image-15606" src="https://www.dronahq.com/wp-content/uploads/2019/12/6.-Bind-data-to-dropdown.png" alt="6. Bind data to dropdown" width="679" height="314" /></span></span></li> <li style="font-weight: 400;" aria-level="2"><span style="font-weight: 400;">Next I’d like the inspector to enter the mileage on the vehicle that would require a numeric input so I go ahead and add the</span><b> numeric control</b><span style="font-weight: 400;"><span style="font-weight: 400;">.</span></span></li> <li style="font-weight: 400;" aria-level="2"><span style="font-weight: 400;">You can also allow users to upload images of the vehicle so we add the </span><b>File Upload</b><span style="font-weight: 400;"><span style="font-weight: 400;"> control.</span></span><img class="alignnone wp-image-15607" src="https://www.dronahq.com/wp-content/uploads/2019/12/7.-Add-file-upload-1024x525.png" alt="7. Add file upload" width="646" height="331" />&nbsp; <ol> <li style="font-weight: 400;" aria-level="2"><span style="font-weight: 400;">Using this component you can define the file type the user can upload. I selected </span><b><b>Image</b></b></li> <li style="font-weight: 400;" aria-level="2"><span style="font-weight: 400;">Choose whether the user gets to upload an image from the gallery or only use a camera to take a picture and upload it. I chose </span><b><b>Camera only</b></b></li> <li style="font-weight: 400;" aria-level="2"><span style="font-weight: 400;">You can also limit the number of file/image uploads. I have set the limit to </span><b>1 photo</b><span style="font-weight: 400;"><span style="font-weight: 400;"> here</span></span><img class="alignnone wp-image-15608" src="https://www.dronahq.com/wp-content/uploads/2019/12/8.-File-Upload-properies.png" alt="8. File Upload properies" width="610" height="342" />&nbsp; Important: At this point, it should be noted that A. To ensure user fills in all the fields in the form, you can mark the fields as <b>required </b>B. If you want the checklist to be offline enabled, follow these steps: <a href="https://community.dronahq.com/t/creating-offline-forms/223" target="_blank" rel="noopener noreferrer">Offline forms in DronaHQ</a><img class="alignnone wp-image-15609" src="https://www.dronahq.com/wp-content/uploads/2019/12/9.-Required-Offline.png" alt="9. Required, Offline" width="665" height="259" /> &nbsp;</li> </ol> </li> <li style="font-weight: 400;" aria-level="2"><span style="font-weight: 400;">Since I am breaking down this checklist into sections, there are different approaches i can take here:</span> <ol> <li style="font-weight: 400;" aria-level="2"><span style="font-weight: 400;">Break page into sections - revealing each only as the user progresses through the stages</span></li> <li style="font-weight: 400;" aria-level="2"><span style="font-weight: 400;">Use different screens, navigating from one to another as each section gets over </span>I will use separate screens for each section. So, I start by labeling this screen before adding a new one.<img class="alignnone wp-image-15613" src="https://www.dronahq.com/wp-content/uploads/2019/12/10.-Heading.png" alt="10. Heading" width="631" height="421" />&nbsp;</li> </ol> </li> <li style="font-weight: 400;" aria-level="2"><span style="font-weight: 400;"><span style="font-weight: 400;">To add a screen, on the left panel, select SCREENS, the plus icon, and Screen from the dropdown menu.</span></span><img class="alignnone wp-image-15614" src="https://www.dronahq.com/wp-content/uploads/2019/12/11.-add-new-screen.png" alt="11. add new screen" width="660" height="408" />&nbsp;</li> <li style="font-weight: 400;" aria-level="2"><b>Navigate to next section </b><span style="font-weight: 400;">To allow the inspector to move from one section to next, we need to add some </span><b>event handlers</b><span style="font-weight: 400;"><span style="font-weight: 400;"> to the screen.</span></span><img class="alignnone wp-image-15610" src="https://www.dronahq.com/wp-content/uploads/2019/12/9.5.-Navigate.png" alt="9.5. Navigate" width="629" height="334" />&nbsp; While we can choose from these pre-built controls, we can also explore more visually aesthetic UI controls in the Marketplace.<img class="alignnone wp-image-15611" src="https://www.dronahq.com/wp-content/uploads/2019/12/9.6.-Button-1024x440.png" alt="9.6. Button" width="662" height="284" /> I added the button to the footer of the screen. <img class="alignnone wp-image-15612" src="https://www.dronahq.com/wp-content/uploads/2019/12/9.7.-Footer.png" alt="9.7. Footer" width="643" height="432" /> The flash symbol on the control shows that that control supports actions. On the right, select the next button and configure the <a href="https://community.dronahq.com/t/introducing-the-new-action-flow-interface/550">actionflow</a> to navigate from screen 1 to screen 2. &nbsp; <ol> <li style="font-weight: 400;" aria-level="2"><span style="font-weight: 400;">Validate - We need to make sure that the user filled in all the required fields on the screen. To do that, select the validate screen action task in the builder, then select the screen name.</span></li> <li style="font-weight: 400;" aria-level="2"><span style="font-weight: 400;"><span style="font-weight: 400;">Navigate - After successful validation - navigate to the next screen. If validation fails, we can choose to show a warning message</span></span>Note: These navigation button are necessary to be added to each section to allow user to proceed further or go back to previous sections.<img class="alignnone wp-image-15627" src="https://www.dronahq.com/wp-content/uploads/2019/12/image20-1024x488.png" alt="Using actionflows for form validation and navigation" width="590" height="281" /></li> </ol> </li> <li style="font-weight: 400;" aria-level="2"><b>Layout of the Checklist </b><span style="font-weight: 400;"><span style="font-weight: 400;">Follow this step if you want to control how the different form fields show across different screens.</span></span>I added layouts to this screen because we don’t want our checklist UI to get impacted based on device (think mobile vs. tablet vs. desktop). Here is an elaborate <a href="https://community.dronahq.com/t/layout-and-columnar-layouts/506">guide on using layouts</a>. For this use case, I add one layout inside of which I add one column and then another one. Inside these columns I will also add a <b>Panel </b>control. This will come in handy in next steps.<img class="alignnone wp-image-15615" src="https://www.dronahq.com/wp-content/uploads/2019/12/11.5.-layouts.png" alt="Layouts to make your checklist responsive" width="644" height="319" /> &nbsp; Just be sure to configure the panel column configurations like in the image below. You can play around with these configurations to suit your needs.<img class="alignnone wp-image-15628" src="https://www.dronahq.com/wp-content/uploads/2019/12/image10.png" alt="Layout properties" width="643" height="404" /></li> <li style="font-weight: 400;" aria-level="2"><span style="font-weight: 400;">Head back over to Controls and look for the Selection controls and pick the </span><b>SELECT BAR</b><span style="font-weight: 400;"><span style="font-weight: 400;">. After labeling the control, I add the options that need to be shown in the Static Data Section.</span></span><img class="alignnone wp-image-15616" src="https://www.dronahq.com/wp-content/uploads/2019/12/12.-Selection-Control-1024x392.png" alt="12. Selection Control" width="673" height="258" />&nbsp;</li> <li style="font-weight: 400;" aria-level="2"><span style="font-weight: 400;"><span style="font-weight: 400;">If the user selects the “Needs Repair” option. I want to open up an option to attach an image. So, I insert another File Upload Control to upload the image.</span></span><img class="alignnone wp-image-15617" src="https://www.dronahq.com/wp-content/uploads/2019/12/13.-File-Upload-Needs-Repair-1024x365.png" alt="13. File Upload - Needs Repair" width="704" height="251" />&nbsp;</li> <li style="font-weight: 400;" aria-level="2"><span style="font-weight: 400;"><span style="font-weight: 400;">This field need not be shown unless the “Needs Repair” option is selected. So, we will introduce conditional visibility at this step. To add conditional visibility, head over to “Rules” on the left panel and then “Add New Rule”</span></span><span style="font-weight: 400;">Here we can configure the conditions when we want to hide or show the file upload field. Click on save and head out of the Rules widget. </span>Here is how Rules work &gt; <a href="https://community.dronahq.com/t/applying-rules/227" target="_blank" rel="noopener noreferrer">https://community.dronahq.com/t/applying-rules/227</a><img class="alignnone wp-image-15618" src="https://www.dronahq.com/wp-content/uploads/2019/12/14.-Rules.png" alt="14. Rules" width="674" height="426" /></li> <li style="font-weight: 400;" aria-level="2">The rest of the questions in this section have the same format. Question, 4 options to select from, and an image to upload in case the select option ‘needs repair’. To make the process faster, I will copy this control and paste one below the other.  I select the panel that holds the field and duplicate it.<img class="alignnone wp-image-15629" src="https://www.dronahq.com/wp-content/uploads/2019/12/image9.png" alt="duplicate form fields" width="697" height="497" /></li> <li style="font-weight: 400;" aria-level="2">All I have to do on this screen now is change the label (the question) and configure the visibility rules.<img class="alignnone wp-image-15619" src="https://www.dronahq.com/wp-content/uploads/2019/12/15.-Duplicate-and-rename.png" alt="15. Duplicate and rename" width="620" height="488" /></li> <li style="font-weight: 400;" aria-level="2"><b><b><span style="font-weight: 400;">Similarly, I added screens for more sections/stages of the inspection by duplicating the screens and renaming the fields within the screen.</span></b></b><img class="alignnone wp-image-15630" src="https://www.dronahq.com/wp-content/uploads/2019/12/image24-1024x429.png" alt="" width="642" height="269" />&nbsp;</li> <li style="font-weight: 400;" aria-level="2"><strong>Sticky Menu </strong><span style="font-weight: 400;">To assist in easy navigation through the sections, we will add a </span><a href="https://community.dronahq.com/t/using-menus/522" target="_blank" rel="noopener noreferrer"><span style="font-weight: 400;">sticky menu</span></a><span style="font-weight: 400;"> to our checklist. </span><span style="font-weight: 400;"><span style="font-weight: 400;">Just head over to the screens menu and select a menu screen of choice</span></span><img class="alignnone wp-image-15631" src="https://www.dronahq.com/wp-content/uploads/2019/12/image11.png" alt="creating a menu screen" width="655" height="467" />&nbsp; Add the item lists and configure the navigation.</li> <li style="font-weight: 400;" aria-level="2">To ensure menu remains visible across each section, enable sticky menu in each pages screen properties<img class="alignnone wp-image-15633" src="https://www.dronahq.com/wp-content/uploads/2019/12/image13-1024x421.png" alt="menu" width="654" height="269" /></li> <li style="font-weight: 400;" aria-level="2">Here is a quick preview of the road so far :</li> </ol> <img class="alignnone wp-image-15634" src="https://www.dronahq.com/wp-content/uploads/2019/12/image6-1024x572.png" alt="preview of inspection checklist" width="691" height="386" /> <span style="font-weight: 400;">DronaHQ empowers the business user to design checklists and deploy them without having to go to the IT or DevOps. These checklist apps built once can run on Android, iOS, or Web devices </span> Next up, we will cover: <ol> <li style="font-weight: 400;" aria-level="2"><span style="font-weight: 400;">Update Database</span></li> <li style="font-weight: 400;" aria-level="2">Generate Reports</li> <li style="font-weight: 400;" aria-level="2"><span style="font-weight: 400;">Send Alerts - Updates on new Submission, Escalation Warnings</span></li> </ol> &nbsp;
gayatrisachdev1
796,248
Rest vs. GraphQL: A Critical Review
Originally posted on the We Watch Tech website This week at work, an engineer proposed that we...
0
2021-08-18T16:06:09
https://dev.to/amorriscode/rest-vs-graphql-a-critical-review-290b
graphql, rest, api, techtalks
> Originally posted on the [We Watch Tech website](https://wewatch.tech/posts/rest-vs-graphql) This week at [work](https://monthly.com), an engineer proposed that we start putting effort into ensuring our backend endpoints follow RESTful practices. The team was excited by the idea. Our endpoints don't currently follow any spec, RESTful or otherwise. You never know what you're going to get. This proposal reminded me that I've had a talk on my YouTube watchlist for a while. An opinionated, critical view comparing REST and GraphQL. I've enjoyed the GraphQL developer experience in the past. I may be susceptible to [shiny object syndrome](https://en.wikipedia.org/wiki/Shiny_object_syndrome), but there's clear pros to using GraphQL... right? REST and GraphQL aren't actually the same thing. Z points out that REST is an **architectural style** while GraphQL is a **language and framework**. One is more like a suggestion while the other strict and tangible. Both of them help us create a communication layer between our distributed systems. Or, as Z suggests, we'll call them API paradigms for now. ## A World of Constraints One of my favourite parts of Z's talk is when he talks about constraints. When making any technical decision we should be looking at the constraints of our system. It seems obvious but defining your constraints can be quite challenging. They're bound to evolve as your systems do as well. No matter what solutions we decide on, our choice should always a be a function of our constraints. Z gives a great example of someone who builds a colonial home simply because they like colonial houses. Well, those houses were built because of colonial constraints. Just because you can do something doesn't mean you should. ### Constraints Imply Properties Whatever constraints we build _into_ our system, we can derive certain properties. Having a decoupled client and server *implies* two codebases that can evolve separately. Having a stateless server *implies* that your server is reliable and scaleable. Having a stateless server decoupled from our client will ultimately give us a codebase with reliability, scalability, and evolvability built in. ## Properties of Distributed Systems and Ecosystems So, if constraints imply properties, what properties should we care about? This will also depend on your situation. Z does suggest a few properties to consider. ### Distributed System Properties 1. Performance 2. Scalability 3. Simplicity 4. Modifiability 5. Visibility 6. Portability 7. Reliability 8. Discoverability 9. Type-safety 10. Developer experience 11. Cost effectivity ### Distributed Ecosystem Properties 1. Community 2. Tooling 3. Ecosystem maturity 4. Resources 5. Enterprise readiness For any system you're architecting, you'll want to pick the properties you care most about and optimize for those. It's rare that any one solution checks all the boxes. Every team is going to have different types of constraints. From business (customer or product requirements) to cultural (resources or knowledge). They will also be optimizing for different properties. Because of this, there will never be a clear winner for arguments like REST vs. GraphQL. That won't stop us from arguing about it though, will it? Let the battle commence! ## The Weigh In There are two contenders in this fight. REST is old. Tried and true but starting to show its age in the ring. GraphQL has a spring in its step. But sometimes rookies make simple mistakes. This is what Z has to say about the pros and cons for each solution. ### REST **Pros** - Scales indefinitely - Great performance (thanks HTTP2) - Tried and true - Affordance-centric (API is expressed as structured messages) - Server-driven - Decoupled client and server **Cons** - Huge barrier to entry (difficult to master, etc.) - Challenging mindset shift from SOAP to REST - Poor (or no) tooling for clients - No framework or tooling guidance - Requires discipline - Even hard for experts to get it right - Hard to keep consistent - Hard to govern ### GraphQL **Pros** - Easy to start with - Easy to produce and consume - Lots of hand-holding - Contract-driven - Built-in introspection - Easy to keep consistent - Easy to govern - Closer to SOAP **Cons** - Ignores problems of distributed systems - Queries can be suboptimal - Bikeshedding age old solutions (caching, etc.) - DIY scaling and performance - Ignores hard work done by HTTP (`POST` for everything!) - JSON all the things - Lack of ecosystem maturity ## The Clear Winner There isn't one. Both of the options have plenty of pros and cons. Like everything in the world of software, there are many ways to skin an eggplant. If you're looking to make a decision between REST and GraphQL, it might not be an easy one. Start by narrowing down the properties that are most important to you and work your way back. ### Where REST Wins If you're looking to build a system for the long term. REST isn't a new idea. It's been battle tested. There are standards built around important things like authentication, caching, and rate limiting. It has scalability in mind. ### Where GraphQL Wins The communication between your frontend and backend are simple. Or if you want a data-driven approach to the API paradigm. Also, the developer experience is pretty darn enjoyable. ## So-Called REST All of the information covered this far is useful, but it wasn't the most mind blowing for me. You probably don't have to search to hard to see a lot of this covered elsewhere on the interwebs. One of the cons Z listed for REST piqued my curiosity. It was the fact that there is a huge barrier to entry. I've seen "RESTful practices" used a lot in my career so far. I thought I *knew* REST. It turns out, I've seen more *so-called* REST than anything else. Here's a quote written in 2008 by [Roy Fielding](https://roy.gbiv.com/untangled/2008/rest-apis-must-be-hypertext-driven)(he created REST by the way): > What needs to be done to make the REST architectural style clear on the notion that hypertext is a constraint? In other words, if the engine of application state (and hence the API) is not being driven by hypertext, then it cannot be RESTful and cannot be a REST API. Period. Is there some broken manual somewhere that needs to be fixed? I've never actually seen a REST API that reached [level three on the Richardson Maturity Model](https://restfulapi.net/richardson-maturity-model/#level-three). One that has true discoverability and uses [hypermedia as the engine of application state](https://restfulapi.net/hateoas/). But does that matter? Z argues that GraphQL is far better than a so-called REST API. The proposal at work this week was for a *so-called* REST API and I'm not mad about it. We're optimizing for properties like simplicity, portability, discoverability, and developer experience. In our current system, those properties are sadly lacking. There's a lot of tooling out there that makes REST more accessible these days too. From the [OpenAPI specification](https://swagger.io/specification/) to things like [Flaks RESTful](https://flask-restful.readthedocs.io/en/latest/). Even with that in mind, I can't help but think about GraphQL. Can we optimize for the properties listed about while solving other problems clients face like slow and spotty internet? ## Microservices When mentioning microservices, I was surprised to hear Z recommend REST. He says it is almost as if they were born to be used together. What about [gRPC](https://grpc.io/)? Or an [event-driven architecture](https://en.wikipedia.org/wiki/Event-driven_architecture)? I think there's more to the story here. ## No Contest This talk hasn't made me more confident in my ability to implement a RESTful API. It hasn't shown me that either option is the obvious solution for my API communication woes. We will forever have to decide between many options to solve our problems. Framing these decisions based on the constraints and desired properties of our systems will always lead to better results. Even though there's no clear winner to this fight, there are a ton of great resources about REST, GraphQL, and APIs. Here are a few worth looking at: - [REST API Tutorial](https://restfulapi.net/) - [Introduction to GraphQL](https://graphql.org/learn/) - [GraphQL vs. REST from Apollo GraphQL](https://www.apollographql.com/blog/graphql/basics/graphql-vs-rest/) - [The so-called 'RESTful' web in 2018 and beyond](https://www.philosophicalhacker.com/post/rest-in-2018) - [GitHub's GraphQL documentation](https://docs.github.com/en/graphql) - [adidas' API Guidelines*](https://adidas.gitbook.io/api-guidelines) - [Z's own writeup about his talk](https://medium.com/good-api/rest-vs-graphql-a-critical-review-5f77392658e7) <div class="text-sm">*I never thought I'd be reading API guidelines from a shoe/fashion company. It turns out <a href="https://github.com/adidas" target="_blank" rel=”noreferrer noopener”>they have a decent amount of open source projects</a>!</div>
amorriscode
796,282
Study Guide: ReactJS + Redux
💿Here is a study guide I curated for ReactJS + Redux beginners, people who need a refresh, or anyone...
0
2021-08-18T17:31:54
https://dev.to/am20dipi/study-guide-reactjs-redux-2a2g
react, javascript, redux
:cd:Here is a study guide I curated for ReactJS + Redux beginners, people who need a refresh, or anyone just looking to learn something new!:cloud: I've broken it down into a few subtopics: * [INTRODUCTION TO REACT / GENERAL](#INTRODUCTION-GENERAL) * [COMPONENTS](#COMPONENTS) * [STATE + PROPS](#STATE-PROPS) * [ROUTING](#ROUTING) * [EVENTS](#EVENTS) * [LIFECYCLE HOOKS + LIFECYCLE METHODS](#LIFECYCLE) * [REDUX](#REDUX) * [JWT AUTHENTICATION](#JWT) ### INTRODUCTION TO REACT / GENERAL <a name="INTRODUCTION-GENERAL"></a> 1. What is React? 2. What are React's core features? 3. How is React code written? 4. What is JSX? 5. What is the Virtual DOM? 6. What is memoization? Give an example. 7. What is client-side routing? 8. What is object destructuring? Give an example. 9. What does "referentially transparent" mean? 10. What does "reconciliation" mean? 11. What is the difference between a framework and a library? 12. What is ReactDOM? 13. What does ReactDOM.render() do? 14. What is Babel? 15. What is transpiling? What is compiling? 16. What is Node Package Manager? What does it do? 17. What is Webpack? What does it do? 18. What does "unidirectional data flow" mean? 19. What is the purpose of keys? ### COMPONENTS <a name="COMPONENTS"></a> 1. What are the key features of Class components? 2. What are the key features of Functional components? 3. What is a "controlled" component? What is an "uncontrolled" component? 4. What is a "pure" component? 5. Is there a difference between class and functional components? (Think state, functionality, syntax) 6. What is the React.Component class? What is its purpose? ### STATE + PROPS <a name="STATE-PROPS"></a> 1. Describe state. 2. Describe props. 3. What are the ways we can update state? 4. What is the difference between React state and Redux State? 5. What is a "controlled" form? ### ROUTING <a name="ROUTING"></a> 1. What is React-Router? What does it do? 2. What are routeProps? 3. How does React handle nested routes? 4. How does React handle routing in general? 5. What does the Switch component do? ### EVENTS <a name="EVENTS"></a> 1. How does React handle events? Give an example. 2. What is a "synthetic" event? 3. What is a "native" event? 4. What is the purpose of "e.preventDefault()"? ### LIFECYCLE HOOKS + LIFECYCLE METHODS <a name="LIFECYCLE"></a> 1. What is a Lifecycle Hook? Name + describe some examples. 2. What is a Lifecycle Method? Name + describe some examples. 3. What is mounting? What is unmounting? 4. Is there ultimately a difference between Lifecycle Hooks and Lifecycle Methods? ### REDUX <a name="REDUX"></a> 1. What is Redux? Name some core features. 2. What is the Redux "store"? 3. What is an action? How do actions work? What do they return? 4. What is a reducer? How do reducers work? What do they return? 5. How does React and Redux communicate? 6. What is an action creator? 7. What is dispatching? 8. How does the store get updated? 9. What is mapPropsToState()? 10. What is mapDispatchToState()? 11. What is connect()? 12. Using Redux, when do components get rerendered? 13. What is Thunk? 14. What does "Provider" do? ### JWT AUTHENTICATION <a name="JWT"></a> 1. What is JWT? 2. What is the JWT structure? 3. Describe the JWT header. 4. Describe the JWT payload. 5. Describe the JWT signature. 6. How does JWT work? What is the flow? 7. What is a token? :cd:Thank you for reading along!:cd: :cloud:Comment below for any suggestions!:cloud:
am20dipi
796,290
Is it time to let go of Bootstrap?
Hello again!, After a short break, I am back again with a non-technical post. As Web-Dev's, we use...
0
2021-08-18T18:29:31
https://dev.to/codereaper08/is-it-time-to-let-go-of-bootstrap-347i
webdev, css, todayisearched, html
Hello again!, After a short break, I am back again with a non-technical post. As Web-Dev's, we use and search all possible ways, to get our job done in the easy way. The most vital visual part of Web-Dev, the **FRONT-END**, is very important to catch the eyes and to give a nice user-friendly experience for the user. To make this job easy, we use CSS frameworks like Bootstrap. So, after these many good years with many technical competitors, is Bootstrap still good to hang on with? Let's see about this in today's blog. So, we'll start with ## What is Bootstrap? Bootstrap is a CSS framework (Most popular), which uses class based Web-design. The official site of Bootstrap describes itself as, **“Quickly design and customize responsive mobile-first sites with Bootstrap, the world’s most popular front-end open source toolkit, featuring Sass variables and mixins, responsive grid system, extensive prebuilt components, and powerful JavaScript plugins.”** And that's completely true, Bootstrap is fast and provide responsive mobile-first build classes to achieve what we Web-Dev's dream of as “RESPONSIVE DESIGN”. It provides an awesome grid system(Which I love) and JavaScript plugins(I hate them using jQuery, we'll get into it). ## Competitors ![CSS frameworks](https://www.tekkiwebsolutions.com/wp-content/uploads/Top-CSS-Frameworks.jpg) <figcaption>Image source: www.tekkiwebsolutions.com</figcaption> Bootstrap now faces a reasonable competition from similar UI kit based CSS frameworks like **_Foundation_** and **_Bulma_**. Apart from these, It also faces a severe blow from **_TailwindCSS_**. Bootstrap is always criticized for its inflexibility. I would say, it's not inflexibility, but the huge amount of time taken for customizing the defaults provided by Bootstrap(It provides default UI components, because it's a UI Kit based CSS framework). Whereas in frameworks like **_TailwindCSS_**, Utility classes, which provide low-level flexibility, are provided. ## Should Bootstrap worry about competition? I would say Bootstrap was not made to work like **TailwindCSS**. Bootstrap was made to provide developers of all levels, from beginners to advanced, the ability to quickly spin up a nice looking UI without worrying about responsiveness. Bootstrap's users are mostly beginners, who start their journey of using class based CSS utilities from pure CSS. It also has a good learning curve, so people get it better soon, as frameworks like **TailwindCSS**, **Foundation** and **Bulma** comparatively has a steeper learning curve. ## Should we use Bootstrap still in 2021? Of course, It is best in class for rapid web-deign, where you want a useful and nice looking site, without any brand colour pallets or pixel specific needs. Even today, more than 19% of websites use **Bootstrap** as their CSS framework. I would say, it's the most probable gateway for learners, who get into class based CSS frameworks from pure CSS and HTML. If you want a quick site for a Boot camp you arrange next week, go for Bootstrap, It's faster to build, gives responsiveness. ## Bootstrap is gearing back again! ![Bootstrap 5](https://getbootstrap.com/docs/5.0/assets/brand/bootstrap-social.png) <figcaption>Image source: getbootstrap.com</figcaption> As you all know, Bootstrap 5 came with a nice update from 4. It let go of jQuery and switched to Vanilla JavaScript. So, now how good is that! Bootstrap also managed to bring back the Bootstrap icon support. It also came up with some low level utility classes for added flexibility. Overall, Bootstrap is not going to be dead, but getting back on track. Thanks for Reading and following me! If you didn't, make sure to follow me, so we can learn and discuss tech-stuff. ### Attributions: cover-image : www.drupal.org
codereaper08
796,295
Beginner's guide to State Management using NGXS
NGXS is a state management pattern + library for Angular. It acts as a single source of truth for...
0
2021-08-19T12:48:34
https://dev.to/siddheshthipse/beginner-s-guide-of-state-management-using-ngxs-35dn
angular, beginners, redux, webdev
>NGXS is a state management pattern + library for Angular. >It acts as a single source of truth for your application's state, providing simple rules for predictable state mutations. >NGXS is modeled after the CQRS pattern popularly implemented in libraries like Redux and NgRx but reduces boilerplate by using modern TypeScript features such as classes and decorators. Getting started with NGXS as a beginner can be daunting, not because it is some kind of rocket science but essentially due to the fact that not many resources are available to learn it in a right way. ![Block Schematic of NGXS](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/jg9lyhjajpvpk5pem3tb.png) In this tutorial, we will use Angular along with NGXS to create a simple CRUD application consuming dummy REST APIs. If you're running out of patience already you can hop onto [StackBlitz](https://stackblitz.com/github/siddheshthipse/learning-ngxs) and see for yourself what we're gonna do. #### Prerequisites * Basic knowledge of Angular 2+ is must. * Prior knowledge of RxJS would be helpful but isn't absolutely necessary. ### So let's get started #### Step 1: Install Angular CLI `npm install -g @angular/cli` OR `yarn add global @angular/cli` Create a new Angular project, let's call it 'learning-ngxs' `ng new learning-ngxs` ####Step 2: Install NGXS library First go to the project folder `cd learning-ngxs` Then enter this command `npm install @ngxs/store --save` or if you're using yarn `yarn add @ngxs/store` ####Step 3: Installing Plugins(optional) * Although this step is optional, I would highly recommend you to go through it since Logger and Devtools are the two extremely handy dev dependencies. * These plugins help us in tracking the changes our state goes through. For installing Logger and Devtools plugins fire the commands `@ngxs/logger-plugin --save` & `@ngxs/devtools-plugin --save-dev` respectively. ####Step 4: Importing Modules This is how your `app.module.ts` file will look after importing the necessary modules ``` import { NgModule } from '@angular/core'; import { BrowserModule } from '@angular/platform-browser'; import {HttpClientModule} from '@angular/common/http'; import {FormsModule,ReactiveFormsModule} from '@angular/forms'; //For NGXS import { NgxsModule } from '@ngxs/store'; import { NgxsLoggerPluginModule } from '@ngxs/logger-plugin'; import { NgxsReduxDevtoolsPluginModule } from '@ngxs/devtools-plugin'; import { AppRoutingModule } from './app-routing.module'; import { AppComponent } from './app.component'; import { GeneralComponent } from './general/general.component'; import { AppState } from './states/app.state'; import { DesignutilityService } from './designutility.service'; @NgModule({ declarations: [ AppComponent, GeneralComponent ], imports: [ BrowserModule, AppRoutingModule, HttpClientModule, FormsModule, ReactiveFormsModule, NgxsModule.forRoot([]), NgxsLoggerPluginModule.forRoot(), NgxsReduxDevtoolsPluginModule.forRoot() ], providers: [], bootstrap: [AppComponent] }) export class AppModule { } ``` #### Step 5: Creating Components and Services Let's create a component say 'general' for displaying the contents of our state `ng g c general` Create a service called 'designutility' for interacting with the server to `GET`, `POST`, `UPDATE` and `DELETE` the data. `ng g s designutility` Do not forget to add `DesignutilityService` inside the `providers` array in `app.module.ts`. ``` providers: [DesignutilityService] ``` Make sure that you've imported all the modules mentioned in Step 4. #### Step 6: Creating Actions Create a new folder named 'actions' inside src>app Inside the actions folder, create a new file named `app.action.ts` ``` //Here we define four actions for CRUD operations respectively //Read export class GetUsers { static readonly type = '[Users] Fetch'; } //Create export class AddUsers { static readonly type = '[Users] Add'; constructor(public payload: any) { } } //Update export class UpdateUsers { static readonly type = '[Users] Update'; constructor(public payload: any, public id: number, public i:number) { } } //Delete export class DeleteUsers { static readonly type = '[Users] Delete'; constructor(public id: number) { } } ``` >Actions can either be thought of as a command which should trigger something to happen, or as the resulting event of something that has already happened. >Each action contains a type field which is its unique identifier. Actions are dispatched from the components to make the desirable changes to the State. You might have noticed that except for `GetUsers`, in all other actions we have a parameterized constructor. * These parameters are nothing but the data which would be coming from various components whenever the action is dispatched. * For example in `AddUsers` action we have a constructor with parameter named `payload`, this payload will basically comprise of information about the new user. * This data about the newly created user will get stored inside the State whenever the action `AddUsers` is dispatched from the component. #### Step 7: Working with Service In the `designutility.service.ts`, let’s add HTTP calls to fetch, update, add and delete to-do items. In this tutorial, we are using JSONPlaceholder for making fake API calls. ``` import { Injectable } from '@angular/core'; import {HttpClient} from '@angular/common/http'; @Injectable({ providedIn: 'root' }) export class DesignutilityService { constructor(private http:HttpClient) { } fetchUsers(){ return this.http.get('https://jsonplaceholder.typicode.com/users'); } addUsers(userData){ return this.http.post('https://jsonplaceholder.typicode.com/users',userData); } deleteUser(id:number){ return this.http.delete('https://jsonplaceholder.typicode.com/users/'+id); } updateUser(payload,id:number){ return this.http.put('https://jsonplaceholder.typicode.com/users/'+id, payload); } } ``` #### Step 8: Creating State Now we've arrived at the most important part of this tutorial. Create a new folder named 'states' inside src>app. Inside the states folder, create a new file named `app.state.ts` ``` import { Injectable } from "@angular/core"; import { Action, Selector, State, StateContext } from "@ngxs/store"; import { DesignutilityService } from "../designutility.service"; import { tap } from 'rxjs/operators'; import { AddUsers, DeleteUsers, GetUsers, UpdateUsers } from "../actions/app.action"; export class UserStateModel { users: any } @State<UserStateModel>({ name: 'appstate', defaults: { users: [] } }) @Injectable() export class AppState { constructor(private _du: DesignutilityService) { } @Selector() static selectStateData(state:UserStateModel){ return state.users; } @Action(GetUsers) getDataFromState(ctx: StateContext<UserStateModel>) { return this._du.fetchUsers().pipe(tap(returnData => { const state = ctx.getState(); ctx.setState({ ...state, users: returnData //here the data coming from the API will get assigned to the users variable inside the appstate }) })) } @Action(AddUsers) addDataToState(ctx: StateContext<UserStateModel>, { payload }: AddUsers) { return this._du.addUsers(payload).pipe(tap(returnData => { const state=ctx.getState(); ctx.patchState({ users:[...state.users,returnData] }) })) } @Action(UpdateUsers) updateDataOfState(ctx: StateContext<UserStateModel>, { payload, id, i }: UpdateUsers) { return this._du.updateUser(payload, i).pipe(tap(returnData => { const state=ctx.getState(); const userList = [...state.users]; userList[i]=payload; ctx.setState({ ...state, users: userList, }); })) } @Action(DeleteUsers) deleteDataFromState(ctx: StateContext<UserStateModel>, { id }: DeleteUsers) { return this._du.deleteUser(id).pipe(tap(returnData => { const state=ctx.getState(); console.log("The is is",id) //Here we will create a new Array called filteredArray which won't contain the given id and set it equal to state.todo const filteredArray=state.users.filter(contents=>contents.id!==id); ctx.setState({ ...state, users:filteredArray }) })) } } ``` ##### About Selector() * The `Selector()` is used to get a specific piece of data from the `AppState`. * In our case we are grabbing the `users` array which is present inside the `AppState` * The selector is used to return the data back to the component with the help of `Select()` as shown in Step 10. #### Step 9: Documenting the State in app.module.ts Now that we are done with the creation of `AppState`, it is necessary to document this state in our `app.module.ts` file. So go to imports array inside `app.module.ts` and make the necessary change. ``` NgxsModule.forRoot([AppState]), NgxsLoggerPluginModule.forRoot(), NgxsReduxDevtoolsPluginModule.forRoot() ``` #### Step 10: Working with Component Component is the place from where we're gonna control the contents of the state, in our case it's `general.component.ts` We are performing basic CRUD operations on our `AppState`. For that, we have a table to display existing users, update user information, remove user and a form to insert a new user into the `AppState`. ``` import { Component, OnInit } from '@angular/core'; import { FormGroup, FormBuilder } from '@angular/forms'; import { Select, Store } from '@ngxs/store'; import { Observable } from 'rxjs'; import { AddUsers, DeleteUsers, GetUsers, UpdateUsers } from '../actions/app.action'; import { AppState } from '../states/app.state'; @Component({ selector: 'app-general', templateUrl: './general.component.html', styleUrls: ['./general.component.css'] }) export class GeneralComponent implements OnInit { //Here I have used Reactive Form, you can also use Template Driven Form instead userForm: FormGroup; userInfo: []; @Select(AppState.selectStateData) userInfo$: Observable<any>; constructor(private store: Store, private fb: FormBuilder) { } ngOnInit(): void { this.userForm = this.fb.group({ id: [''], name: [''], username: [''], email: [''], phone: [''], website: [''] }) this.store.dispatch(new GetUsers()); this.userInfo$.subscribe((returnData) => { this.userInfo = returnData; }) } addUser() { this.store.dispatch(new AddUsers(this.userForm.value)); this.userForm.reset(); } updateUser(id, i) { const newData = { id: id, name: "Siddhesh Thipse", username: "iamsid2399", email: 'siddheshthipse09@gmail.com', phone: '02138-280044', website: 'samplewebsite.com' } this.store.dispatch(new UpdateUsers(newData, id, i)); } deleteUser(i) { this.store.dispatch(new DeleteUsers(i)); } } ``` ##### Few Important Points * Import `select` and `store` from `ngxs/store` * The `Select()` is basically used to grab the data present in the `AppState`. * Notice how we are dispatching various actions to perform the desired operations, for example if we want to delete a user, we are dispatching an action named `DeleteUsers` and passing `i` (userid) as a parameter. * So that the user having userid equal to `i` will get deleted from the `AppState`. For designing part I have used Bootstrap 5, but you can totally skip using it if UI isn't your concern as of now. After creating the basic UI, this is how our `general.component.html` will look like ``` <div class="container-fluid"> <h2 style="text-decoration: underline;">Getting started with NGXS</h2> <div class="row my-4"> <div class="col-md-3"> <h5 style="color: grey;">Add new user to State</h5> <form [formGroup]="userForm" (ngSubmit)="addUser()"> <label class="form-label">ID</label> <input type="text" class="form-control mb-2" placeholder="User ID" formControlName="id"> <label class="form-label">Name</label> <input type="text" class="form-control mb-2" placeholder="Enter Name" formControlName="name"> <label class="form-label">Username</label> <input type="text" class="form-control mb-2" placeholder="Enter a unique username" formControlName="username"> <label class="form-label">Email</label> <input type="email" class="form-control mb-2" placeholder="example@abcd.com" formControlName="email"> <label class="form-label">Phone</label> <input type="number" class="form-control mb-2" placeholder="Enter Contact No." formControlName="phone"> <label class="form-label">Website</label> <input type="email" class="form-control mb-2" placeholder="Enter website name" formControlName="website"> <button type="submit" class="btn btn-primary btn-sm mt-2">Add User</button> </form> </div> <div class="col-md-9"> <h5 style="color: grey;">User Information</h5> <table class="table"> <thead> <tr> <th scope="col">ID</th> <th scope="col">Name</th> <th scope="col">Username</th> <th scope="col">Email</th> <th scope="col">Phone</th> <th scope="col">Website</th> <th scope="col">Update</th> <th scope="col">Delete</th> </tr> </thead> <tbody> <tr *ngFor="let contents of userInfo; index as i"> <th scope="row">{{contents.id}}</th> <td>{{contents.name}}</td> <td>{{contents.username}}</td> <td>{{contents.email}}</td> <td>{{contents.phone}}</td> <td>{{contents.website}}</td> <td><button class="btn btn-outline-warning btn-sm" (click)="updateUser(contents.id,i)"><i class="bi bi-pencil-fill"></i></button></td> <td><button class="btn btn-danger btn-sm" (click)="deleteUser(contents.id)"><i class="bi bi-trash-fill"></i></button></td> </tr> </tbody> </table> </div> </div> </div> ``` ![Landing Page UI](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/gmol3081o9g5cryy6hm1.png) That's it, we have successfully implemented State Management in our Angular Application. Now there is definitely more to NGXS than this, but once you've completely understood the basics, learning the advanced stuff is a cakewalk. Incase of any suggestions/queries please feel free to comment down below. Source code available on [Github](https://github.com/siddheshthipse/learning-ngxs)
siddheshthipse
796,519
CI/CD Pipelines with Kubernetes: Build, migrate and integrate Security seamlessly
In the cloud world, containers are the center point of a growing majority of deployments. By...
0
2021-08-18T20:26:57
https://dev.to/opsera/ci-cd-pipelines-with-kubernetes-build-migrate-and-integrate-security-seamlessly-eh3
devops, kubernetes, security
In the cloud world, containers are the center point of a growing majority of deployments. By providing compartmentalization of workloads and the ability to run “serverless”, containers can speed up and secure deployments and create flexibility unreachable by old style application servers. While a variety of tools have been developed to meet this need, none are as impactful to the industry as Kubernetes. It has emerged as the de facto container orchestration tool for many companies. > Kubernetes alone is a powerful framework, but relies entirely on proper configurations to achieve the desired results. Kubernetes facilitates the ability to automate the DevOps CI/CD pipeline but alone can be unwieldy. In this article, you will learn how to build, migrate to and integrate security in a fully-managed Infrastructure-as-Code CI/CD (Continuous Integration and Continuous deployment) pipelines for container-based applications - with low-code automation. ##From Dependency Hell to Containers## ![From Dependency Hell to Containers](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/2y2ec1mwdkauzz569qw6.jpg) By eliminating the “dependency hell” problem containers solved one of the most fundamental issues plaguing the software industry. They allow developers to keep their applications abstract from underlying environments, increasing agility and robustness. Containers achieve several key performance metrics critical in modern software development, including consistent and predictable environments, ability to function virtually from anywhere, providing logically isolated view of the OS to developers and easy replication. Because of their lightweight nature, containers can be shipped as deployable units from different environments, complete with their libraries and configuration. ##The Problem with Containers## But containers need to be managed properly. You could have thousands of containers in an environment, with open ports, different addresses and a host of applications. What if a container fails while in production? How would the system switch to other containers? With containers the industry felt the need for a container orchestration tool, which could allocate resources, provide abstracted functionality like internal networking and file storage, and monitor health of these systems. > This is the key problem solved by Kubernetes. ##Kubernetes to the Rescue## ![Kubernetes to the Rescue](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/2xn4w1cuzidypzyk7x05.jpg) Kubernetes is a platform for containerized workloads and services offering both declarative configuration and automation. Kubernetes makes it possible to fully exploit the true powers of containers and achieve the primary goals of Continuous Integration, Delivery, and Deployment (CI/CD). Let’s see how Kubernetes makes all of this possible and where does it fit in the broader DevOps and CI/CD ecosystem. ####Deployment#### Kubernetes uses clusters for automatic deployment of containerized microservice applications. You can use triggers in Kubernetes Deployment engine to automate anything. Ample integrations with CI/CD tools like Buildbot, Argo, Flux, Pulumi are available. ####The Power of Configurations#### You can define your own deployments and Kubernetes enforces your requirements based on defined states. You can define various aspects of your infrastructure deployment in Kubernetes including deployment objects (pods). You can easily create, update and delete Kubernetes objects by storing multiple object configuration files in a directory and recursively creating and updating these objects as needed. Kubernetes also allows you to store and manage passwords, OAuth tokens, and SSH keys and deploy application configuration without rebuilding your container images. ####Immutability#### Because of its declarative nature and image immutability, Kubernetes offers a diverse range of mechanisms to maintain the system’s state based on your desired outcomes. You can define Deployments to create new Replica Sets, and remove existing deployments to adapt to the new resources and deployments. Kubernetes can also automatically trigger roll backs in case of errors. ####Scalability#### Kubernetes uses configurations to achieve scaling and on-demand adaption. It can create and destroy containers as and when needed. Its ReplicationController can kill, create and supervise pods based on your requirements. On-demand infrastructure handling is implemented via container scheduling and auto-scaling, automatic health checks, replication, service naming, discovery and load balancing. ####Zero Downtime and Optimized Performance#### Kubernetes achieves zero downtime even in frequent deployment situations by incrementally updating Pods instances with new ones. Kubernetes creates and destroys containers based on system requirements. It also rolls backs to previous working state in cases of failure. Kubernetes’ Pod Eviction lifecycle for gracefully shutting down clusters and creating new ones is also extremely useful in complex systems. ##Kubernetes: Difficulties in Migration and Adoption## ![Kubernetes: Difficulties in Migration and Adoption](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/y2d2yqo8bytvxluk1vti.jpg) You are ready to use the magical powers of containerized software development and want to use Kubernetes for your company. But how to get started? How and where to deploy Kubernetes? Would containerized development be suitable for your company? Several government and private entities do not support containerized software applications amid security policies. Deciding between directly deploying Kubernetes for your cloud environment or choosing a Platform as a Service (PaaS) approach is also extremely important for your future needs and business feasibility. ####Faulty Migration Can Break Your System and Future Scalability#### Migrating from VMs to containers could be disastrous if you don’t take into account platform dependencies, system-level issues and server-side dynamics. For example, if you package more than one service inside a container during refactoring, you could end up losing your ability to scale, automate and expand your features. ####Data Implementation and Storage#### Remapping your data storage techniques to container-based data systems will also be critical. Refactoring or rewriting your application for containerization involves completely rewiring your architecture. ####Security Challenges#### Implementing Kubernetes comes with a variety of security challenges that can compromise your entire application if not handled carefully. According to the State of Kubernetes and Container Security report, a whopping 94% companies said they ran into problems while implementing Kubernetes, including misconfiguration, runtime threats or vulnerabilities. Some security issues while migrating to containerized environments include using insecure base or parent images, running misconfigured services, outdated processes and using faulty namespaces. Overall, if you rely on Kubernetes alone for container orchestration, things could become extremely complex and difficult because of hard configurations, technical requirements and manual processes. ##Opsera Continuous Orchestration for a Clean and Seamless Migration to Kubernetes## ![Opsera Continuous Orchestration for a Clean and Seamless Migration to Kubernetes](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/ak53nmrxho8swjco8dlj.jpg) This is the problem solved by Opsera Continuous Orchestration, which helps you take full advantage of Kubernetes to develop fully managed Infrastructure-as-Code CI/CD (Continuous Integration and Continuous deployment) pipelines for container-based applications. ####No-Code Pipelines#### One of the biggest strengths of Opsera’s Continuous Orchestration capabilities is no-code pipelines. For example, in Kubernetes, if you want to implement automation at any level, you’d need to work on long configurations, quality checks, write manual load balancers and create various triggers and rollbacks. With Opsera, you can get rid of all manual configuration processes. You just define your clusters, nodes, pods, and use continuous orchestration and Terraform templates for security checks and scans. Your team won’t need to write long code pieces. They can use Opsera continuous orchestration framework for validation, thresholds, gates, approvals and adding additional steps in the workflow without writing custom code. To get a holistic image of your system activity throughout the CI/CD pipeline, Opsera offers Unified Insights, which shows complete activity logs and monitoring data as a “single pane of glass” console (including console logs). ####Migration from VM to Docker Made Easy with Opsera#### With Opsera you don’t have to dread the much-needed migration from VM to containers. Opsera Continuous Orchestration makes is super easy for you to convert the existing VM images into Docker images and deploy them into the Kubernetes cluster. ####YOU JUST HAVE TO:#### * Connect the existing VM code base to a Continuous Integration (CI) system. * Create a Docker image as part of the build process. * Place the container in the repository management system (Artifactory, ECR, Nexus, etc.). * Scan the image using native K8 security scans and upon validation, deploy the container with the respective microservices code into the K8 cluster. * Upon validation, promote the Docker image from QA to production. ‍ ####Security and Quality built into pipelines#### Opsera also ensures quality, security and integrity of your product throughout the development and deployment cycle. Your team can use simple drag-and-drop tools of Opsera to build the pipelines and workflows for code commit, software builds, security scans, vault integration, approvals, notifications, thresholds and gates, quality testing integrations, validation, integration with change control and monitoring. > To minimize user intervention and leaks, use Opsera to implement security and quality thresholds and gates in the pipelines. These pipelines could be built without any complex coding skills.
opsera_staff
796,550
Como corrigir erro de execução do Nodemon - Node.js
Recentemente, adentrei no mundo do Back-end e optei por fazê-lo com Node.js. Entre meus estudos, me...
0
2021-08-18T21:43:38
https://dev.to/mdar4/como-corrigir-erro-de-execucao-do-nodemon-node-js-3015
help, node, javascript, nodemon
Recentemente, adentrei no mundo do Back-end e optei por fazê-lo com Node.js. Entre meus estudos, me deparei com o Nodemon, que é um módulo utilizado para monitorar todas as alterações nos arquivos de sua aplicação e reiniciar automaticamente o servidor quando for necessário. Facilitando muito a vida do desenvolvedor, pois não será necessário rodar a aplicação a cada alteração. Porém, muitos como eu podem se deparar com este erro de execução: <code>O termo 'nodemon' não é reconhecido como nome de cmdlet, função, arquivo de script ou programa operável. Verifique a grafia do nome ou, se um caminho tiver sido incluído, veja se o caminho está correto e tente novamente.</code> Que pode facilmente ser resolvido com o seguinte comando: <code>npm install nodemon -g</code> Porém, se o erro persistir, o problema pode estar nas permissões do servidor para executar o script que deve estar desabilitada. Portanto siga os seguintes passos: 1° - Execute o cmd do PowerShell como administrador; 2° - Execute os comandos: <code> Get-ExecutionPolicy</code> E veja o que ele retorna; 3° - Caso o retorno seja <code>Restricted</code>, dê o comando: <code>Set-ExecutionPolicy RemoteSigned</code> e escolha a opção <code>yes</code> apertando a letra <code>y</code> e após um <code>enter</code>; Agora no terminal <code>VS CODE</code>, dentro da pasta em que estão os arquivos a serem rodados, execute os comandos: 1° - <code>npm install nodemon -g</code> 2° - <code>npm install nodemon --save-dev</code> Caso ainda não funcione, você ainda pode utilizar o método forçado, que é feito pelo JSON da aplicação. No arquivo <code>package.json</code> ```json "scripts": { "dev": "nodemon", "start": "node index.js", "test": "echo "Error: no test specified" && exit 1" }, ``` Se fizer uso deste método, lembre-se de quando for rodar o arquivo, você apenas deve dar o comando <code>npm start</code>. Dê um <code>save</code> com <code>CTRL+ S</code> e reinicie o terminal. <a href="https://answers.microsoft.com/pt-br/windows/forum/all/iniciar-o-powershell-no-windows-10-pelas-teclas-de/2482445c-6266-4876-bc7a-d8e19e563cf3" target=_blank>Veja os 5 possíveis métodos aqui.</a> Espero ter ajudado e até a próxima !
mdar4
796,673
VsCode React Clone
Hello, I created the visual studio code using only React, I would like to know your opinion, if it...
0
2021-08-19T00:31:35
https://dev.to/rafazeon/vscode-react-clone-5d2n
Hello, I created the visual studio code using only React, I would like to know your opinion, if it looks good, if you want it to go up on github, thank you. link: https://optimistic-wright-846bee.netlify.app/
rafazeon
796,677
What's the Best Mesh Router for 2021?
I have a Google Home mesh router that I've had for a few years and it's been working well, but I'm...
0
2021-08-19T00:58:21
https://dev.to/nickytonline/what-s-the-best-mesh-router-for-2021-3i1k
discuss, routers, hardware
I have a Google Home mesh router that I've had for a few years and it's been working well, but I'm looking to upgrade to something faster and probably add a fourth node. Yes I've Googled and found some, but curious what folks here think. What mesh router would you recommend in 2021? Photo by <a href="https://unsplash.com/@rgaleria?utm_source=unsplash&utm_medium=referral&utm_content=creditCopyText">Ricardo Gomez Angel</a> on <a href="https://unsplash.com/s/photos/mesh-router?utm_source=unsplash&utm_medium=referral&utm_content=creditCopyText">Unsplash</a>
nickytonline
796,688
[pt-br] keycloak: Resolvendo problema de 'WFLYCTL0348: Timeout after [300] seconds waiting for service container stability.'
Introdução Olá pessoal! Hoje meu post será sobre um problema que passei, no meu trabalho,...
0
2021-08-19T01:46:42
https://dev.to/andremoriya/keycloak-resolvendo-problema-de-wflyctl0348-timeout-after-300-seconds-waiting-for-service-container-stability-41bo
keycloak, docker, wflyctl0348, timeout
## Introdução Olá pessoal! Hoje meu post será sobre um problema que passei, no meu trabalho, subindo um container do keycloak e se conectando a base de dados do SQL Server na GCP Cloud SQL. Abaixo irei apresentar a solução que encontrei para o erro: **WFLYCTL0348: Timeout after [300] seconds waiting for service container stability.** ## O aconteceu? No trabalho estava testando o keycloak com o MS SQL Server. Rodando os containers localmente, do keycloak e do banco foi tudo tranquilo. Porém ao fazer o teste apontando o keycloak para o banco na GCP Cloud SQL, me deparei com o erro e o container parou de funcionar. Olhando para a base de dados, algumas tabelas foram criadas mas não todas. ## Mas por que disso? Isso acontece pois o keycloak, por padrão, vem configurado um timeout de 300 segundos e o liquibase nesse tempo não terminou ainda a migração. Para essa configuração há 3 variáveis na jogada: > *jboss.as.management.blocking.timeout* > *deployment-timeout* > *default-timeout* ## O que foi feito? Para resolver o problema foi necessário criar um arquivo para alterar esses timeout's, um Dockerfile para criar uma imagem customizada e o docker-compose para criar o container ### Arquivo para alterar os timeout's O nome do meu arquivo foi *changeTimeout.batch*, mas você pode escolher um nome melhor (rsrs). O conteúdo do arquivo ficou parecido com isso: ``` embed-server --std-out=echo --server-config=standalone-ha.xml batch /system-property=jboss.as.management.blocking.timeout:add(value=900) /subsystem=deployment-scanner/scanner=default:write-attribute(name=deployment-timeout,value=900) /subsystem=transactions:write-attribute(name=default-timeout,value=900) run-batch stop-embedded-server ``` Esse arquivo faz com que as 3 variáveis citados acima, seja alteradas para 900 segundos ou 15 minutos, mas você pode colocar o tempo que quiser, desde que seja em segundos. ### Dockerfile O Dockerfile ficou assim: ``` FROM quay.io/keycloak/keycloak:10.0.2 COPY --chown=jboss ./changeTimeout.batch /tmp/changeTimeout.batch RUN cd $JBOSS_HOME \ && ./bin/jboss-cli.sh --file=/tmp/changeTimeout.batch \ && rm -rf $JBOSS_HOME/standalone/configuration/standalone_xml_history \ && rm -rf $JBOSS_HOME/standalone/data \ && rm -rf $JBOSS_HOME/standalone/tmp \ && rm -rf /tmp/changeTimeout.batch # Optional parameters ENV KEYCLOAK_USER admin ENV KEYCLOAK_PASSWORD admin123 ``` Criado o seu Dockerfile execute o comando para criar a imagem ``` docker build -t keycloak . # O nome 'keycloak' será usado depois no docker-compose no parâmetro 'image' ``` ### docker-compose.yml E o meu docker-compose ficou dessa forma: ``` version: "3.8" services: keycloak-sqlserver: container_name: keycloak-sqlserver image: keycloak # Lembra o comentário acima, sobre o nome? environment: PROXY_ADDRESS_FORWARDING: "true" DB_VENDOR: mssql DB_ADDR: [IP] DB_DATABASE: [NOME_DB] DB_SCHEMA: dbo DB_USER: [USUARIO] DB_PASSWORD: [SENHA] ports: - 6090:8080 - 6091:9990 ``` Após feita essas configurações, execute o comando para testar: ``` docker-compose up -d ``` Se tudo ocorrer bem (rsrsrs), após o liquibase finalizar a migração, o keycloak continuará com o processo de inicialização e você verá a seguinda saída nos logs: ``` 01:33:57,370 INFO [org.jboss.as.server] (Controller Boot Thread) WFLYSRV0212: Resuming server 01:33:57,375 INFO [org.jboss.as] (Controller Boot Thread) WFLYSRV0060: Http management interface listening on http://0.0.0.0:9990/management 01:33:57,376 INFO [org.jboss.as] (Controller Boot Thread) WFLYSRV0051: Admin console listening on http://0.0.0.0:9990 01:33:57,376 INFO [org.jboss.as] (Controller Boot Thread) WFLYSRV0025: Keycloak 10.0.2 (WildFly Core 11.1.1.Final) started in 54943ms - Started 690 of 995 services (708 services are lazy, passive or on-demand) ``` ## Conclusão Esse foi a solução que encontrei usando essa referência. [WFLYCTL0348: TimeoutException while running Keycloak in a Docker container with an external database (MariaDB)](https://serviceorientedarchitect.com/wflyctl0348-timeoutexception-while-running-keycloak-in-a-docker-container-with-an-external-database-mariadb/) No meu caso estava usando o SQL Server e usei o docker-compose também. Espero que isso possa ajudá-lo, caso venha a ter o mesmo problema. Críticas, dúvidas ou sugestões entre em contato e vamos conversar. Muito obrigado
andremoriya
796,944
Make readable string formatting
I run into this example some days ago while reading someone's else code (variable names were modified...
14,163
2021-08-19T09:31:05
https://dev.to/joaomcteixeira/don-t-make-cryptic-strings-for-formatting-fh2
python, strings, codeclean, refactorit
I run into this example some days ago while reading someone's else code (variable names were modified to `some...` or `var...`): ```python somejob = "{}{}{}{}{}{}{}{}".format( rundir, "/", fileroot, "_", someobj.somemethod(run["run_dir"]), "_", str(some_var), "w" ) ``` **What is wrong with this example?** First, can you actually understand the final shape of the `somejob` string? For me it is just utterly cryptic. *How many `{}` are there?* So, what is wrong with this case and how can we improve it? The problem with this string formatting example is that **constants** are being passed as **variables**, hiding the shape of the string. It becomes much easier to read if the developer defines the constant sub-strings in the main string: ```python somejob = "{}/{}_{}_{}w".format( rundir, fileroot, someobj.somemethod(run["run_dir"]), str(somevar), ) ``` Still, because in this particular case we are using `paths`, I would go further and advocate for using `pathlib.Path` instead of the hardcoded `/`: ```python # reduce the long call to a short temporary variable _tmp = someobj.somemethod(run["run_dir"]) somejob = Path( rundir, f'{fileroot}_{_tmp}_{somevar}w', ) ``` I truly believe these modifications improve code reading and facilitates the life of maintainers. What do you think? Does the last example reads better than the first one? Cheers,
joaomcteixeira
797,079
How to write for loops in React JSX
In this tutorial, we will learn how to write loops inside JSX in React. Setting up the...
0
2021-08-19T11:03:03
https://www.codingdeft.com/posts/react-for-loop/
react, javascript
In this tutorial, we will learn how to write loops inside JSX in React. # Setting up the project Let's create a new React app using the following command: ```bash npx create-react-app react-for-loop ``` Let's add some styling to the page in `index.css`: ```css body { margin: 10px auto; } .app { margin: 0; position: absolute; top: 0; left: 50%; transform: translate(-50%, 0%); } ``` # Using the map function In our application, let's display a list pizza toppings: ```jsx const toppings = [ "Golden Corn", "Paneer", "Tomato", "Mushroom", "Onion", "Black Olives", ] function App() { return ( <div className="app"> <h2>Pizza Toppings</h2> <ul> {toppings.map(topping => { return <li>{topping}</li> })} </ul> </div> ) } export default App ``` In the above code, - We have declared a list of Pizza toppings (as you may have guessed, I am a vegetarian and can't even imagine pineapple as a topping 🤮) - Inside the render function, we are using the [Javascript map](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/map) function for looping the list. - The map function accepts a callback, which receives the current item as the first argument (the name of the topping in our case). Then, we return the JSX that need to be rendered for each topping (a list item in our case). # Adding key to the list If you start the application, run it in the browser, and open the browser console, you will see a warning as shown below: ![Warning: Each child in a list should have a unique "key" prop.](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/4czsxb2nr587o6ozmw2e.png) React is warning us that each item in the list should have a unique key. Let's understand why keys are important: Say, for example, one of the items in the list changes, then having keys help React in identifying which item has changed in order to re-render the list. You can read more about keys [here](https://reactjs.org/docs/lists-and-keys.html). ```jsx const toppings = [ "Golden Corn", "Paneer", "Tomato", "Mushroom", "Onion", "Black Olives", ] function App() { return ( <div className="app"> <h2>Pizza Toppings</h2> <ul> {toppings.map(topping => { return <li key={topping}>{topping}</li> })} </ul> </div> ) } export default App ``` Since the name of the topping is unique, we have used it as the key. If there aren't any unique fields you may use the index of the array as well, as shown below: ```jsx toppings.map((topping, index) => { return <li key={index}>{topping}</li> }) ``` # Implicit returns Since we are using an arrow function as a callback function, we can write implicit returns since there is only a single line of code inside the callback. ```jsx const toppings = [ "Golden Corn", "Paneer", "Tomato", "Mushroom", "Onion", "Black Olives", ] function App() { return ( <div className="app"> <h2>Pizza Toppings</h2> <ul> {toppings.map(topping => ( <li>{topping}</li> ))} </ul> </div> ) } export default App ``` # Separating the Logic and the JSX If you are one of those persons who doesn't like to mix logic and JSX (surprisingly, I am not one of them! I like to mix logic and JSC no matter how clumsy it gets), you could have a separate function to have an array populated with the list of JSX as shown below. ```jsx const toppings = [ "Golden Corn", "Paneer", "Tomato", "Mushroom", "Onion", "Black Olives", ] let listToRender = [] const generateList = () => { for (let index = 0; index < toppings.length; index++) { const topping = toppings[index] listToRender.push(<li key={index}>{topping}</li>) } } generateList() function App() { return ( <div className="app"> <h2>Pizza Toppings</h2> <ul>{listToRender}</ul> </div> ) } export default App ``` # Source code You can view the source code [here](https://github.com/collegewap/react-for-loop) and do let me know in the comment section below about your favorite style of looping in React.
collegewap
797,112
Why Should You Use A VPN?
A VPN is a Virtual Private Network, in many of my guides I will always recommend using a VPN Service...
0
2021-08-19T12:11:38
https://dev.to/maximking1/why-should-you-use-a-vpn-45e0
vpn, security, ip, protection
A VPN is a Virtual Private Network, in many of my guides I will always recommend using a VPN Service for the ultimate online protection. But, what does it actually do? I’ve been asked this question many times so I’ll explain it here. A VPN will essentially masks your IP Address and location when browsing the web. When you visit a website in the headers (this is like what it requests) it will send a host IP which will either be your Home IP if your on your Home Network or Mobile Sim IP Address. Every network has its own IP Address, it’s the internet’s way of sending and receiving packets. It’s like your Home Address, so people can send and receive parcels they need the Address. When your VPN is active all it does is instead of talking directly to your Router it will forward the request via one of there servers (usually this is there nearest one, you can in there app) and you will look like your sending that packet form there server, this will make your IP completely hidden. But beware, if you don’t choose a “safe” VPN Service they will be able to see any of your traffic these are the ones I recommend below: - VyperVPN - Paid - ProtonVPN - Paid, Free Plan Very Limited There are many more out there just these 2 are great ones I recommend.. For anymore help you can contact me on my [discord server](https://discord.gg/FzsJMSRYDD)!
maximking1
797,657
Operadores Aritméticos (Parte 1)
Usamos operadores aritméticos para... fazer cálculos (duh de novo!). Os operadores aritméticos...
0
2021-08-22T13:10:19
https://dev.to/ananopaisdojavascript/operadores-aritmeticos-parte-1-3lmn
soma, subtracao, multiplicacao, divisao
Usamos operadores aritméticos para... fazer cálculos (duh de novo!). Os operadores aritméticos são: ```javascript /* + adição */ /* - subtração */ /* * multiplicação */ /* / divisão */ /* % módulo */ ``` ##Epa... o que é esse `%`?!?! Para ficar um pouquinho mais fácil, `%` é o resto da divisão. Por exemplo, o resto da divisão de 5 por 2 é igual a 1, portanto ficaria representado assim: ```javascript 5 % 2 = 1; // 1 é o resto da divisão ``` ##Mas temos outros tipos de operadores... Temos também o incremento `++` e o decremento `--` que indicam adicionar 1 ou diminuir em 1. ```javascript i++; // O mesmo que i + 1 i--; // O mesmo que i - 1 ``` Podemos usar esses operadores junto com o `=` para criarmos operadores de atribuição. ```javascript a += b; // O mesmo que a = a + b a -= b; // O mesmo que a = a - b a *= b; // O mesmo que a = a * b a /= b; // O mesmo que a = a / b ``` E aí? Gostaram? Até a próxima anotação!
ananopaisdojavascript
800,532
Is It Possible to Use Typescript in an AngularJS application?
Yes, it is very much possible to use typescript in an Angular JS application. You will have to...
0
2021-08-23T09:41:48
https://dev.to/katholder/is-it-possible-to-use-typescript-in-an-angularjs-application-37o7
angular, typescript, android, computerscience
Yes, it is very much possible to use typescript in an Angular JS application. You will have to install the typings for Angular. You can do this with the <b>TypeScript</b> Definition Manager. Basically what this does is tell typescript how Angular is (strict) typed. <b>Using NPM:</b> npm install -g tsd tsd install angular AngularJS is an undisputed champion among all the front end <b>web development frameworks</b>, well I am no expert to say that since honestly I have not worked much with other popular libraries like Knockout, backbone, amberJS etc. but for last few months I have been exploring the AngularJS and I am loving it. AngularJS brings several goodies to the table, it's very well designed, robust and well thought framework. In my opinion if you are a web developer, it’s totally worth it to invest your time learning angularJS even if you do not work much on the front end and do not plan to use it in your project in near future. With the announcement in ng-conf about angularJS and TypeScript collaboration and “Angular 2: built on typescript” anouncement, there seems to be a lot of momentum shift in the developers community from JavaScript to TypeScript for angularJS projects. You can go through all the <a href="https://codersera.com/blog/typescript-vs-javascript/">TypeScript VS JavaScript</a> comparisons to get a clear understanding of things.
katholder
801,143
How to start with i18next in the node application
This article will show how to start i18next in a node project. i18next i18next is one of...
14,270
2021-08-23T17:55:49
https://how-to.dev/how-to-start-with-i18next-in-the-node-application
javascript, i18n
This article will show how to start [i18next](https://www.i18next.com/) in a node project. # i18next i18next is one of the libraries I included in my list of [5 interesting internationalization libraries](https://how-to.dev/5-javascript-internationalization-libraries-that-look-interesting). On the project page, it's called *internationalization-framework*, and indeed it looked the most complete from the libraries I checked. # Package To start, let's create a new package: ``` $ npm init -y ``` To make sure we can use es modules, let's add to `package.json`: ```JSON ... "type": "module", ... ``` # Dependecy We can install i18next as a normal dependency with: ``` $ npm install --save i18next npm WARN i18next-vanilla@1.0.0 No description npm WARN i18next-vanilla@1.0.0 No repository field. + i18next@20.4.0 added 1 package from 1 contributor and audited 3 packages in 0.658s found 0 vulnerabilities ``` # Code The minimal code needed to experiment with the library is `index.js`: ```JS import i18next from "i18next"; i18next .init({ lng: "en", resources: { en: { translation: { hello_world: "hello world", }, }, }, }) .then((t) => { console.log(t("hello_world")); }); ``` # Running The code works as expected: ```shell $ node index.js hello world ``` # Links * [repository](https://github.com/how-to-js/i18next-vanilla) * [branch](https://github.com/how-to-js/i18next-vanilla/tree/node-start) # Summary In this article, we have started playing with i18next. Stay tuned for the following parts!
marcinwosinek
802,475
WhatsApp GB : vaut-il la peine d'être téléchargé ?
Qu'est-ce que le WhatsappGB MOD ? Il s'agit d'une modification de WhatsApp qui offre une expérience...
0
2021-08-24T22:21:21
https://dev.to/whatsmod/whatsapp-gb-vaut-il-la-peine-d-etre-telecharge-22fl
android
Qu'est-ce que le **WhatsappGB MOD** ? Il s'agit d'une modification de WhatsApp qui offre une expérience de messagerie supérieure et de nombreuses nouvelles fonctionnalités qui manquaient dans l'original. Il a été développé principalement sous forme d'extensions pour les plugins WordPress. Toutes les fonctionnalités de WhatsApp n'ont pas été modifiées et tous les plugins n'ont pas été activés pour être utilisés avec WhatsappGB. Whatsapp GB est une plateforme de messagerie instantanée et une application de réseau social qui offre un cryptage de bout en bout entre tous les utilisateurs. Cela permet de garantir la sécurité et la confidentialité de toutes les communications, même si le réseau est très encombré ou en danger imminent d'être mis sur écoute. Si vous souhaitez télécharger l'application et en savoir plus sur Whatsapp GB, rendez-vous sur https://whatsgb.info/. ## Quelle est la différence entre GB WhatsApp et WhatsApp Plus ? Les deux applications sont des **versions modifiées de WhatsApp**. ![Alt Text](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/6if5n26dufcinmif8d8y.png) Cependant, si vous avez des doutes sur la différence entre WhatsApp GB et WhatsApp Plus, nous expliquons ci-dessous les différences entre ces applications : - Appels illimités disponibles sur Whatsapp GB. - Blocage des appels pour des contacts ou des groupes spécifiques dans WhatsappGB. - La possibilité de copier le statut des contacts. - Aucun accès root n'est requis dans GBWhatsApp. Ce sont là, en gros, les principales différences entre les deux applications, mais nous pouvons constater qu'il n'y a pas beaucoup de variations. Les deux offrent des fonctionnalités très similaires aux utilisateurs, l'application GB WhatsApp étant plus proche de l'application originale tandis que WhatsApp Plus offre plus de confidentialité et de personnalisation. **GBWA est une version modifiée de l'application officielle WhatsApp**. Elle vous permet d'envoyer des messages multimédias gratuits, de mettre à jour votre liste d'amis, de rechercher des services et de réaliser des enregistrements historiques au sein de l'application. Vous avez déjà voulu changer l'apparence de WhatsApp, mais vous n'avez pas réussi à la faire fonctionner correctement sur votre appareil ? Vous avez cherché un moyen de masquer la fenêtre de chat tout en ayant accès aux fonctions que vous souhaitez, mais vous n'avez rien trouvé qui réponde à vos besoins ? Si c'est le cas, alors ce guide est fait pour vous. WhatsappGB Mod est une application WhatsApp modifiée qui vous permet de **personnaliser plusieurs aspects de l'application de messagerie**, avec plus de 60 thèmes différents à choisir. ![Alt Text](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/xt7izf9ekxrdw1rjtlkw.jpg) Vous pouvez masquer la boîte de dialogue et passer à un thème personnalisé en appuyant sur le bouton à trois lignes situé sous l'écran de dialogue. ## Dois-je télécharger Whatsapp GB ? Vous ne connaissez pas le MOD Whatsapp GB ? Il s'agit d'une modification du service de messagerie WhatsApp qui offre un certain nombre de fonctionnalités utiles aux utilisateurs qui souhaitent conserver les paramètres de confidentialité de leurs messages WhatsApp tels qu'ils les souhaitent. Voici quelques-uns des **meilleurs trucs et astuces** GB WhatsApp qui vous aideront à garder vos messages personnels et sécurisés, même lorsque vous utilisez la messagerie Facebook sur votre smartphone ou votre ordinateur. Vous pouvez consulter ce post pour tous les détails sur le mod et comment l'installer sur votre compte WhatsApp. Vous pouvez également trouver plus d'informations [ici](https://zoomup.fr/forum/profil/whatsappgb/ "ici"). Nous vivons dans un monde où les plateformes et les applications de communication mobile sont très diverses. WhatsApp est l'une des applications les plus utilisées dans ce domaine, mais son interface peut être assez déconcertante pour un débutant. C'est là qu'intervient le MOD WhatsappGB, une version modifiée de WhatsApp développée pour **Android et iOS** et conçue pour rendre l'application plus facile et plus amusante à utiliser. Elle comprend plus de 40 fonctionnalités, dont l'affichage de médias enrichis, l'amélioration du navigateur de stock, l'amélioration de la lecture et de l'écoute des messages, ainsi que de nombreuses autres qui rendront votre expérience WhatsApp complète.
whatsmod
803,512
Developer Life in a nutshell
Crunch time is very real in the tech industry regardless of your position. This meme pretty much...
0
2021-08-25T20:35:03
https://dev.to/code_doge/developer-life-in-a-nutshell-1ppk
webdev, programming, coding, devops
Crunch time is very real in the tech industry regardless of your position. This meme pretty much wraps up the feeling {% youtube 6ax20_bwz1Q %}
code_doge
804,519
How to use the IMSQRT Function in Excel Office 365?
The IMSQRT function returns the complex Square root of the complex number (inumber) having both real...
0
2021-08-27T12:19:28
https://geekexcel.com/how-to-use-the-imsqrt-function-in-excel-office-365/
tousetheimsqrtfuncti, excel, excelfunctions
--- title: How to use the IMSQRT Function in Excel Office 365? published: true date: 2021-08-26 16:33:48 UTC tags: ToUseTheIMSQRTFuncti,Excel,ExcelFunctions canonical_url: https://geekexcel.com/how-to-use-the-imsqrt-function-in-excel-office-365/ --- The **IMSQRT function** returns the **complex Square root of the complex number** (inumber) having both **real & imaginary parts**. In this article, we are going to see how to **use the IMSQRT** **Function In Excel Office 365.** Let’s get into this article!! Get an official version of MS Excel from the following link: **[https://www.microsoft.com/en-in/microsoft-365/excel](https://www.microsoft.com/en-in/microsoft-365/excel)** ## IMSQRT Function Syntax ``` =IMSQRT (inumber) ``` **Syntax Explanation:** **inumber:** complex number having both real & imaginary ## Example1 - Firstly, you have to **create a sample data** to get the **complex Square root** of the **input complex number** (inumber). ![](https://geekexcel.com/wp-content/uploads/2021/08/Sample-data-36.png)<figcaption>Sample data</figcaption> - Then, you need to calculate the **IMSQRT Function** by using the following **formula**. ``` =IMSQRT (A2) ``` **A2:** complex number (inumber) provided as a cell reference. ![](https://geekexcel.com/wp-content/uploads/2021/08/Use-IMSQRT-function.png)<figcaption>Use IMSQRT function</figcaption> - Now, the the formula returns the **complex Square root of the complex number**. - Finally, you need to **copy the formula** to the other remaining cells using **Ctrl + D ** shortcut key. ![](https://geekexcel.com/wp-content/uploads/2021/08/Copy-to-other-cells-1-1024x459.png)<figcaption>Copy to other cells</figcaption> ## Example2 - Firstly, you have to **create a sample data** to get the **complex Square root** of the **input complex number** (inumber). ![](https://geekexcel.com/wp-content/uploads/2021/08/Ex-2-Sample-data.png)<figcaption>Sample data</figcaption> - Then, you need to calculate the **IMSQRT Function** by using the following **formula**. ``` =IMSQRT (A2) ``` **A2:** complex number (inumber) provided as a cell reference. ![](https://geekexcel.com/wp-content/uploads/2021/08/IMSQRT-function-2.png)<figcaption>IMSQRT Function</figcaption> - Now, the the formula returns the **complex Square root of the complex number**. - Finally, you need to **copy the formula** to the other remaining cells using **Ctrl + D ** shortcut key. ![](https://geekexcel.com/wp-content/uploads/2021/08/Use-CtrlD.png)<figcaption>Copy to other cells</figcaption> **Check this too:** - **[IMTAN Function](https://geekexcel.com/how-to-use-the-imtan-function-in-excel-office-365/)** - [**IMSUM Function**](https://geekexcel.com/how-to-use-imsum-function-in-ms-excel-365-with-examples/) - **[IMSUB Function](https://geekexcel.com/how-to-use-imsub-function-in-ms-excel-365-with-examples/)** **NOTES:** - The formula returns the **#NUM! error** if the complex number doesn’t have **lower case i or j ** (iota). - The formula returns the **#VALUE! Error** if the complex number doesn’t have correct **complex number format**. ## Verdict We hope that this short tutorial gives you guidelines to **use the IMSQRT** **Function In Excel Office 365. ** Please leave a comment in case of any **queries,** and don’t forget to mention your valuable **suggestions** as well. Thank you so much for Visiting Our Site!! Continue learning on **[Geek Excel](https://geekexcel.com/)!! **Read more on [**Excel Formulas**](https://geekexcel.com/excel-formula/) **!!** **Read Also:** - **[How to use the IMTAN Function in Excel office 365?](https://geekexcel.com/how-to-use-the-imtan-function-in-excel-office-365/)** - **[How to use the PROB function in Excel Spreadsheets?](https://geekexcel.com/how-to-use-the-prob-function-in-excel-spreadsheets/)** - **[Use IMSUB Function in MS Excel 365 – { With Examples }](https://geekexcel.com/how-to-use-imsub-function-in-ms-excel-365-with-examples/)** - **[How to Use IMSUM Function in MS Excel 365? – (With Examples)](https://geekexcel.com/how-to-use-imsum-function-in-ms-excel-365-with-examples/)** - **[How to Use IMPRODUCT Function in Excel 365? – [with Examples]](https://geekexcel.com/how-to-use-improduct-function-in-excel-365-with-examples/)**
excelgeek
804,530
Haskell Foundation: Interview with Andrew Boardman
In this article, I interview Andrew Boardman, the Executive Director of the Haskell Foundation. We...
0
2021-08-30T12:34:39
https://serokell.io/blog/interview-with-andrew-boardman
haskell
--- title: Haskell Foundation: Interview with Andrew Boardman published: true date: 2021-08-26 00:00:00 UTC tags: haskell canonical_url: https://serokell.io/blog/interview-with-andrew-boardman cover_image: https://dev-to-uploads.s3.amazonaws.com/uploads/articles/pgownm0ftkwsipz19brp.jpg --- In this article, I interview Andrew Boardman, the Executive Director of the [Haskell Foundation](https://haskell.foundation/). We talk about the Haskell Foundation, its plans and goals, and Andrew’s experience while guiding the foundation. Read further to discover what the Haskell Foundation does and how you can help it. ## Interview with Andrew Boardman ### What is the Haskell Foundation? The Haskell Foundation is a non-profit organization with a mission to drive mainstream adoption of the Haskell programming language. ### What is your role at the Haskell Foundation? I am the Executive Director, which means that it is my job to execute on our mission and strategy and figure out how to use the Foundation’s resources to best help the Haskell community. ![Andrew Boardman card](https://serokell.io/files/en/enexjrph.card_(3)_(1).jpg) ### What are the goals of the Haskell Foundation? Our top-level goal is getting more programmers and more organizations using Haskell. We want there to be more opportunities for Haskellers to use the language for their day jobs and evangelize the competitive advantages that the language and its runtime have, so companies can create higher quality products for their customers using fewer resources. ### How will the Haskell Foundation help advance the open-source Haskell ecosystem? We have a few different ways we support our open-source ecosystem. In some cases, we identify a need that hasn’t been addressed and act as a catalyst to bring the subject matter experts together to figure out the right solution. We can also be the project managers. When resources are needed, we can pay for it, source in-kind donations from Sponsors, etc. We are dedicated to our community and want to help it thrive. We adopted the Guidelines for Respectful Communication from the GHC Steering Committee to help ensure that everyone feels welcome and included and are working on our Code of Conduct as well. We are taking the best practices we can find from other communities to foster a lively, energetic, and friendly atmosphere. ### What are the pain points the Haskell Foundation is looking to address right now? Which issues are you working on right now? The Foundation is doing a few things in the technical space, like Bodigrim’s work to convert Text to utf-8, and some in the community space, like the [Haskell Interlude](https://haskell.foundation/podcast/) podcast. One of the bigger pain points we are working on is the lack of active maintainers in some areas of the ecosystem. We are working on exciting the community, getting people involved in various open-source projects, and matchmaking between the projects that need volunteers and the people who really want to help but don’t know where to start. ### What are the difficulties in managing such a diverse and distributed set of ecosystem participants? The biggest challenge is competing priorities. We have a lot of very passionate, very smart people in Haskell, and there are times when they want opposite things. The Haskell Foundation does have a purpose, and sometimes what we need to do to work towards that purpose is contrary to some Haskeller’s goals. ### What is the relationship of the Haskell Foundation to its sponsors? Our sponsors and donors pay the bills and give us the resources we need to make a difference. Our Board of Directors is the group that fundamentally determines what the Foundation will do, and some of the members of our Board are employees of Sponsors, but two are not directly related. We are working on a proposal to create a Technical Advisory Board, and for that there is likely to be a formal relationship between sponsorship level and some of the membership, but the recommendations from that group are advisory only and not binding. At the end of the day, companies sponsor the Haskell Foundation to support the community and help make it better. It is a relationship of enlightened self-interest, and it gives those sponsors greater visibility within the community, which can be particularly helpful for recruiting, but also means that the compiler, tools, and libraries that they build their business on have the resources necessary to be maintained and improved. ### Are there any ways that Haskell enthusiasts can help the foundation? Absolutely! We have many generous individual sponsors of the Foundation, a fantastic community of volunteers helping with HF projects, we love having subject matter experts available for advice and questions. For those Haskellers lucky enough to work at a company using the language, please advocate to your management to give back to and support our community by becoming sponsors! ### Where can people learn more about the foundation? Beyond our [website](https://haskell.foundation), the main ways you can learn about what we’re doing or ask questions are the [Haskell Discourse](https://discouse.haskell.org), our [Slack](https://join.slack.com/t/haskell-foundation/shared_invite/zt-mjh76fw0-CEjg2NbyVE8rVQDvR~0F4A), or by emailing us at contact@haskell.foundation. For those who are interested in volunteering for HF projects or just for Haskell projects in general, and want help figuring out what projects could use a hand, email us at volunteer@haskell.foundation, or join us on Slack and introduce yourself! * * * I would like to thank Andrew for the interview and wish the best of luck to the Haskell Foundation in accomplishing its goals! If you want to read more interviews with people that use FP for both hobby side projects and large-scale industrial projects, I suggest visiting our [interviews](https://serokell.io/blog/interviews) section. In addition, don’t forget to follow our blog via [Twitter](https://twitter.com/serokell), [Medium](https://serokell.medium.com/), or [Dev](https://dev.to/serokell), or simply by subscribing to our newsletter below!
serokell
804,621
HackerRank #12 | Strings Introduction | 🇧🇷
Este exercício pede que, a partir da entrada de duas strings, o console retorne: O número de...
0
2021-08-26T21:17:38
https://dev.to/beatrizmaciel/hackerrank-12-strings-introduction-2d1n
java, compareto, comparable, substring
[Este exercício](https://www.hackerrank.com/challenges/java-strings-introduction/problem) pede que, a partir da entrada de duas strings, o console retorne: * O número de caracteres através do tamanho da `string` (length) * `No` para que as strings estejam na ordem alfabética correta ou `Yes` se estiverem na ordem alfabética incorreta ou equivalente*. * A concatenação das strings, sendo que a primeira letra de cada palavra deve ser impressa em maiúsculo. O passo a passo para a resolução desse problema é: * Declarar uma variável `Scanner` * Escanear a `String A` e a `String B` * Somar o tamanho da `String A` com o Tamanho da `String B` `System.out.println(A.length() + B.length());` * Usar o método `.compareTo()` para comparar a ordem alfabética da `String A` com a `String B` #### Interface java.lang.Comparable e método .compareTo() O método `.compareTo()` faz parte da `interface Comparable` e organiza, por default, em ordem alfanumérica. Isso significa que organize em ordem crescente (para números) ou alfabética (para letras). Veja o exemplo: ``` public CPF implements Comparable { private int numero; public int compareTo (CPF novoCPF){ if (this.numero < outroCPF.numero) { return -1; } if (this.numero > outroCPF.numero) { return 1; } if (this.numero == outroCPF.numero) { return 0; } } ``` No primeiro `if`, o `.compareTo()` retorna um número negativo indicando que o `this` deve vir _antes_ de outroCPF. O exemplo usa -1 para ilustrar, mas poderia ser qualquer número negativo. No segundo `if`, o `.compareTo()` retorna um número positivo para que o `this` venha _depois_ do outroCPF. O exemplo usa 1 para ilustrar, mas poderia ser qualquer número positivo. No terceiro `if`, se ambos foram iguais, o retorno será 0 e a ordem será mantida. Neste caso, o default é zero (0). ========= Por fim, a última etapa é a de organizar as strings de forma que a primeira letra de cada palavra fique em maiúsculo. Para isso, usamos o método `substring()`, da classe String. O método `substring()` retorna outra string, derivada da primeira string. Aqui alguns exemplos: ``` "unhappy".substring(2) returns "happy" "Harbison".substring(3) returns "bison" "emptiness".substring(9) returns "" (an empty string) ``` Quando passamos dois parâmetros na substring (ex: `.substring(0,10)`), significa que estamos selecionando aquela quantidade de caracteres. Exemplo: ``` String stringExemplo = "JavaScript e Java"; String resultado = stringExemplo.substring(0,10) System.out.println(resultado); Console: JavaScript ``` Isso porque a palavra JavaScript tem 10 letras e selecionamos de 0 a 10. Vamos usar essa seleção, mas de 0 a 1, para pegar a primeira letra das palavras que declararmos nas strings. Dessa forma, o código vai ficar: ``` String A1 = (A.substring(0, 1)).toUpperCase() + A.substring(1); String B1 = (B.substring(0, 1)).toUpperCase() + B.substring(1); ``` Por fim, somamos `A.substring(1)` e `B.substring(1)` porque precisamos dizer ao computador que voltaremos a imprimir os caracteres (a começar pela posição 1) em letras minúsculas. Sem essa adição, a impressão no console termina na primeira letra maiúscula, deixando de imprimir o resto em minúsculo. Caso quiséssemos delimitar a quantidade de caracteres minúsculos, poderíamos usar dois parâmetros (1, 10) e depois voltar a imprimir caracteres maiúsculos usando um ou dois parâmetros. ========= O código final fica assim: ``` public static void main(String[] args) { Scanner scanner = new Scanner(System.in); String A = scanner.next(); String B = scanner.next(); int sum = A.length() + B.length(); System.out.println(sum); if(A.compareTo(B) > 0){ System.out.println("Yes"); } else { System.out.println("No"); } String A1 = (A.substring(0,1)).toUpperCase() + A.substring(1); String B1 = (B.substring(0,1)).toUpperCase() + B.substring(1); ; System.out.println(A1 + " " + B1); } } ``` ========= * Observação: > O método compareTo() usa o sistema menor para maior. Sendo assim, A < B < C < D < E ... < Z. Isso significa que, quando mais perto de Z, maior o "valor" de um caracter. E quanto mais perto de A, menor o seu valor. É por isso que pode parecer confuso que uma letra que vem primeiro retorne "No", mas é porque ela é menos "valiosa" do que uma letra que vem depois. ========= #### Referências: - [Substring](https://docs.oracle.com/javase/7/docs/api/java/lang/String.html#substring(int)) : Oracle - [CompareTo](https://docs.oracle.com/javase/7/docs/api/java/lang/Comparable.html) : Oracle - [CompareTo](https://blog.caelum.com.br/ordenando-colecoes-com-comparable-e-comparator/) : Caelum - [CompareTo](https://www.guj.com.br/t/usando-compareto/132830/2) : Guj ============ Essa publicação faz parte de uma série de exercícios resolvidos em Java no HackerRank. Acesse a série completa: - [HackerRank #6 | Scanner e End-of-file](https://dev.to/beatrizmaciel/hackerrank-6-scanner-e-endoffile-462c) - [HackerRank #7 | Int to String / String to Int](https://dev.to/beatrizmaciel/hackerrank-7-int-em-string-e-vice-versa-4n1e) - [HackerRank #8 | Date and Time](https://dev.to/beatrizmaciel/hackerrank-8-date-and-time-1f78) - [HackerRank #9 | Static Initializer Block](https://dev.to/beatrizmaciel/hackerrank-9-static-initializer-block-48ha) - [HackerRank #10 | Currency Formatter](https://dev.to/beatrizmaciel/hackerrank-10-currency-formatter-22oj) - [HackerRank #11 | DataTypes](https://dev.to/beatrizmaciel/hackerrank-11-datatypes-2e9h) - HackerRank #12 | Strings Introduction - [HackerRank #13 | Substring Comparisons](https://dev.to/beatrizmaciel/hackerrank-13-substring-comparisons-57ha) - [HackerRank #14 | Abstract Class](https://dev.to/beatrizmaciel/hackerrank-14-abstract-class-3h5d) - [HackerRank #18 | BigInteger](https://dev.to/beatrizmaciel/hackerrank-18-biginteger-4jad) - [HackerRank #19 | Loops II](https://dev.to/beatrizmaciel/hackerrank-19-loops-ii-385n) - [HackerRank #20 | String Reverse](https://dev.to/beatrizmaciel/hackerrank-20-string-reverse-nec) - [HackerRank #23 | Instanceof keyword](https://dev.to/beatrizmaciel/hackerrank-23-instanceof-keyword-3lh6) - [HackerRank #26 | Generics](https://dev.to/beatrizmaciel/hackerrank-26-generics-55p8) - [HackerRank #27 | 1D Array](https://dev.to/beatrizmaciel/hackerrank-27-1d-array-5f80) - [HackerRank #28 | Anagrams](https://dev.to/beatrizmaciel/hackerrank-28-anagrams-boi) - [HackerRank #33 | Arraylist](https://dev.to/beatrizmaciel/hackerrank-33-arraylist-2lj1) - [HackerRank #34 | Exception Handling Try / Catch](https://dev.to/beatrizmaciel/hackerrank-34-exception-handling-try-catch-144f) - [HackerRank #36 | Exception Handling](https://dev.to/beatrizmaciel/hackerrank-35-exception-handling-44e) - [HackerRank #37 | List](https://dev.to/beatrizmaciel/hackerrank-37-list-4gmj) - [HackerRank #38 | SubArray](https://dev.to/beatrizmaciel/hackerrank-38-subarray-1693) - [HackerRank #39 | HashSet](https://dev.to/beatrizmaciel/hackerrank-39-hashset-3jb3) - [HackerRank #40 | Java Dequeue](https://dev.to/beatrizmaciel/hackerrank-40-java-dequeue--497h)
beatrizmaciel
804,647
Why you should care about Azure Front Door Standard and Premium
This post was originally published on Thu, Aug 26, 2021 at cloudwithchris.com. Azure Front Door -...
0
2021-08-27T09:25:34
https://www.cloudwithchris.com/blog/azure-front-door-standard-premium/
architecture, azure, resilience, cloud
**This post was originally published on Thu, Aug 26, 2021 at [cloudwithchris.com](https://www.cloudwithchris.com/blog/azure-front-door-standard-premium/).** Azure Front Door - It's an Azure Service that has been generally available for quite some time. It went [Generally Available (GA) in April of 2019](https://azure.microsoft.com/en-us/updates/azure-front-door-service-is-now-available/) after being in [Public Preview since September 2018](https://azure.microsoft.com/en-us/updates/azure-front-door-service-in-public-preview/). It's had several updates since, including a slew of Web Application Firewall enhancements, Rules Engine support and much more. But did you know Microsoft released the Azure Front Door Standard and Premium SKUs in preview in Februrary of 2021? So, what are they? How do they compare to the aforementioned Azure Front Door offering? And when would you want to think about using Azure Front Door compared with Azure CDN? We'll be covering all of those points in this post. ## What is Azure Front Door? Let's first set the scene, making sure we're all on the same page. What even is Azure Front Door? If you haven't deployed it for your own solution, it's quite likely that you've used it as a consumer. There is a great case study on how [LinkedIn uses Azure Front Door](https://customers.microsoft.com/en-gb/story/841393-linkedin-professional-services-azure-front-door-service) as part of their own infrastructure stack. Not a LinkedIn user? Well, the [original Azure Front Door general availability blog post](https://azure.microsoft.com/en-gb/blog/azure-front-door-service-is-now-generally-available/) notes that Office 365, Xbox Live, MSN and Azure DevOps had all adopted Azure Front Door. So, like I mentioned - if you haven't already deployed it - it's quite likely you've already used it! Azure Front Door is a global service, which is typically used as an entry point for web applications. It's well-suited for this task, as it operates at Layer 7 (HTTP/HTTPS-based) of the networking stack. However, calling it a load balancer would be underselling it. Azure Front Door uses the Microsoft Global Edge network to accept traffic from end-users. You can associate a Web Application Firewall (WAF) with it, to protect your applications from potential threats. > **Note:** There are different types of Load Balancing options. For example, Azure Load Balancer operates at Layer 4. Azure Traffic Manager is a DNS based load balancer. The difference between these is where they operate in the networking stack. Layer 4 is the transport layer, whereas Layer 7 is the application layer. > > Therefore, the decisions that can be made at Layer 4 are typically based around the TCP and UDP protocols. There is no context or option to make decisions based upon information at the application level (e.g. Path based filtering, etc.). Layer 7 load balancing allows you to make load balancing decisions based upon some information/context from the application. Think about aspects like Request Headers, Request Paths, etc. A good comparison would be Azure Load Balancer (Layer 4) vs Azure Application Gateway (Layer 7). > > You can find some additional information on Layer 4 vs Layer 7 load balancing on the [NGINX Website](https://www.nginx.com/resources/glossary/layer-7-load-balancing/). ## How do Azure Front Door Classic, Standard and Premium compare? Azure Front Door Standard and Premium [went into preview in February 2021](https://azure.microsoft.com/en-us/updates/azure-front-door-standard-and-premium-now-in-public-preview/). The explanation of Azure Front Door in the previous section is true for Azure Front Door (Classic), as well as Azure Front Door Standard and Premium. However, Azure Front Door Standard and Premium has additional enhancements. Depending on the type of traffic - You can either accelerate traffic by using Dynamic Site Acceleration (DSA) to the appropriate source, or serve up cached contents through it's Content Delivery Network functionality. In the Standard and Premium SKUs, Azure Front Door combines the capabilities of Azure Front Door, Azure CDN and Azure Web Application Firewall (WAF). Both Azure Front Door Standard and Premium contain several common features, including - * Custom Domains * SSL Offload * Caching * Compression * Global load balancing * Layer 7 routing * URL rewrite * Enhanced Metrics and diagnostics * Traffic report Azure Front Door premium contains the following features, in addition to the previous list - * Private Origin (Private Link) * Web Application Firewall (WAF) support * Bot Protection * Security Report > **Note:** Private Origin (Private Link) support is a big deal in my opinion. Before Azure Front Door Standard/Premium, I've seen a few scenarios where an organisation wants to build an Architecture of Azure Front Door in front of Azure API Management. The only way to achieve this at the time was by restricting traffic inbound, based upon Request Headers sent from Azure Front Door. > > With Azure Private Origin (Private link), you can still route traffic to your backend origins, even if they are only accessible privately. > > Why would you care about this pattern? So that you can guarantee traffic is not being bypassed to your backend services, and is being routed through Azure Front Door. Perhaps you have adopted some rules in your WAF that you wish to process before traffic reaches your application. Having a private backend, while having a public entry point at the edge allows you to achieve this. It's worth mentioning that (at time of writing), Azure Front Door Standard and Premium are in a preview state. Azure Front Door (Classic) is Generally Available. However, the [docs call out many reasons](https://docs.microsoft.com/en-gb/azure/frontdoor/standard-premium/overview#why-use-azure-front-door-standardpremium-preview) to use Azure Front Door Standard or Premium. It's important to note that it's not recommended for production workloads until it exists a preview state. There is a difference in the pricing models between Azure Front Door (Classic) and Azure Front Door Standard / Premium. Azure Front Door classic had a more involved pricing structure, based upon outbound data transfers, routing rules, inbound data transfers and frontend hosts. The WAF capability was an additional cost if enabled, with custom rules / managed rulesets also having an additional price per unit. In contrast, Azure Front Door Standard / Premium's pricing model is simplified. There is a base fee for either the Standard or Premium SKU. On top of that, there are charges based upon outbound data transfers (i.e. data going out of Front Door POPs to the client), inbound data transfers from POPs to origin and requests incoming from client to Front Door POPs. > **Note:** It's important to note that Azure Front Door Premium includes Web Application Firewall (WAF) at no additional cost. This is an additional cost in Azure Front Door (Classic). Of course, the finer details of the pricing model can change over time. For the latest and greatest, please review the [Azure Pricing Page](https://azure.microsoft.com/en-gb/pricing/details/frontdoor/). ## Azure Front Door vs Azure CDN Based on the previous section, you've likely noticed that Azure Front Door (Standard/Premium) and Azure CDN now share some common functionality around caching, and the rules engine. If you've previously used Azure Front Door (Classic), then you may have previously had an architecture that used both Azure Front Door as well as Azure CDN. However, even Azure Front Door (Classic) had [caching capabilities built-in as per the Azure Docs](https://docs.microsoft.com/en-us/azure/frontdoor/front-door-caching). You'll notice that the adjustments for Azure Front Door Standard and Premium, make this feel like a much more integrated experience, as it is part of the setup process of your new Azure Front Door Resource (as explained in the [blog post announcing Azure Front Door Standard and Premium](https://azure.microsoft.com/en-gb/blog/azure-front-door-enhances-secure-cloud-cdn-with-intelligent-threat-protection/)). The idea behind this new Azure Front Door experience is a single unified platform to accelerate static and dynamic content acceleration. All that, with the combined functionality of Web Application Firewall (as explained in the opening of this post). > **Note:** What is the difference between Static Content/Site Acceleration and Dynamic Content/Site Acceleration? > > Think of Static Content/Site Acceleration as caching the files closer to your end-users. So, a typical CDN scenario. This is how the Cloud With Chris website, as well as Cloud With Chris Podcast MP3 files are delivered to you. They are hosted in a central location (e.g. Azure Static Web App or Azure Storage Account), and are cached at Points of Presence on the Microsoft Edge closer to you. > > But what about Dynamic Site Acceleration? The fact that it's dynamic means that we can't cache the content, as it's likely going to change over time. That strategy may not work here. Fundamentally, the internet is an unreliable place. Routes become unavailable, transient issues can impact our path. Dynamic Site Acceleration uses route optimization techniques to choose the most optimal path to the origin, so that users can be sent via the fastest and most reliable route possible. > > Dynamic Site Acceleration can often use additional TCP optimizations to ensure the traffic is routed efficiently and effectively. For example, eliminating TCP slow start, leveraging persistent connections and tuning TCP packet parameters are just some typical examples (these are general examples to illustrate the point, and not specific to Azure Front Door). ## How does Azure Front Door work? As a service, your usage of Azure Front Door is primarily around configuration (i.e. setting up your endpoint name, your origin details and additional configuration around caching, compression and WAF options). From a scalability perspective, the service deals with this transparently.You won't see any sliders to specify the minimum, maximum or desired number of instances. You don't need to specify autoscale rules or similar. The service will scale automatically for you. Now, I've hinted a few times that Azure Front Door is a global service. This means that Azure Front Door's edge nodes (sometimes known as points of presence) are global in nature. This point is worth thinking about in some further detail. One of the configuration options that you have in Azure Front Door is adjust the health probes used from the edge nodes to your origin. Why is this important? As Azure Front Door is global, it's going to have many of these edge environments all across the globe. That means that each of those edge environments will be sending a health probe at some point. If you're particularly aggressive with your probe timeout settings (e.g. every few seconds), then this will cause a significant increase in the requests to your backend origin. > **Note:** This is particularly important to consider if your origin wasn't designed for scale, and you may need to consider the additional load from these probes. > > Alternatively, if you are using a serverless tier (based on pay-per-execution), then your health probe configuration will have a tangible impact on your costs. ## Summary In summary, Azure Front Door Standard / Premium are some welcome evolutions on the Azure Front Door (Classic) offering. It has a new pricing model which is simpler to understand, and contains some notable feature updates (e.g. Private Origin Support (Private Link)). Azure Front Door Standard is content-delivery optimised as opposed to premium which is security optimised. Azure Front Door can bring value if you have a distributed set of users that you want to serve content to. The content can either be dynamic (and leverage the Dynamic Site Acceleration capabilities of Azure Front Door) or static (and leveraging the caching capabilities of Azure Front Door). Don't forget, the premium SKU is security optimized and has Web Application Firewall (WAF) capabilities built-in. A great addition to the entry point for your Web Application! If you want to learn more about Azure Front Door, I recommend that you take a look at the [Introduction to Azure Front Door](https://docs.microsoft.com/en-us/learn/modules/intro-to-azure-front-door/) Microsoft Learn Module, as well as the Azure Documentation. Be aware that there is a separate documentation hub for [Azure Front Door (Classic)](https://docs.microsoft.com/en-us/azure/frontdoor/front-door-overview) and [Azure Front Door (Standard/Premium)](https://docs.microsoft.com/en-us/azure/frontdoor/standard-premium/overview). Are you already using Azure Front Door? Are you using Classic, Standard or Premium? Perhaps you're considering using Azure Front Door after scanning through this post? I'd love to hear more over on [Twitter, @reddobowen](https://twitter.com/reddobowen). If there's anything that you'd like me to explore in a hands-on blog post, please let me know! I'm already considering a blog post which compares Azure Front Door (Classic) with Azure API Management to Azure Front Door (Premium) with Azure API Management, and the private link capabilities (which I hinted a little further up in the article). Thanks for reading, and bye for now!
reddobowen
804,722
Funções (Código Limpo: Que Bruxaria é Essa?!?! - Parte 3)
Argumentos da função (o ideal é que sejam 2 ou menos) Limitar a quantidade de parâmetros...
0
2021-09-24T14:34:14
https://dev.to/ananopaisdojavascript/funcoes-codigo-limpo-que-bruxaria-e-essa-parte-3-12c6
cleancode, javascript
## Argumentos da função (o ideal é que sejam 2 ou menos) Limitar a quantidade de parâmetros de uma função é incrivelmente importante porque a deixa mais fácil de ser testada. Três ou mais argumentos causam uma combinação explosiva na qual você precisa testar toneladas de casos distintos com cada argumento separado. Um ou dois argumentos é o ideal e, se possível, evite um terceiro argumento. Mais do que isso deve ser consolidado. Se o normal para você é usar mais de dois parâmetros, então a sua função está tentando fazer demais. Nos casos nos quais é algo inevitável, um objeto de alto nível será suficiente como um parâmetro. Como o JavaScript permite que você escreva objetos em movimento, sem um monte de classes padrão, você pode usar um objeto se precisa de muitos argumentos. Para fazer com que as propriedades esperadas pela função sejam óbvias, você pode usar a sintaxe de desestruturação do ES2015/ES6. A desestruturação tem algumas vantagens: * Quando alguém olha a assinatura da função, fica imediatamente claro ver quais propriedades estão sendo usadas. * Pode ser usada para estimular parâmetros nomeados. * A desestruturação também clona os valores primitivos especificados do objeto argumento passado dentro da função, o que ajuda a prevenir efeitos colaterais. Observação: objetos e vetores que são desestruturados do objeto argumento NÃO são clonados. * Linters podem avisar você das propriedades inutilizadas, o que seria impossível sem a desestruturação. ### Não é recomendável: ```javascript function createMenu(title, body, buttonText, cancellable) { // ... } createMenu("Foo", "Bar", "Baz", true); ``` ### É recomendável: ```javascript function createMenu({ title, body, buttonText, cancellable }) { // ... } createMenu({ title: "Foo", body: "Bar", buttonText: "Baz", cancellable: true }); ``` ## Funções devem apresentar apenas uma única utilidade Esta é, de longe, a regra mais importante na engenharia de software. Quando funções apresentam mais de uma utilidade, são mais difíceis de compor, testar e explicar. Quando você restringe a função a uma única ação, pode ser refatorada com facilidade e seu código ficará com uma leitura mais limpa. Se você assimilar apenas essa regra, estará na frente de muitos desenvolvedores. ### Não é recomendável: ```javascript function emailClients(clients) { clients.forEach(client => { const clientRecord = database.lookup(client); if (clientRecord.isActive()) { email(client); } }); } ``` ### É recomendável: ```javascript function emailActiveClients(clients) { clients.filter(isActiveClient).forEach(email); } function isActiveClient(client) { const clientRecord = database.lookup(client); return clientRecord.isActive(); } ``` ## Os nomes de funções devem dizer o que fazem ### Não é recomendável: ```javascript function addToDate(date, month) { // ... } const date = new Date(); // It's hard to tell from the function name what is added addToDate(date, 1); ``` ### É recomendável: ```javascript function addMonthToDate(month, date) { // ... } const date = new Date(); addMonthToDate(1, date); ``` ## Funções devem apresentar somente um único nível de abstração Quando sua função apresenta mais de um nível de abstração, normalmente está fazendo demais. A divisão das funções leva a uma reutilização e testes mais fáceis. ### Não é recomendável: ```javascript function parseBetterJSAlternative(code) { const REGEXES = [ // ... ]; const statements = code.split(" "); const tokens = []; REGEXES.forEach(REGEX => { statements.forEach(statement => { // ... }); }); const ast = []; tokens.forEach(token => { // lex... }); ast.forEach(node => { // parse... }); } ``` ### É recomendável: ```javascript function parseBetterJSAlternative(code) { const tokens = tokenize(code); const syntaxTree = parse(tokens); syntaxTree.forEach(node => { // parse... }); } function tokenize(code) { const REGEXES = [ // ... ]; const statements = code.split(" "); const tokens = []; REGEXES.forEach(REGEX => { statements.forEach(statement => { tokens.push(/* ... */); }); }); return tokens; } function parse(tokens) { const syntaxTree = []; tokens.forEach(token => { syntaxTree.push(/* ... */); }); return syntaxTree; } ``` ## Remova código duplicado Esforce-se para evitar código duplicado. O código duplicado é ruim porque significa que há mais de um lugar para alterar algo se você precisa modificar alguma lógica. Imagine a seguinte situação: você comanda um restaurante e monitora o seu inventário: todos os seus tomates, cebolas, alho, pimentas, etc. Se você tem várias listas para mantê-lo, todas deverão estar atualizadas sempre que você servir uma refeição com tomates, por exemplo. Se você tem uma única lista, haverá apenas um lugar para atualização! Às vezes seu código está duplicado porque você apresenta duas ou mais funcionalidades ligeiramente distintas, que dividem muito em comum, porém essas diferenças lhe forçam a ter duas ou mais funções separadas que fazem mais do que as mesmas utilidades. A remoção do código duplicado significa criar uma abstração que pode lidar esse conjunto de funcionalidades diferentes com uma única função/módulo/classe. Obter a abstração correta é crucial e é por isso que você deve seguir o princípios de SOLID que estão na seção Classes. Abstrações ruins podem ser piores que código duplicado, portanto tenha cuidado! Dito isso, se você pode criar uma boa abstração, vá em frente! Não se repita, do contrário você se encontrará na situação de atualizar muitos lugares toda vez que você quiser apenas alterar uma única coisa. ### Não é recomendável: ```javascript function showDeveloperList(developers) { developers.forEach(developer => { const expectedSalary = developer.calculateExpectedSalary(); const experience = developer.getExperience(); const githubLink = developer.getGithubLink(); const data = { expectedSalary, experience, githubLink }; render(data); }); } function showManagerList(managers) { managers.forEach(manager => { const expectedSalary = manager.calculateExpectedSalary(); const experience = manager.getExperience(); const portfolio = manager.getMBAProjects(); const data = { expectedSalary, experience, portfolio }; render(data); }); } ``` ### É recomendável: ```javascript function showEmployeeList(employees) { employees.forEach(employee => { const expectedSalary = employee.calculateExpectedSalary(); const experience = employee.getExperience(); const data = { expectedSalary, experience }; switch (employee.type) { case "manager": data.portfolio = employee.getMBAProjects(); break; case "developer": data.githubLink = employee.getGithubLink(); break; } render(data); }); } ``` ## Configure objetos padrão em `Object.assign` ### Não é recomendável: ```javascript const menuConfig = { title: null, body: "Bar", buttonText: null, cancellable: true }; function createMenu(config) { config.title = config.title || "Foo"; config.body = config.body || "Bar"; config.buttonText = config.buttonText || "Baz"; config.cancellable = config.cancellable !== undefined ? config.cancellable : true; } createMenu(menuConfig); ``` ### É recomendável: ```javascript const menuConfig = { title: "Order", // User did not include 'body' key buttonText: "Send", cancellable: true }; function createMenu(config) { let finalConfig = Object.assign( { title: "Foo", body: "Bar", buttonText: "Baz", cancellable: true }, config ); return finalConfig // config now equals: {title: "Order", body: "Bar", buttonText: "Send", cancellable: true} // ... } createMenu(menuConfig); ``` ## Não use ***flags*** como parâmetros de função ***Flags*** dizem ao seu usuário que a função tem mais de um uso. Funções devem ter apenas uma única utilidade. Divida suas funções se seguem padrões diferentes de código com base em um valor booleano. ### Não é recomendável: ```javascript function createFile(name, temp) { if (temp) { fs.create(`./temp/${name}`); } else { fs.create(name); } } ``` ### É recomendável: ```javascript function createFile(name) { fs.create(name); } function createTempFile(name) { createFile(`./temp/${name}`); } ``` ## Evite os Efeitos Colaterais (Parte 1) Uma função produz um efeito colateral se tem mais de um uso além de obter um valor e retorna outro(s) valor(es). Um efeito colateral pode ser a gravação em um arquivo, a modificação de alguma variável global ou a transferência acidental de todo o seu dinheiro a um estranho. Agora, se o seu programa precisa apresentar efeitos colaterais de vez em quando. Assim como o exemplo anterior, talvez você precise fazer gravação em um arquivo. O que você quer fazer é centralizar em um local o que você está fazendo. Não tenha várias funções e classes que gravem em um arquivo em particular. Tenha apenas um serviço para fazê-lo. Primeiro e único. O ponto principal é evitar armadilhas comuns como compartilhar estados entre objetos sem estrutura alguma, usar tipos de dados mutáveis que podem ser escritos por qualquer coisa e não centralizar onde acontecem seus efeitos colaterais. Se você tomar essas atitudes, será mais feliz do que a vasta maioria dos programadores. ### Não é recomendável: ```javascript // Variável global fazendo referência à função a seguir. /* Se temos outra função que usa esse nome, agora seria um vetor e poderia quebrá-lo. */ let name = "Ryan McDermott"; function splitIntoFirstAndLastName() { name = name.split(" "); } splitIntoFirstAndLastName(); console.log(name); // ['Ryan', 'McDermott']; ``` ### É recomendável: ```javascript function splitIntoFirstAndLastName(name) { return name.split(" "); } const name = "Ryan McDermott"; const newName = splitIntoFirstAndLastName(name); console.log(name); // 'Ryan McDermott'; console.log(newName); // ['Ryan', 'McDermott']; ``` ## Evite Efeitos Colaterais (Parte 2) No JavaScript, alguns valores não se modificam (são imutáveis) e alguns se modificam (são mutáveis). Objetos e vetores são dois tipos de valores mutáveis. Portanto é importante manejá-los com cuidado quando são passados como parâmetros para uma função. Uma função JavaScript pode mudar as propriedades de um objeto de alterar os conteúdos de um vetor, o que poderia facilmente causar ***bugs*** em toda parte. Imagine que existe uma função que aceita um vetor como parâmetro que representa um carrinho de compras. Se a função faz uma mudança no vetor do carrinho de compras - ao identificar um item para compra, por exemplo - então qualquer outra função que use o mesmo vetor cart será afetado por essa inclusão. O que pode ser bom e ruim. Vamos imaginar uma situação ruim: O usuário clica no botão Comprar que chama uma função `purchase` que dispara uma requisição de rede e manda o vetor `cart `para o servidor. Por causa de uma conexão de rede ruim, a função `purchase` continua tentando fazer a requisição. Agora, e se nesse meio tempo o usuário clica por acidente no botão Adicionar ao Carrinho de um produto que não quer na realidade antes que a requisição de rede comece? Se essa situação acontece e a requisição se reinicia, aquela função de compra enviará o item incluído por acidente porque o vetor `cart` foi modificado. Um boa solução para a função `addItemCart` seria sempre clonar o `cart`, editá-lo e retornar o clone. Essa solução garante que as funções que ainda estão usando o antigo carrinho de compra não sejam afetadas pelas mudanças. Duas condições dessa abordagem precisam ser mencionadas: Talvez existam casos nos quais você realmente queira modificar o objeto de entrada, porém quando adota essa prática de programação, descubrirá que esses casos são bem raros. A maioria das coisas podem ser refatoradas para não apresentarem efeitos colaterais! A clonagem de grandes objetos pode ser bem cara quanto ao desempenho. Felizmente, não é um grande problema na prática porque há ótimas bibliotecas que permitem com que essa abordagem de programação seja rápida e não tão intensa, em termos de memória, que se você clonasse manualmente objetos e vetores. ### Não é recomendável: ```javascript const addItemToCart = (cart, item) => { cart.push({ item, date: Date.now() }); }; ``` ### É recomendável: ```javascript const addItemToCart = (cart, item) => { return [...cart, { item, date: Date.now() }]; }; ``` ## Não escreva funções globais Elementos globais poluidores é uma prática ruim no JavaScript porque você poderia entrar em conflito com outra biblioteca e o usuário da sua API não saberia de nada até que obtivesse uma exceção em produção. Pensando em um exemplo: e se você quisesse estender um método de vetor nativo do JavaScript para obter um método `diff` que pudesse mostrar a diferença entre dois vetores? Você poderia escrever sua nova função para `Array.prototype` porém poderia entrar em conflito com outra biblioteca que tentasse fazer a mesma coisa. E se outra biblioteca estivesse usando `diff` somente para encontrar a diferença entre o primeiro e o último elementos do vetor? É por essas e outras que seria muito melhor usar apenas as classes ES2015/ES6 e simplesmente estender o global `Array`. ### Não é recomendável: ```javascript Array.prototype.diff = function diff(comparisonArray) { const hash = new Set(comparisonArray); return this.filter(elem => !hash.has(elem)); }; ``` ### É recomendável: ```javascript class SuperArray extends Array { diff(comparisonArray) { const hash = new Set(comparisonArray); return this.filter(elem => !hash.has(elem)); } } ``` ## Prefira a programação funcional à programação imperativa O JavaScript não é uma linguagem funcional do mesmo modo que o Haskell, porém tem um sabor funcional. Linguagens funcionais podem ser mais limpas e fáceis de serem testadas. Prefira esse estilo de programação sempre que puder. ### Não é recomendável: ```javascript const programmerOutput = [ { name: "Uncle Bobby", linesOfCode: 500 }, { name: "Suzie Q", linesOfCode: 1500 }, { name: "Jimmy Gosling", linesOfCode: 150 }, { name: "Gracie Hopper", linesOfCode: 1000 } ]; let totalOutput = 0; for (let i = 0; i < programmerOutput.length; i++) { totalOutput += programmerOutput[i].linesOfCode; } ``` ### É recomendável: ```javascript const programmerOutput = [ { name: "Uncle Bobby", linesOfCode: 500 }, { name: "Suzie Q", linesOfCode: 1500 }, { name: "Jimmy Gosling", linesOfCode: 150 }, { name: "Gracie Hopper", linesOfCode: 1000 } ]; const totalOutput = programmerOutput.reduce( (totalLines, output) => totalLines + output.linesOfCode, 0 ); ``` ## Encapsule condicionais ### Não é recomendável: ```javascript if (fsm.state === "fetching" && isEmpty(listNode)) { // ... } ``` ### É recomendável: ```javascript function shouldShowSpinner(fsm, listNode) { return fsm.state === "fetching" && isEmpty(listNode); } if (shouldShowSpinner(fsmInstance, listNodeInstance)) { // ... } ``` ## Evite condicionais negativas ### Não é recomendável: ```javascript function isDOMNodeNotPresent(node) { // ... } if (!isDOMNodeNotPresent(node)) { // ... } ``` ### É recomendável: ```javascript function isDOMNodePresent(node) { // ... } if (isDOMNodePresent(node)) { // ... } ``` ## Evite condicionais Parece ser uma tarefa impossível. Muita gente, ao escutar esse conselho, pergunta: "Como eu devo fazer qualquer coisa sem o `if`?!". A resposta é que você pode usar polimorfismo para alcançar o mesmo resultado em muitos casos. A segunda questão é: "Tudo bem, é legal, mas porque eu teria que fazer isso?!". A resposta vem de um conceito de código limpo que já aprendemos: uma função deve apresentar uma única utilidade. Quando você tem classes e funções com `if`, você está dizendo ao usuário que sua função tem mais de um uso. Lembre-se: apenas tenha uma única utilidade. ### Não é recomendável: ```javascript class Airplane { // ... getCruisingAltitude() { switch (this.type) { case "777": return this.getMaxAltitude() - this.getPassengerCount(); case "Air Force One": return this.getMaxAltitude(); case "Cessna": return this.getMaxAltitude() - this.getFuelExpenditure(); } } } ``` ### É recomendável: ```javascript class Airplane { // ... } class Boeing777 extends Airplane { // ... getCruisingAltitude() { return this.getMaxAltitude() - this.getPassengerCount(); } } class AirForceOne extends Airplane { // ... getCruisingAltitude() { return this.getMaxAltitude(); } } class Cessna extends Airplane { // ... getCruisingAltitude() { return this.getMaxAltitude() - this.getFuelExpenditure(); } } ``` ## Evite verificação de tipos (Parte 1) O JavaScript não tem tipo, o significa que suas funções podem levar qualquer tipo de argumento. Às vezes você pode ser bicado por essa liberdade toda e torna-se tentador verificar tipos em suas funções. Há várias formas de evitar essa atitude. O primeiro ponto a ser considerado são APIs consistentes. ### Não é recomendável: ```javascript function travelToTexas(vehicle) { if (vehicle instanceof Bicycle) { vehicle.pedal(this.currentLocation, new Location("texas")); } else if (vehicle instanceof Car) { vehicle.drive(this.currentLocation, new Location("texas")); } } ``` ### É recomendável: ```javascript function travelToTexas(vehicle) { vehicle.move(this.currentLocation, new Location("texas")); } ``` ## Evite verificação de tipos (Parte 2) Se você está trabalhando com valores primitivos básicos como cadeias de caracteres e números inteiros, você deve considerar o uso do TypeScript. É uma excelente alternativa ao JavaScript regular, uma vez que fornece tipos estáticos em cima da sintaxe padrão do JavaScript. O problema como a verificação normal do JavaScript é que desempenhá-la bem exige muita verbosidade extra de modo que a falsa sensação de "tipos seguros" obtida por você não compensa a perda de facilidade de leitura. Mantenha seu código JavaScript limpo, escreva bons testes e tenha boas revisões de código. Do contrário, faça tudo isso mas com TypeScript (como eu já disse, é uma ótima alternativa!) ### Não é recomendável: ```javascript function combine(val1, val2) { if ( (typeof val1 === "number" && typeof val2 === "number") || (typeof val1 === "string" && typeof val2 === "string") ) { return val1 + val2; } throw new Error("Must be of type String or Number"); } ``` ### É recomendável: ```javascript function combine(val1, val2) { return val1 + val2; } ``` ## Não exagere na otimização Navegadores modernos executam um monte de otimizações por debaixo dos panos. Muitas vezes se você os otimiza está apenas perdendo seu tempo. Há bons recursos para verificar onde a otimização está ausente. Mire-as neste meio tempo até que estejam resolvidas se puderem. ### Não é recomendável: ```javascript for (let i = 0, len = list.length; i < len; i++) { // ... } ``` ### É recomendável: ``` for (let i = 0; i < list.length; i++) { // ... } ``` ## Remova código morto Código morto é tão ruim quanto código duplicado. Não há razão para mantê-lo na sua base de códigos. Se não é chamado, livre-se dele! Esse código ainda estará seguro no histórico da sua versão se ainda for necessário. ### Não é recomendável: ```javascript function oldRequestModule(url) { // ... } function newRequestModule(url) { // ... } const req = newRequestModule; inventoryTracker("apples", req, "www.inventory-awesome.io"); ``` ### É recomendável: ```javascript function newRequestModule(url) { // ... } const req = newRequestModule; inventoryTracker("apples", req, "www.inventory-awesome.io"); ``` E aí? Gostaram? Até a próxima tradução! 🤗
ananopaisdojavascript
805,169
how to make crud by reactjs
A post by NADER-001cv
0
2021-08-27T11:37:19
https://dev.to/nader001cv/how-to-make-crud-by-reactjs-lic
nader001cv
805,202
O que é uma Gem?
O que é uma Gem? Gem é um pacote que oferece funcionalidades a fim de resolver uma...
0
2022-01-01T18:38:52
https://dev.to/dnovais/gems-ruby-3ine
braziliandevs, ruby, rails
## O que é uma Gem? Gem é um pacote que oferece funcionalidades a fim de resolver uma necessidade específica de um programa Ruby. Pense como o conceito de biblioteca em outras linguagens de programação. Para instalar uma gem execute em seu terminal. ```ruby gem install cpf_cnpj ``` Podemos listar todas as gems instaladas ```ruby gem list ``` Vamos usar a gem que instalamos como exemplo... ```ruby require "cpf_cnpj" CPF.valid?(number) # Check if a CPF is valid CPF.generate # Generate a random CPF number CPF.generate(true) # Generate a formatted number cpf = CPF.new(number) cpf.formatted # Return formatted CPF (xxx.xxx.xxx-xx) cpf.stripped # Return stripped CPF (xxxxxxxxxxx) cpf.valid? ``` ### RubyGems - Repositório (site) de gems [RubyGems.org](http://rubygems.org/) é o serviço de hospedagem de gem da comunidade Ruby. Onde você também pode criar e publicar suas gems (em breve irei fazer um post passo a passo para criar uma gem). **Contato:** Email: contato@diegonovais.com.br LinkedIn: https://www.linkedin.com/in/diegonovais/ Github: https://github.com/dnovais
dnovais
805,205
DativeJs version 2 has been released
DativeJs has released it's version 2 The version 2 has a directives options...
0
2021-08-27T12:17:52
https://dev.to/tobithealpha/dativejs-version-2-has-been-released-nhm
dativejs, framework, javascript, node
DativeJs has released it's version 2 The version 2 has a directives options now https://dativejs.js.org
tobithealpha
805,209
GraphQL APIs with Quarkus
A query language for your API In this article, I'll show you Quarkus GraphQL support. As an example,...
14,343
2021-08-30T07:54:35
https://claudioaltamura.de/api/graphql-apis-with-quarkus
java, graphql
**A query language for your API** In this article, I'll show you Quarkus GraphQL support. As an example, I use the Superheroes application from my previous articles. We will discuss some GraphQL topics. ## Code, dependencies and model The source code for this app is available on [Github](https://github.com/claudioaltamura/quarkus-graphql-superheroes"). If you like, you can try the examples by yourself. As dependencies, I included e.g. SmallRye GraphQL and lombok. Here you can have a detailed look at the [pom.xml](https://github.com/claudioaltamura/quarkus-graphql-superheroes/blob/main/pom.xml) file. Quarkus helps you to create GraphQL APIs. The GraphQL schema is going to be generated. You just have to define your model. Here I show you as an example the Superhero data transfer object. I use DTOs to expose data from an API. Lombok `@Data` takes care of getter, setter, toString, and the equals and hashCode methods. ``` import lombok.Data; @Data @FieldDefaults(level = AccessLevel.PRIVATE, makeFinal = true) public class Superhero { String name; City city; } ``` ## Fetching data To query all cities you just have to send a command like this to the GraphiQL UI http://localhost:8080/q/graphql-ui/ . ``` { allCities { name } } ``` And with GraphQL it's quite easy to fetch object graphs. For example, we could query a city with their superheroes like this. ``` query getCity { city(cityId: 0) { name symbol superheroes { name } } } ``` ## Resolver and mutations on the server-side A resolver is responsible for defining queries. All Queries are located in `SuperheroResolver`. ``` @GraphQLApi public class SuperheroResolver { @Inject SuperheroService superheroService; @Query("allCities") @Description("Get all cities.") public List<City> getAllCities() { return superheroService.getAllCities(); } ... } ``` I have separated the mutations from the queries. Mutations are write operations like create, update or delete. Here I show the create() method from `SuperheroMutation` with SuperheroInput as an input object. ``` @GraphQLApi public class SuperheroMutation { @Inject SuperheroService superheroService; @Mutation public Superhero createSuperhero(@Name("superhero") SuperheroInput superheroInput) { var superhero = new Superhero(superheroInput.getName(), superheroInput.getCity()); superheroService.addSuperhero(superhero); return superhero; } ... } ``` ## Testing GraphQL APIs It's pretty cool that Quarkus automatically generates a GraphQL schema based on your source code. To display the schema, just invoke http://localhost:8080/graphql/schema.graphql . Here I want to show you quickly, how to write automated tests. How do we test a GraphQL API? Here comes [Rest-Assured](https://rest-assured.io/) to the rescue. You can write tests in a manner as you already know from REST. ``` @QuarkusTest public class SuperheroTest { @Test void allCities() { final Response response = given() .contentType(ContentType.JSON) .body("{\"query\":\"{\\n allCities{\\n name\\n}\\n}\"}") .when() .post("/graphql") .then() .assertThat() .statusCode(200) .and() .extract() .response(); final List<City> allCities = response.jsonPath().getList("data.allCities", City.class); assertThat(allCities) .isNotEmpty() .hasSize(2) .extracting(City::getName) .contains("Gotham City", "New York City"); } } ``` ## Conclusion I like the GraphQL support from Quarkus. It's great that the GraphQL schema is generated automatically through code and annotations. In the next part I'll show you how to test you GraphQL API with curl, the GraphiQL tool and insomnia. *Photo by [Raphaël Biscaldi](https://unsplash.com/@les_photos_de_raph?utm_source=unsplash&amp;utm_medium=referral&amp;utm_content=creditCopyText) on [Unsplash](https://unsplash.com/s/photos/graph?utm_source=unsplash&amp;utm_medium=referral&amp;utm_content=creditCopyText)* **Links** https://github.com/claudioaltamura/quarkus-graphql-superheroes https://quarkus.io/guides/smallrye-graphql https://rest-assured.io/
claudioaltamura
805,222
How to save and fetch data in localstorage in redux toolkit?
A post by Joseph Uzuegbu
0
2021-08-27T13:03:26
https://dev.to/josephuzuegbu/how-to-save-and-fetch-data-in-localstorage-in-redux-toolkit-58f0
josephuzuegbu
805,387
Typewriter Effect with CSS
I tried to come up with my own CSS-only version of a typewriter effect.
14,440
2021-08-27T22:13:36
http://alvaromontoro.com/blog/67987/typewriter-effect-with-css
css, html
--- title: Typewriter Effect with CSS published: true description: I tried to come up with my own CSS-only version of a typewriter effect. tags: css, html cover_image: https://dev-to-uploads.s3.amazonaws.com/uploads/articles/4o14zoz8uuqik5u7mazp.gif canonical_url: http://alvaromontoro.com/blog/67987/typewriter-effect-with-css series: CSS Typewriter Effect --- A [reddit user asked in the CSS channel](https://www.reddit.com/r/css/comments/pc0pkf/any_of_you_guys_know_how_to_do_that_type_writer/) if there was a way of building a typewriter effect. Some people pointed out at [Geoff Graham's article on CSS Tricks](https://css-tricks.com/snippets/css/typewriter-effect/) (which includes different versions in CSS and JS), and many more recommended using JavaScript or some JS libraries/modules... and I tried to come up with my own [CSS-only version](https://codepen.io/alvaromontoro/pen/rNwVpdd): {% codepen https://codepen.io/alvaromontoro/pen/rNwVpdd %} The idea is to animate the `content` property of a pseudo-element like `::before` to show one character at a time. And then, we can use the `::after` element to display a blinking caret. The `content` property is discretely animatable. This means that there won't be transitions –it would have been nice–, but it will still animate it "step by step," which it's exactly what we want. It is not perfect, but it can be eye-catchy, and it has some nice pros compared to similar CSS-only solutions. Also, it is slightly customizable (the caret can change color and size), and I tried to make it as accessible as possible. The main issue is calculating the steps and the time at which they must happen. To simplify and generalize the process, I created a short JavaScript snippet to help generate the animation steps for any set of words... Unfortunately, although it works in most cases, my math is wrong, and it sometimes fails. (I'll add a link once I verify it works fine.) ## Pros and Cons Pros of this approach: - It is multiline: many of the CSS-only typewriter animations only work for single lines/words. This one will work in multiple lines too. - It doesn't cut letters/words: each letter is added individually instead of hiding with overflows that may display them partially (as it happens in other solutions). - No need for monospace fonts: related to the point above. Other animations only work with monospace to go around the cutting words/letters issue. This one will work with non-monospace fonts too. Cons of this approach: - Requires some accessibility boost (see below): in my defense, most animations that do this (CSS or JS) have this issue. - It involves a lot of code: the CSS animation will have as many lines as letters are in total... And it is a pain to write them: a lot of calculations! So I created a small script to generalize the process. - Not supported by all browsers: the animation of the pseudo-elements is not supported by some browsers (most notably, Safari on Mac and iOS.) To go around this last part, maybe I could have used the `steps()` timing function. But in the end, it would require some (simpler) calculations too. ## Accessibility We are going to do a couple of things to boost the accessibility of this animation... and one of them consists of removing the animations 😅 First, while a sighted user can see the text changing, that may not be the case for a user of assistive technologies (AT). For example, a screen reader user won't get information about the text growing/shrinking –and thank you, because it would be a pain in the neck! To avoid getting a half description of the title, we should add an `aria-label` to the container with the full description. ```html <h1 aria-label="I'm a developer, writer, reader, and human."> I'm a&nbsp; <span class="typewriter"></span> </h1> ``` Without the `aria-label`, screen readers will read the title as "_I'm a_"; with the `aria-label`, they'll read "_I'm a developer, writer, reader, and human._", which is much better. The other thing we can do to make the component a bit more accessible is to remove the actual animations. If a user has the reduced motion setting on, we should stop the caret blinking, leave it fixed, and maybe show the words fully instead of letter by letter. To do so, CSS counts with the `prefers-reduce-motion` media query: ```css @media (prefers-reduced-motion) { /* let the caret be fixed instead of blinking */ .typewriter::after { animation: none; } /* replace the letter popup for a shorter animation */ @keyframes sequencePopup { 0%, 100% { content: "developer"; } 25% { content: "writer"; } 50% { content: "reader"; } 75% { content: "human"; } } .sequencePopup::before { content: "developer"; animation: none; } } ``` We didn't fully remove the animation; we only replaced it with another that is more accessibility-friendly. Not all animations are bad, and "reduced motion" doesn't mean "no motion."
alvaromontoro
805,507
5 VSCode Extensions I Use Every Day
Here are five VSCode extensions I like and use daily 😀 1. Peacock This lets you change...
0
2021-08-27T16:35:46
https://dev.to/allthecode/5-vscode-extensions-i-use-every-day-19jb
webdev, beginners, vscode, codenewbie
Here are five VSCode extensions I like and use daily 😀 ## 1. Peacock This lets you change the colour of individual VSCode windows. Great for when you have many open and want to easy differentiate between Frontend, Backend and Types for example. It puts the settings in you .vscode file so if you're on a team make sure to add that to your .gitignore. ![Peacock VSCode extension](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/9btqsd9umtkp28hcbpfv.jpg) ## 2. Code Spell Check My spelling isn't great and my typing tends to have typos, [this extension](https://marketplace.visualstudio.com/items?itemName=streetsidesoftware.code-spell-checker) puts a little blue squiggle under each misspelt word so you can see. It's subtle because unlike normal prose it's very common for developers **toWriteThingsInAnOddWay** that are actually valid, spelling errors aren't as important as linting errors and the extension maker knows that. ![Code Spell Check extension](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/8lmpous0t4b31xs7h5ee.png) ## 3. Material Icon Theme The stock icon theme is a bit dull I think, jazz it up a bit with [this extension](https://marketplace.visualstudio.com/items?itemName=PKief.material-icon-theme). Thanks to [Maximilian Schwarzmüller](https://twitter.com/maxedapps) for using this in his videos and recommending it. ![Material UI Icons](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/m68gyc7sl98pp9xhnbes.png) ## 4. Rainbow CSV I don't know about you but I don't trust Excel or Numbers with CSVs, I prefer to look at them in plain text, but my eyes hate me for it! [This extension](https://marketplace.visualstudio.com/items?itemName=mechatroner.rainbow-csv) makes each column in your CSV the same colour so it's easier for your brain to parse what I going on. ![Rainbow CSV VSCode Extension](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/8l88esoovg0lqooi59oa.png) ## 5. Serendipity Theme I love this [theme](https://marketplace.visualstudio.com/items?itemName=wicked-labs.wvsc-serendipity), it launched on Product Hunt in July and it think it's beautiful, so did everyone else as it was product of the day! It also sorted out the flickering issues I was having with VSCode which is a nice relief on my eyes as well. ![Serendipity VSCode theme](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/v1zjsu9254tdtrnc4qos.png) ## Reel time I made this as a reel a while back on Instagram as well! {% instagram CSJwyV3jlp7 %}
allthecode
805,525
Reasons To Use Recursion and How It Works
Hello Engineers Today, I will talk about recursion in what, why, and how. What is...
0
2021-08-27T17:04:19
https://dev.to/manarabdelkarim/why-and-how-to-solve-iterative-problems-recursively-the-smart-coding-4nj2
python, algorithms, programming, beginners
#### Hello Engineers Today, I will talk about recursion in what, why, and how. What is recursion , why to use it, and how to solve problems with it. The examples will be in Python since Python is easy to understand and close to the algorithms .. Shall we start ? ![recursion](https://media1.giphy.com/media/H4DjXQXamtTiIuCcRU/200.gif) ### What is recursion? A more complex definition of recursion is: a technique that solve a problem by solving a smaller problems of the same type . We can simplify the definition by saying that recursion is a function that calls itself directly or indirectly. Don't worry for now, it will be much clearer when we start writing our examples. ### Why to use recursion? I choose this question over "when to use recursion" because many learners who studied recursion wanted to know why to use it since that all the problems we can solve in recursion , we can also solve it in normal iterative loops! So here is my answer: **1- Learning recursion makes you a better programmer:** Learning and practicing recursion helps you improve your problem solving skills, because you will learn how to break down bit problems into smaller ones. Also, you will learn the principle of stack in data structure (A stack is an abstract data type that holds an ordered, linear sequence of items), the principle of LIFO (Last In First Out) and how to make use of the call stack. **2- Using recursion makes the code clearer:** Recursion code is simpler and shorter than an iterative code. The recursion function will be written in less lines of code and will be easier for debugging. **3- Recursion is data structure's best friend:** As I mentioned above, recursive functions use the call stack of the interpreter. So, we can make use of the existing of call stack instead of writing code and creating a stack by ourselves or by using any external libraries. which means we can use recursion whenever we want to use stack. Two good implementation examples for using recursion in data structures are trees and graphs in-depth traversal. ### How to write recursive functions? Before writing a recursive function ,let's talk about a few factors to be determined : **1- Determine the size factor:** The size factor means that your problem should not exceed your static value or your memory allocation for that particular program. In simple language your program should not have large numbers and not too many iterations. Because again, recursion functions use call stack and the call stack has a limit. When the stack becomes full the program will crash and you will have an error. ![recursionerror](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/nabxiju4v37hs5pnbq81.png) **2- Determine the base case/s:** The base cause could be a single or multiple values depending on your program. I will use a while loop here to explain the base case .. if we want to write a program that print "hello world" 5 times using while, we will write: ``` def display_hello(i): while(i > 0): print("hello world") i -=1 ``` The base cause determines when the loop will stop .. in our example the base cause is i=0 because when the value of i becomes zero the loop will break and stop. Base case in recursion is that particular value that if we reach we want to stop recalling of the function and start removing and executing every function in the call stack. Not having a base cause will make the function call itself until the call stack becomes full and the program crashes. Also, having a wrong base cause will result to a wrong output. ![base cause](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/z8zs2lqtl47178g04q46.png) **3- Determine the general case/s:** General cause is the one where the problem expressed as a small version of itself. Which means, the program will continue iterate the general causes until it reaches the base cause In our example above, when i=0 considered as the base cause and we send 5 as a parameter , then we can think of: i=1, i=2, i=3, i=4, and i=5 as the general causes. Now, let's Write a recursive function and trace it using the previous problem: We want to write a function that write "hello world" 3 times: Let's analyze the problem: The function will check the base cause, if the current case doesn't match the base cause then the function will call itself one time .. So the increasing is a liner (it could be O(n)) (it will be probably safe for the call stack size) let's try writing our function now by using our while loop example **1- The base cause -> i =0** ``` def display_hello(i): if i>0: ``` **2- The print command -> print("hello world")** ``` def display_hello(i): if i>0: print("hello world") ``` **3- The changes in every iteration -> i-=1** to send the new value of the variable to the next function call we have to write it as a parameter ``` def display_hello(i): if i>0: print("hello world") display_hello(i-1) ``` ![recursion](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/jwk5w9akkavmuzy0f5j2.png) And that's it for this small problem .. Before tracing it let's add one print command after the function call and show the result at the end to make the tracing more interesting **Assuming that the first invocation was :** ``` display_hello(3) ``` **And our function is :** ``` def display_hello(i): if i > 0: print("hello world!") display_hello(i-1) print(f'The i value is {i}') ``` **Now we will trace it.** In the first call the function will enter the call stack ![recursion](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/vj8mo5zuuekz4ayia490.png) Then the program will execute the commands : ![recursion](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/a8dhpz3jf0qgvl9v2gre.png) When the execution reaches line 4 (the function recall) it will stop there (it will pause the execution of the rest commands) and add another function to the stack : ![recursion](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/x1m5v7och63bnjfzpz57.png) Then the program will execute the commands in the second recalled function : ![recursion](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/93hjilm0ibrga4z42jpq.png) Again , when the execution reaches line 4 (the function recall) it will stop there (it will pause the execution of the rest commands) and add another function to the stack : ![recursion](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/kg7tpzmyzh69a3liujba.png) For this time too , our base cause has not satisfied yet because i is still bigger than zero, so the execution will continue until the function recall and then adds another function to the stack. ![recursion](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/t0yt5qcq5omqrlzlnvob.png) Now finally the parameter is 0 which is the value of i ![recursion](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/0uhuk6ibng237irnxeie.png) The execution will start until line 2 because the condition says that i should be bigger than zero, but i is equal to zero .. So we reached the base cause and we will not reach the recall "invocation" and the prints ![recursion](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/g5q8yflb26t7hp8jam6w.png) Because this function finished all the commands that should be executed, it's the time to pop the function out of the stack : ![recursion](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/60xym2sjxt6lucmn060w.png) Now we returned to the previous function when the parameter was 1 so now the program will execute the rest of the command/s: ![recursion](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/jiwaywbpajqg722pzr7r.png) The function now is completed all the commands that should be executed, time to pop the function out of the stack : ![recursion](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/x1m5v7och63bnjfzpz57.png) Now we returned to the function that its parameter is two and we will execute the rest of the commands : ![recursion](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/x58hd9upkojv3jz2wdqk.png) Again, after we done the execution we will remove the function from the stack: ![recursion](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/vj8mo5zuuekz4ayia490.png) Now we have the first call which 3 was its parameter, and we will execute the rest of the commands: ![recursion](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/hg29vx3sqw27rno8od1q.png) And here the last function will pop out from the stack and the call stack will become empty and here is the end of our program: ![recursion](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/sajlfw27cr15rk1p2r9d.png) Let's check if our tracing was right by executing the code : ![recursion](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/lrfucdwiwjwclpofp57t.png) So here we reach the end of today's article ## Happy recursion 😁 ### Happy recursion 😁 #### Happy recursion 😁 ##### Happy recursion 😁 ###### Happy recursion 😁 #### Author Note: I didn't use Fibonacci as an example because I believe that it is not a good example for teaching recursion and recursion is one of the worst solutions to solve Fibonacci in terms of both time and space. View this article [Fibonacci without recursiveness in Python - a better way](https://dev.to/joaomcteixeira/fibonacci-without-recursiveness-in-python-a-better-way-4hm) ### References: - [Recursion](https://www.geeksforgeeks.org/recursion/) - [Recursion: The Pros and Cons](https://medium.com/@williambdale/recursion-the-pros-and-cons-76d32d75973a) - [Learn All About Recursion in Python and C++ - Udemy](https://www.udemy.com/course/recursion-in-python-and-c/)
manarabdelkarim
805,530
#100daysofcode [Day-14]
100daysofcode [Day-14] I'm trying to gain more knowledge about ES6 and today I've learnt...
0
2021-08-27T17:18:56
https://dev.to/alsiam/100daysofcode-day-14-48a9
100daysofcode, javascript, beginners, webdev
#100daysofcode [Day-14] I'm trying to gain more knowledge about ES6 and today I've learnt es6 filter, destructuring, map, forEach and something more. ![Alt Text](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/axhgij23gt4hg0lgiu95.png)
alsiam
805,535
Survey Page: using form element.
A post by AyushRaghuvanshi
0
2021-08-27T17:31:50
https://dev.to/ayushraghuvanshi/survey-page-using-form-element-620
codepen
{% codepen https://codepen.io/hashrag0308/pen/wveaVaw %}
ayushraghuvanshi
805,541
¿Qué es un algoritmo?
¿Sabías que muchas de las funciones que realizamos en nuestro día a día es un algoritmo? Por ejemplo,...
0
2021-08-27T18:06:44
https://dev.to/joseltoro/que-es-un-algoritmo-4168
algoritmo, algorithms
¿Sabías que muchas de las funciones que realizamos en nuestro día a día es un algoritmo? Por ejemplo, el seguir los pasos para preparar la receta de algún postre, instalar una impresora en la oficina, lavar los utensilios sucios, levantarse temprano todos los días para preparar el desayuno, o cualquier otra función que contemple una secuencia de pasos, vendría a ser un algoritmo. ¡Que no te sorprenda que tu vida esté llena de algoritmos! Y en este primer tema les voy a explicar el porqué de ello y lo que tal vez estés pensando, qué tiene que ver el preparar una receta o el instalar una impresora con los algoritmos y la programación. ¡Comencemos! Al escuchar la palabra “algoritmo”, seguramente viene a nuestra cabeza los algoritmos que veíamos en el colegio como, por ejemplo: el algoritmo de Euclides para calcular el máximo común divisor de dos números, la misma multiplicación es un algoritmo para obtener un producto, o la división para determinar el cociente de dos números. Yendo un poco más a nivel universitario, tenemos el método simplex para la optimización de problemas que lo enseñan en el curso de IOP (Investigación de Operaciones). Todos estos son algoritmos, pues siguen una serie de operaciones para obtener un resultado. Así como estos algoritmos puedo mencionarles muchos otros que son de gran utilidad para la educación, para el trabajo, para las empresas y para la vida misma, ya que nos facilitan las cosas y nos permiten solucionar diferentes tipos de problemas. Creo que ya te vas dando una idea de para qué sirve un algoritmo, sino pues definamos de manera muy sencilla qué es un algoritmo. **¿Qué es un Algoritmo?** Un algoritmo es una secuencia ordenada y finita de pasos que permiten resolver un problema. Dicho de otro modo, es un método que será expresado en un conjunto de pasos para resolver un problema. ¿Y qué tiene que ver esto con la programación? Pues que dicho método puede ser implementado en un programa de computadora que satisfaga las necesidades de las personas. **¿Qué es un programa de computadora?** Un programa de computadora es la implementación de un algoritmo en un determinado lenguaje de programación como, por ejemplo: Java, C, C++, .NET, PHP, GO, etc. En la siguiente imagen se puede ver la relación clara que existe entre problema, algoritmo y programa. ![image](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/s92bglazkby1fnbj074z.png) Espero que este pequeño post haya sido de su agrado, nos vemos en una siguiente oportunidad. Saludos y que tengan un buen día.
joseltoro
805,716
A New Way To Use Apple Mail For Email Sanity 🤯
This article is intended for apple users -- as the primary email application that will be...
0
2021-08-27T20:05:45
https://dev.to/louismin/a-new-way-to-use-apple-mail-for-email-sanity-92d
productivity, tutorial, ios, ipad
###### *This article is intended for apple users -- as the primary email application that will be used is the Apple Mail app. In this article, you'll learn about a workflow I use to follow the Inbox Zero approach without having to navigate between different apps.* --- ## TL;DR Apple Mail can be used as an "email aggregator" that works as a holistic app for you to handle all your incoming emails from Gmail, Outlook, *[insert other email service providers]*, etc. **In a nutshell, the "magic sauce" is a mixture of the email forwarding feature all email service providers have and the Apple ecosystem with Apple Mail**. The workflow requires all emails to be forwarded to your iCloud email address. After that, the only job to do is to follow an Inbox Zero approach *(keeping your inbox empty or almost empty)* for your iCloud Inbox. Yes, it's really that simple 🤷‍♂️. In this article, I'll go into further details about why using Apple Mail and basic email forwarding can significantly improve the way you handle your emails. --- Before diving in, keep in mind some of these pros and cons I've experienced using this workflow: ### Pros: * Takes advantage of the Apple ecosystem * Reduces the number of apps you need to manage your emails with * Doesn't rely on a 3rd-party service (often a paid service) to aggregate your emails * Keeps a "backup" of your original emails * Easier to follow the Inbox Zero approach * On macOS, Apple Mail automatically sets the correct email address to reply from ### Cons: * Tedious initial setup -- depends on how many email accounts you need to add to your device(s) (personally, I had 8 email accounts I had to set up on 4 devices -- iPhone, iPad, Mac Pro, MacBook Pro) * iCloud Mail service downtime (I haven't experienced this, but thought I should include this based on some google results talking about this issue) * On iOS and iPadOS, Apple Mail doesn't automatically set the correct email address to reply from (other email apps don't as well) --- ## Let's Get Started! <br/><br/> ### 1. Create iCloud Email Address & Enable If you haven't already done so, you'll need to create your iCloud email address and enable iCloud Mail in your iCloud account. If you're on macOS, you can set up your iCloud email address by going to Internet Accounts from System Preferences and enabling Mail from your iCloud account. If you're on iOS or iPadOS, enabling iCloud Mail in your iCloud account will prompt you to create an email. ![On macOS, go to Systems Preferences to access Internet Accounts (left). On iOS & iPadOS, go to Settings then iCloud to access iCloud Mail (right)](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/pnnx2qpn5bsbirm17ooa.png) ###### *On macOS, go to Systems Preferences to access Internet Accounts (left). On iOS & iPadOS, go to Settings then iCloud to access iCloud Mail (right).*<br/><br/> ### 2. Add All Email Addresses To Your Device(s) For each device, you'll have to add all your Gmail, Outlook, etc. email accounts. For macOS, you can do so by going to Internet Accounts (make sure these accounts are enabled by going to the Mail app preferences). For iOS and iPadOS, navigate to Apple Mail under settings and tap Accounts. ![On macOS Apple Mail, navigate to accounts and make sure "enable this account" checkbox is selected for all email addresses.](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/xe2yvkarp7tmqvd422r5.png) ###### *On macOS Apple Mail, navigate to accounts and make sure "enable this account" checkbox is selected for all email addresses.*<br/><br/> ### 3. Forward All Email Addresses To iCloud Email With your iCloud email address created and email accounts added to your device(s), it's time to start forwarding all your other email address to iCloud. For brevity, I've only included images of the steps to take for Gmail. The steps should be similar for other email service providers. ![Click the gear icon to access all settings (left). From the Settings page, navigate to "Forwarding and POP/IMAP" to add a forwarding email address (right)](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/9zhdir4dqc2kp6njxfla.png) ###### *Click the gear icon to access all settings (left). From the Settings page, navigate to "Forwarding and POP/IMAP" to add a forwarding email address (right).*<br/><br/> Once you've added a forwarding email address, click Forward a copy of incoming mail to and select the iCloud email address. After doing so, you'll have the option to: - Keep Gmail's copy in the Inbox - Mark Gmail's copy as read - Archive Gmail's copy - Delete Gmail's copy If you want to keep a "backup" of your emails, don't select Delete Gmail's copy. This is just personal preference. Any other option, when enabled, will keep the original email even if you delete the forwarded email from your iCloud Inbox. ### 4. Organize Apple Mail After forwarding all your emails, it's time to start organizing Apple Mail to your liking. The placement and settings for each inbox in Apple Mail is device-dependent, so you'll have to repeat this process for each device. For reference, I've included an image below of my sidebar configuration: ![My macOS Apple Mail sidebar](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/7z9mu6t0imk35i8o8r8q.png) ###### *My macOS Apple Mail sidebar*<br/><br/> For this workflow, the main objective is to reach Inbox Zero from your iCloud Inbox. So, I moved the iCloud email account towards the top and minimized all other email accounts. It's important to note that for consistency, all email actions from replying to deleting should be done only in the iCloud Inbox. ### 5. Delete Old Email Apps 🎉 Finally! It's time to delete your old email apps and be on your way to reaching Inbox Zero! --- ## FAQs ### Why forward emails to an iCloud email instead of just adding email accounts to Apple Mail? > One of the major issues of using email services providers with Apple Mail, specifically for iOS and iPadOS, is how data is received (i.e. how you get a new email notification). Because push notification is no longer supported, the only methods available are fetch and manual. This means that notifications won't show up in real-time. You can set the data to be fetched manually at a 15 minute interval but this would lead to battery drain and more data usage. The benefits of push are real-time notifications, less battery drain, and less data usage. So, you need an iCloud email for Apple Mail to have push notifications. ### Why not use the Gmail/Outlook app to manage multiple emails? > You can! But there's one caveat for Gmail -- no Gmail app on the Mac App Store. This means that for macOS, you'll have to stick to juggling between different windows and tabs to access all your Gmail accounts. ### Does this workflow trap you in the Apple ecosystem? > No. Rather than replacing your email accounts to a single iCloud email address, this email workflow describes a method of "email aggregation" to easily follow the Inbox Zero approach. Also, when you're on a non-Apple device, you can always manage your iCloud email from [Apple's iCloud home page](https://icloud.com). --- ## ⭐️ Bonus Tip: Custom Email Signatures A cool feature of Apple Mail on macOS is Apple Mail's ability to automatically set the correct email address to respond from (this also means a custom signature you set for your email address will be used!). To set your custom signatures on iOS and iPadOS, head over to Apple Mail under settings and select Signatures. After doing so, select Per Account -- if you have different signatures for different email addresses. For macOS, go to Apple Mail's preferences page and select the Signatures tab. If you're using a styled signature, make sure to uncheck Always match my default message font before pasting your signature to retain your custom layout and font styles. ![On macOS, go to Signatures tab under Apple Mail preferences (left). On iOS & iPadOS, go to Apple Mail under settings and tap "Per Account" for email-specific signatures (right).](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/f22v6kf9mg849clrsy9a.png) ###### *On macOS, go to Signatures tab under Apple Mail preferences (left). On iOS & iPadOS, go to Apple Mail under settings and tap "Per Account" for email-specific signatures (right).*<br/><br/> --- ## Author's Note > Thank you for taking the time to read about an email workflow that I've been using to manage my personal and work email addresses. Personally, I've disciplined myself to keep my iCloud Inbox empty by the end of the day. In doing so, this has made a huge impact on my overall productivity. I'm excited to share my email workflow and I would love to hear about your email workflow in the Discussion below! > -Be Positive. Stay Productive.-
louismin
805,723
Git vs. GitHub: What's the difference?
Git or GitHub. Are they the same/equal thing? If not, are they connected/related. The...
0
2021-08-27T20:37:20
https://dev.to/shivangisharma01/git-vs-github-what-s-the-difference-ko4
git, github
###Git or GitHub. Are they the same/equal thing? If not, are they connected/related. The veracity is that Git and GitHub are connected far more closely than you think they're, but with some key differences setting them apart. What's the difference between Git and GitHub? Well to know that first we will take a deep-examine at each one. But before we do that you need to know the concept of *version control*. ###So now what is Version control? Version control is *like a correction tape* for your program. It's work is to save program for your project. It tracks and logs the changes you make to your file sets over time, it gives you the power to review and even restore your earlier versions of your work. If you notice that your text is misaligned so rather than crawling back through every line of your code, you'll use the version control to reload earlier version of your code, until you find it satisfactory or correct. ######Now let's flow directly to *Git*. ###What is Git? It was first developed back in 2005. Git is immensely popular and high-quality version of control system. Git is installed on your *local system* and keeps all the record of your ongoing program versions. you do no need any internet access to use it except if you want to download it. Git is extremely easy to use and it is not paid, hence inexpensive. It also has a branching model which allow user to make their own independent local branches, so that you can try out new ideas but without making changes in your main branch and you can anytime merge, delete and recall them. ###What is GitHub? GitHub is Git repository hosting service. It is entirely *cloud-based*, totally distinct from git which only allows you to control your projects in your local server/computer. GitHub is like an online storage of git , in technical words the database of projects you are working on in your local server it is being saved on the cloud in GitHub. Which allows you and any authorized person by you to see the work or contribute in that project. Like Git, GitHub also has the branching system which makes it smooth to try different approach's and distinct the work of other person from you so that it does not create any heap. You can excess your work from anywhere in the world just with connectivity of internet. ###Conclusion To conclude Git is a version control system installed on your local system and it keep track of all your work and stores it on local device storage whereas GitHub is a solely cloud-based and a Git repository hosting service. You can push your work from local storage to cloud through internet and access the data from anywhere.
shivangisharma01
805,726
The Phoenix Project by Gene Kim
The Phoenix Project is a fantastic book that is both a professional book aiming to guide teams and "a...
0
2021-08-28T12:34:24
https://www.sandordargo.com/blog/2021/08/28/the-phoenix-project-by-gene-kim
books, watercooler, management
[The Phoenix Project](https://www.amazon.com/gp/product/1942788290/ref=as_li_qf_asin_il_tl?ie=UTF8&tag=sandordargo-20&creative=9325&linkCode=as2&creativeASIN=1942788290&linkId=fc9c78132b98763cc56dca36a783a5f4) is a fantastic book that is both a professional book aiming to guide teams and *"a **novel** about IT, DevOps, and how to help your business win"*. It's written in a style I love the most and I think we have a clear lack of this type of book. It offers both what I'd look for in fiction and in non-fiction books. The author is a great storyteller, he makes you not want to put the book down, not only because you want to learn about DevOps and how to organize properly a modern organization, but also because you are interested in how the story unfolds. Whether the CISO commits suicide or just leaves the city without notifying anyone from the organization or if the main character actually finds another job instead. The only book of similar style is [Code Ahead by Yegor Bugayenko](https://www.amazon.com/gp/product/1982063742/ref=as_li_qf_asin_il_tl?ie=UTF8&tag=sandordargo-20&creative=9325&linkCode=as2&creativeASIN=1982063742&linkId=a09eb2af4520bbf25642d58904093001). Let me know in the comments if you know any similar books! You probably already guessed that I more than recommend reading [The Phoenix Project](https://www.amazon.com/gp/product/1942788290/ref=as_li_qf_asin_il_tl?ie=UTF8&tag=sandordargo-20&creative=9325&linkCode=as2&creativeASIN=1942788290&linkId=fc9c78132b98763cc56dca36a783a5f4). Let me share a couple of details from the book. ## Overtime, overtime, overtime The Phoenix Project is about an enterprise where the business is not happy. They lost their competitive edge and they feel that they are kept hostage by their IT organization. IT is not happy either because nothing works well, their opinions are always neglected, CIOs come and go and whenever there is a deployment, problems are guaranteed. As Erik Reid, a board candidate described, the relationship between a CEO and a CIO (or business and IT) is often like a dysfunctional marriage. Both sides feel powerless and held hostage by the other. Being hostage often manifests in the book by constant overtime. All-nighters, working through the weekends, skipping festivities with your spouse, with your kids. I was reading the book and shaking my head. People would really do that? If they would, why? For money? There are plenty of jobs... Of course, the book also shares some of the reasons. You have a calling, you or your spouse appreciate a high salary and you don't want to move for another opportunity, etc. Anyway, shit happens and there are definitely unanticipated events when someone has to solve the problem immediately and not during the next business day. There are emergencies and I think employees can be flexible in such cases, just like employers should be flexible with personal emergencies. But when it happens every month or every week, it's not an emergency anymore. It's just expected unplanned work. It's work that is in fact normal. Leaving your life behind should not be normal. [Don't burn out.](https://www.sandordargo.com/blog/2021/06/09/3-ways-to-prevent-micro-burnouts) ## The need for mentoring Although the author doesn't write about mentoring explicitly, if you follow the story of Bill Palmer, the new VP of IT Operations, you will notice that there are two key factors to his success. The first one is his attitude. He doesn't accept things as they are but he does whatever he can to change whatever he can for the better. As a former Navy officer, he is willing to fight back, he is willing to share his opinion and he doesn't only have preferences, but he has principles. When he realized that his opinion doesn't matter, he gave his resignation. The other key element is Erik, whom he first described as a *raving madman*. He turned out to be his most important help. He became his mentor who did not solve problems on behalf of Bill, but instead, he gave some ideas, some clues that Bill could follow upon. He couldn't have been succeeded the way he did without his mentor Erik. We all need help, we all need teachers, mentors who don't feed us the solutions on a silver spoon, but who help us to discover the right thing to do on our own - with the initial spark. Ideally, you don't only have one mentor or at least not the same one throughout your career. On different levels, you'll need different mentors. Maybe even in different areas of your lives. And how to find them? As Lao Tzu said, *"when the student is ready the teacher will appear. When the student is truly ready, the teacher will disappear."* So don't worry. Learn, be open and you'll find your mentor. Just like Bill did. ## The 3 ways Erik keeps telling Bill that IT work, IT operations is like plant operations and there are essentially 3 ways to be mastered in order to successfully support the development and after all, the business. The first way is the traditional left to right flow of work. From development, the work flows to IT operations so that it can be delivered to the customer. The question is how to make this flow effective. In plant operations, the key is to keep the amount of Work In Process small. In IT it's not different. Big deployments suck. Reviewing big pull requests sucks. You need small changes, small batches of changes, continuous integration, continuous delivery and deployment to limit the work in process. The second way is about having fast feedback from right to left at all of the work. This is needed so that teams can improve, so that the same failures are not happening again and again. If development makes things more difficult for deploying and operating a system, but they don't get the feedback for it, they cannot improve. Ideally, if something is broken the production system must be stopped until the error is fixed. In a plant, this might mean stopping the assembly lines. In software, on a smaller scale, this means that when you break a unit test, you cannot integrate your change until all the tests are fixed. On a bigger scale, it might mean a complete change freeze if the system becomes too difficult to change, too shaky to operate. The second way is about sending feedback back from each step to the previous ones. One can only improve with feedback. If errors are made at a work centre, but they are never told so, they cannot fix their processes. The third way is what makes the first two happen and in a sustainable way. It's the right culture. You need a team culture, a company culture that cultivates experimentation, as such it doesn't punish for failures as long as you learn from them. You need a culture where people care about their craft, where they hone their skills, they practice towards mastery and as a result, they dare to take some risks to experiment to innovate, to get better. You need a culture where you don't have to hide feedback, where it's taken into account, where problems are not swept under the carpet but where they are welcome as opportunities to make things better. If you want a healthy organization, these 3 ways have to be mastered. ## The 4 types of work Finally, let me share the 4 types of work that are explained in the book. Erik told Bill that there are 4 categories of work and if he really wants to manage IT operations well, he must understand the different types. Bill recognized the first 3 types quite easily, the last one was a bit more difficult whereas often that's the most common one. First, you have *business projects*. This is quite straightforward. New feature requests coming from the sponsoring business units as new projects. Then you have *internal IT projects*, such as modernizing the infrastructure, improving the pipeline or even refactoring the code to accommodate changes easier. Even if these activities are not budgeted directly by business units, it's important to keep track of the money, the resources they take so that you have a clear understanding of capacities for the other types of work. The third category is a broad one, *changes*. Changes are often generated from the first two categories and they are usually tracked in ticketing systems. The last category is *unplanned or recovery work*. If you have an unhealthy organization, this is going to be the most common one. It is always urgent, otherwise, it can be planned and deferred as a change. Unplanned work comes to the expense of the first three categories and as such it's disruptive, it makes plans inaccurate and if it's too frequent, even makes planning impossible. Building a predictable organization requires that you limit the possibilities of unplanned work appearing out of nowhere. ## Conclusion [The Phoenix Project](https://www.amazon.com/gp/product/1942788290/ref=as_li_qf_asin_il_tl?ie=UTF8&tag=sandordargo-20&creative=9325&linkCode=as2&creativeASIN=1942788290&linkId=fc9c78132b98763cc56dca36a783a5f4) is a mix of a novel and a cookbook for implanting a successful DevOps mindset. More than that a mindset that will help you turn a dysfunctional IT - business relationship into prospering collaboration. Yet, I found the first part of the book unusually depressing. Maybe because I felt strong sympathy for Bill Palmer. Speaking of Bill, he has a great personality as a leader and reflects traits that can be useful for many of us. He relentlessly asks questions and looks for solutions to problems instead of complaining. And he doesn't stop until he understands what goes on. I already tried to put in place some items I learnt from him. The Phoenix Project is a must-read for everyone who works in IT, and probably even for those who work **with** IT. I can't wait for [*The Unicorn Project*](https://www.amazon.com/gp/product/1942788762/ref=as_li_qf_asin_il_tl?ie=UTF8&tag=sandordargo-20&creative=9325&linkCode=as2&creativeASIN=1942788762&linkId=9e9b64c0b50993a4d56f1989ddf25908). Happy reading! ## Connect deeper If you liked this article, please - hit on the like button, - [subscribe to my newsletter](http://eepurl.com/gvcv1j) - and let's connect on [Twitter](https://twitter.com/SandorDargo)!
sandordargo
805,754
Building a Webapp with User Authentification using Flask
In this article, I will be showing you how to build a simple web app with user authentification or...
0
2021-08-27T21:51:04
https://dev.to/richkitibwa/building-a-webapp-with-user-authentification-using-flask-443h
In this article, I will be showing you how to build a simple web app with **user authentification** or **login** using flask. ###This app will have the following features: 1. Users will be able to sign up using their email addresses and also create a password. 2. Once a user is signed in, they are registered in the database. 3. If any user tries to sign in with credentials that already exist in the database, an error message will be returned notifying them. 4. The app will have a remember me function to remember users so they don't always have to enter their passwords to login to the app. 5. When logged in, a user will be able to see other routes of the app like profile and sign out. 6. When signed out, the user can only see the home, Login and signup routes. ##Alright lets get coding. The first step is to fire up the IDE of choice. Then create a project folder and then set up a virtual environment in which we will add the different dependencies for the app. Install the necessary packages such as **flask**, **flask-login**(which is used for the user login and authentication), **flask-sqlalchemy** which is used to create a database to store the data. Once all that is set up, create a new python file and call it `init.py`. This will initialise the app. Open the `init.py` file and import the following packages; ``` from flask import Flask from flask_sqlalchemy import SQLAlchemy from flask_login import LoginManager ``` **Flask** provides a lightweight framework for building our web app. **SQLAlchemy** is used to create the database to store user data such as emails and passwords. Checkout the official documentation [here](https://flask-sqlalchemy.palletsprojects.com/en/2.x/) to know about flask-SQLAlchemy. **flask-login** provides user session management for flask. It handles common tasks such as logging in, logging out and remembering users' sessions . Be sure to check out the official flask-login documentation [here](https://flask-login.readthedocs.io/en/latest/) for more information about it. Next, we will create a function to initialize the database using SQLAlchmemy as shown in the code snippet below. Initialise SQLAlchemy so we can use it later. `db = SQLAlchemy()` Create a function called `create_app` and create the flask instance and also add other configurations for the database. ``` def create_app(): app = Flask(__name__) app.secret_key = b'_5#y2L"F4Qz\k\xec]/' app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///users.db' db.init_app(app) ``` create a variable called `login_manager` to create a Login Manager instance to manage user login. ``` login_manager = LoginManager() login_manager.login_view = 'auth.login' login_manager.init_app(app) ``` Then create another python file called `models.py` to store information about the users. The model created is constituted of class which is translated into tables in our database. Each of the attributes are transformed into columns for the table. ``` class User(UserMixin, db.Model): id = db.Column(db.Integer, primary_key=True) email = db.Column(db.String(100), unique=True) password = db.Column(db.String(100)) name = db.Column(db.String(1000) ``` Open the **init.py** file again and import class **User** from **models.py** Open a new python file called auth.py. This file will contain all the logic for our **auth routes** for example login and signup. Import the neccesary packages first. ``` from flask import Blueprint, render_template, redirect, url_for, request, flash from werkzeug.security import generate_password_hash, check_password_hash from models import User from flask_login import login_user, logout_user, login_required from init import db ``` **Flash** is used to show messages to the user for example error messages. **Blueprint** is a python package that can help structure a flask application by grouping its functionality into reusable components. Read more about Blueprint package [here](https://realpython.com/flask-blueprint/). In this file we will put all the auth routes with logic to add new users to the database ,remember the user and logout the user. Here is the full file below `auth.py` ``` from flask import Blueprint, render_template, redirect, url_for, request, flash from werkzeug.security import generate_password_hash, check_password_hash from models import User from flask_login import login_user, logout_user, login_required from init import db auth = Blueprint('auth', __name__) @auth.route('/login', methods=['GET', 'POST']) def login(): if request.method == 'GET': return render_template('login.html') else: email = request.form.get('email') password = request.form.get('password') remember = True if request.form.get('remember') else False user = User.query.filter_by(email=email).first() if not user: flash('Please sign up first!') return redirect(url_for('auth.signup')) elif not check_password_hash(user.password, password): flash('Please check your login details and try again.') return redirect(url_for('auth.login')) login_user(user, remember=remember) return redirect(url_for('main.profile')) @auth.route('/signup', methods=['GET', 'POST']) def signup(): if request.method == 'GET': return render_template('signup.html') else: email = request.form.get('email') name = request.form.get('name') password = request.form.get('password') user = User.query.filter_by(email=email).first() if user: flash('Email already exists') return redirect(url_for('auth.signup')) new_user = User(email=email, name=name, password=generate_password_hash(password, method='SHA256')) db.session.add(new_user) db.session.commit() return redirect(url_for('auth.login')) @auth.route('/logout') @login_required def logout(): logout_user() return redirect(url_for('main.index')) ``` This is the full **init.py** file. ``` from flask import Flask from flask_sqlalchemy import SQLAlchemy from flask_login import LoginManager db = SQLAlchemy() def create_app(): app = Flask(__name__) app.secret_key = b'_5#y2L"F4Qz\k\xec]/' app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///users.db' db.init_app(app) login_manager = LoginManager() login_manager.login_view = 'auth.login' login_manager.init_app(app) from models import User @login_manager.user_loader def load_user(user_id): return User.query.get(int(user_id)) # blueprint for auth routes in the app from auth import auth as auth_blueprint app.register_blueprint(auth_blueprint) # blueprint for non auth routes in the app from main import main as main_blueprint app.register_blueprint(main_blueprint) return app ``` The `main.py` file ``` from flask import Blueprint, render_template from flask_login import login_required, current_user from init import create_app, db main = Blueprint('main', __name__) @main.route('/') def index(): return render_template('index.html') @main.route('/profile') @login_required def profile(): return render_template('profile.html', name=current_user.name) app = create_app() if __name__ == '__main__': db.create_all(app=create_app()) app.run(debug=True) ``` This is the main entry point of the app. The `models.py` file ``` from flask_login import UserMixin from init import db class User(UserMixin, db.Model): id = db.Column(db.Integer, primary_key=True) email = db.Column(db.String(100), unique=True) password = db.Column(db.String(100)) name = db.Column(db.String(1000)) def __repr__(self): return'<User %r>' % self.id def __init__(self, email, password, name): db.create_all() self.email = email self.password = password self.name = name ``` After creating the logic for the app, we now create the templates of the different pages. Create a templates folder in the main project folder and create a new html file called `base.html` This is the main html file from which all the other html file will inherit. We use **jinja templates** to extend the base.html to the other templates. Here is the full `base.html` ``` <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Flask Login</title> <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/bulma/0.7.2/css/bulma.min.css" /> <link rel="stylesheet" href="{{ url_for('static', filename='css/main.css') }}"> </head> <body> <section class="hero is-fullheight" style="background-image:#C4FCEF;"> <div class="hero-head"> <nav class="navbar"> <div class="container"> <div class="navbar-brand"> <a href="{{ url_for('main.index') }}" class="navbar-item" style="color:white"> CampNight </a> </div> <div id="navbarMenuHeroA" class="navbar-menu"> <div class="navbar-end"> <a href="{{ url_for('main.index') }}" class="navbar-item"> Home </a> {% if current_user.is_authenticated %} <a href="{{ url_for('main.profile') }}" class="navbar-item"> Profile </a> {% endif %} {% if not current_user.is_authenticated %} <a href="{{ url_for('auth.login') }}" class="navbar-item"> Login </a> <a href="{{ url_for('auth.signup') }}" class="navbar-item"> Sign Up </a> {% endif %} {% if current_user.is_authenticated %} <a href="{{ url_for('auth.logout') }}" class="navbar-item"> Logout </a> {% endif %} </div> </div> </div> </nav> </div> <div class="hero-body"> <div class="container has-text-centered"> {% block content %}{% endblock %} </div> </div> </section> </body> </html> ``` Notice that for the style we use **Bulma css** which is a nice framework. Read more about it [here](https://bulma.io/). We then create an `index.html` which is the homepage. `index.html` ``` {% extends "base.html" %} {%block content%} <h1 class ="title">Welcome to CampNight </h1> <h2 class="subtitle">Are you ready for an adventure?</h2> {%endblock%} ``` Check out the jinja templates used here in curly brackets. You can read more about jinja templates [here](https://jinja.palletsprojects.com/en/3.0.x/). We then create the `login.html` template `login.html` ``` {% extends "base.html" %} {%block content%} <div class="column is-4 is-offset-4"> <h3 class="title">Login</h3> <div class="box"> {% with messages = get_flashed_messages() %} {% if messages %} <div class="notification is-danger"> {{ messages[0] }} </div> {% endif %} {% endwith %} <form method="POST" action="/login"> <div class="field"> <div class="control"> <input class="input is-large" type="email" name="email" placeholder="Your Email" autofocus=""> </div> </div> <div class="field"> <div class="control"> <input class="input is-large" type="password" name="password" placeholder="Your Password"> </div> </div> <div class="field"> <label class="checkbox"> <input type="checkbox"> Remember me </label> </div> <button class="button is-block is-info is-large is-fullwidth">Login</button> </form> </div> </div> {%endblock%} ``` Then the `profile.html` to display the name of the particular user once they login. ``` {% extends 'base.html' %} {% block content %} <h1 class="title"> Welcome, {{ name }}! </h1> {% endblock %} ``` We then add the `signup.html` for users to sign up. ``` {% extends "base.html" %} {% block content %} <div class="column is-4 is-offset-4"> <h3 class="title">Sign Up</h3> <div class="box"> {% with messages = get_flashed_messages() %} {% if messages %} <div class="notification is-danger"> {{ messages[0] }}<br> Go to <a href="{{ url_for('auth.login') }}">login page</a> </div> {% endif %} {% endwith %} <form method="POST" action="/signup"> <div class="field"> <div class="control"> <input class="input is-large" type="email" name="email" placeholder="Email" autofocus=""> </div> </div> <div class="field"> <div class="control"> <input class="input is-large" type="text" name="name" placeholder="Name" autofocus=""> </div> </div> <div class="field"> <div class="control"> <input class="input is-large" type="password" name="password" placeholder="Password"> </div> </div> <button class="button is-block is-info is-large is-fullwidth">Sign Up</button> </form> </div> </div> {% endblock %} ``` Add another folder in the project folder and name it **static**. This folder contains resources for the app such as customised css sheets and images added to the app. The app is now finally ready and you can run it by running `python main.py` in the terminal. Run the app on local host 5000 and it will displayed in the browser. ![Sample webapp](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/udpn4kxrzhbj6trskz0s.png) Feel free to run the app hosted on [here](https://campnight1.herokuapp.com/) ####Resources Be sure to check out [this](https://medium.com/analytics-vidhya/creating-login-page-on-flask-9d20738d9f42) amazing medium article for more on how to implement user authentification in your web app using flask.
richkitibwa
805,800
9 Developer Tutorials You Should Try from August 2021
I want to share developer articles, tutorial and videos from IBM Developer North America team. These...
0
2021-09-02T18:29:20
https://maxkatz.org/2021/08/27/9-developer-tutorials-you-should-try-from-august-2021/
containers, ibmdeveloper, kubernetes, machinelearning
--- title: 9 Developer Tutorials You Should Try from August 2021 published: true date: 2021-08-27 23:26:38 UTC tags: Containers,IBMDeveloper,Kubernetes,MachineLearning canonical_url: https://maxkatz.org/2021/08/27/9-developer-tutorials-you-should-try-from-august-2021/ --- I want to share developer articles, tutorial and videos from [IBM Developer](http://developer.ibm.com) North America team. These resources offer high-quality developer education so I believe you will find them valuable. [![Summer](https://katzmax.files.wordpress.com/2021/08/pexels-photo-1152359.jpeg)](https://katzmax.files.wordpress.com/2021/08/pexels-photo-1152359.jpeg)<figcaption>Photo by MarcTutorials on <a href="https://www.pexels.com/photo/palm-trees-1152359/" rel="nofollow">Pexels.com</a></figcaption> 📖[Deploying a containerized app to IBM Code Engine](https://dev.to/godspowercuche/deploying-a-containerized-app-to-ibm-code-engine-379h-temp-slug-4546333) by [Mrina Sugosh](https://twitter.com/mrinasugosh) 📖[Deploying a Python Flask App to Kubernetes](https://dev.to/godspowercuche/deploying-a-python-flask-app-to-kubernetes-5dmp-temp-slug-5725205) by [Mrina Sugosh](https://twitter.com/mrinasugosh) 📖[Docker Cheatsheet](https://dev.to/ibmdeveloper/docker-command-cheatsheet-1pe8) by [Mrina Sugosh](https://twitter.com/mrinasugosh) 📖[Get FREE Kubernetes Certification with IBM](https://dev.to/ibmdeveloper/get-free-kubernetes-certification-with-ibm-3o83) by [Jenna Ritten](https://twitter.com/jritten) 📖[Can’t push to your GitHub repo? I can help with that](https://dev.to/ibmdeveloper/can-t-push-to-your-github-repo-i-can-help-with-that-1fda) by [Jenna Ritten](https://twitter.com/jritten) 📖[Journey to the Cloud: IBM Cloud Deployment 4 Ways](https://dev.to/ibmdeveloper/journey-to-the-cloud-ibm-cloud-deployment-4-ways-o5b) by [Jenna Ritten](https://twitter.com/jritten) 📖[IBM Cloud Deployment 4 Ways: IBM Cloud Code Engine](https://dev.to/ibmdeveloper/ibm-cloud-deployment-4-ways-ibm-cloud-code-engine-1i12) by [Jenna Ritten](https://twitter.com/jritten) 📖[How Game Dev and Betting on Myself Altered My Career Path Forever](https://dev.to/bradstondev/how-game-dev-and-betting-on-myself-altered-my-career-path-forever-17bn) by [Bradston Henry](https://twitter.com/BradstonDev) 📖[Simple Guide to Deploying a Node Server to Red Hat OpenShift](https://dev.to/ibmdeveloper/simple-guide-to-deploying-a-node-server-to-red-hat-openshift-aa9) by [Bradston Henry](https://twitter.com/BradstonDev) One more thing. If you are looking to join our live online meetups, you will find weekly developer education events on our [Crowdcast channel](http://crowdcast.io/ibmdeveloper).
maxkatz
805,862
Using YugabyteDB in Python App Development
As a long time PostgreSQL user, it's normal that YugabyteDB got my attention. It's a distributed SQL...
0
2021-08-28T09:47:01
https://dev.to/zimeracorp/using-yugabytedb-in-python-app-development-2en5
python, yugabytedb, cassandra, postgres
As a long time [PostgreSQL](https://www.postgresql.org/) user, it's normal that [YugabyteDB](https://www.yugabyte.com/) got my attention. It's a distributed SQL database which features-compatible with PostgreSQL so that I don't need to lose my investation. YugabyteDB reuses PostgreSQL's query layer, so I can use my development tools as usual. It gives me more since there is also Cassandra query layer. Using YugabyteDB I can reuse my SQL skill and development tools, enhanced with NOSQL data model (especially **wide-column store**), while I have NewSQL's resiliency, scalability, and high performance. In this article, I am going to setup YugabyteDB for local cluster, populate data, and access the data using Python3. ## Install and Configure YugabyteDB Installation is very easy and straightforward. No source code compilation (well, unless you really want to dig that deep). Just [download](https://download.yugabyte.com/local) YugabyteDB, extract, then execute `bin/post-install.sh`. When this step has finished, make sure that `path/to/extracted/yugabytedb/bin` is in the $PATH. Here's what I did: **Fish Shell** ```bash $ set -x path/to/extracted/yugabytedb/bin $PATH ``` **Bash Shell** ```bash $ export PATH=path/to/extracted/yugabytedb/bin:$PATH ``` > **Note**: to avoid writing the same thing over and over again, I usually put the `set` or `export` statements above inside a file and then whenever I want to use YugabyteDB, I just `source the-file.sh`. Next, we need to configure YugabyteDB. To configure YugabyteDB, see [YugabyteDB configuration](https://docs.yugabyte.com/latest/deploy/manual-deployment/system-config/). The documentation is complete but to have everything works, all I need to do is changing `/etc/security/limits.conf` to: ```bash # /etc/security/limits.conf # #Each line describes a limit for a user in the form: ... ... ... #<domain> <type> <item> <value> # * - core unlimited * - data unlimited * - fsize unlimited * - sigpending 119934 * - memlock 64 * - rss unlimited * - nofile 1048576 * - msgqueue 819200 * - stack 8192 * - cpu unlimited * - nproc 12000 * - locks unlimited # End of file ``` Depends on your situation, maybe you need to restart or just logout-login back. All data, logs, configurations, etc for YugabyteDB reside in `$HOME/var/`. Do check `$HOME/var/conf/yugabytedb.conf` for more configuration: ```bash { "tserver_webserver_port": 9000, "master_rpc_port": 7100, "universe_uuid": "dabc3d28-6982-4585-8b10-5faa7352da02", "webserver_port": 7200, "ysql_enable_auth": false, "cluster_member": true, "ycql_port": 9042, "data_dir": "/home/bpdp/var/data", "tserver_uuid": "71ad70b8eef149ae945842572e0fff75", "use_cassandra_authentication": false, "log_dir": "/home/bpdp/var/logs", "polling_interval": "5", "listen": "0.0.0.0", "callhome": true, "master_webserver_port": 7000, "master_uuid": "1ef618e573a04e1d835f4ed4364825d7", "master_flags": "", "node_uuid": "6ae31951-7199-4c22-b30b-e8f235cef7db", "join": "", "ysql_port": 5433, "tserver_flags": "", "tserver_rpc_port": 9100 } ``` > **Note**: PostgreSQL usually uses port 5432, but YugabyteDB default port is 5433. Pay attention to this since we are going to use this when we write our code. So many things we can do with YugabyteDB, but for this article, I will concentrate more on Python app development. Therefore, it's enough now to have local cluster. Let's set it up!. Let's run YugabyteDB: ```bash $ yugabyted start Starting yugabyted... ✅ System checks +--------------------------------------------------------------------------------------------------+ | yugabyted | +--------------------------------------------------------------------------------------------------+ | Status : Running. Leader Master is present | | Web console : http://127.0.0.1:7000 | | JDBC : jdbc:postgresql://127.0.0.1:5433/yugabyte?user=yugabyte&password=yugabyte | | YSQL : bin/ysqlsh -U yugabyte -d yugabyte | | YCQL : bin/ycqlsh -u cassandra | | Data Dir : /home/bpdp/var/data | | Log Dir : /home/bpdp/var/logs | | Universe UUID : dabc3d28-6982-4585-8b10-5faa7352da02 | +--------------------------------------------------------------------------------------------------+ 🚀 yugabyted started successfully! To load a sample dataset, try 'yugabyted demo'. 🎉 Join us on Slack at https://www.yugabyte.com/slack 👕 Claim your free t-shirt at https://www.yugabyte.com/community-rewards/ $ ``` Check the status: ```bash $ yugabyted status +--------------------------------------------------------------------------------------------------+ | yugabyted | +--------------------------------------------------------------------------------------------------+ | Status : Running. Leader Master is present | | Web console : http://127.0.0.1:7000 | | JDBC : jdbc:postgresql://127.0.0.1:5433/yugabyte?user=yugabyte&password=yugabyte | | YSQL : bin/ysqlsh -U yugabyte -d yugabyte | | YCQL : bin/ycqlsh -u cassandra | | Data Dir : /home/bpdp/var/data | | Log Dir : /home/bpdp/var/logs | | Universe UUID : dabc3d28-6982-4585-8b10-5faa7352da02 | +--------------------------------------------------------------------------------------------------+ ``` Just in case you need to shutdown YugabyteDB: ```bash $ yugabyted stop Stopped yugabyted using config /home/bpdp/var/conf/yugabyted.conf. $ ``` Ok, now let YugabyteDB runs. We will use that for later processes. ## Data Preparation Now, it gets more interesting. Using one YugabyteDB server instance, we can use both SQL and Cassandra data model. Let's aggregate some data into PostgreSQL layer and Cassandra layer. For this purpose, we still use default user and password. Later on, you can manage the security side of YugabyteDB. > **Note**: default username and password for PostgreSQL layer: **yugabyte:yugabyte**, while for Cassandra: **cassandra:cassandra**. ### SQL Data YugabyteDB provides [sample datasets](https://docs.yugabyte.com/latest/sample-data/) for SQL data. We are going to use [Northwind Traders Database](https://docs.yugabyte.com/latest/sample-data/northwind/). Get the `DDL` and `Data` scripts from the Northwind sample datasets URL. Follow this sceen dump to prepare the database, tables, and populate the data. The **<database-name>#** pompt is the place to write command. ```bash $ ysqlsh -U yugabyte ysqlsh (11.2-YB-2.7.2.0-b0) Type "help" for help. yugabyte=# create database northwind; CREATE DATABASE yugabyte=# \l List of databases Name | Owner | Encoding | Collate | Ctype | Access privileges -----------------+----------+----------+---------+-------------+----------------------- northwind | yugabyte | UTF8 | C | en_US.UTF-8 | postgres | postgres | UTF8 | C | en_US.UTF-8 | system_platform | postgres | UTF8 | C | en_US.UTF-8 | template0 | postgres | UTF8 | C | en_US.UTF-8 | =c/postgres + | | | | | postgres=CTc/postgres template1 | postgres | UTF8 | C | en_US.UTF-8 | =c/postgres + | | | | | postgres=CTc/postgres yugabyte | postgres | UTF8 | C | en_US.UTF-8 | (6 rows) yugabyte=# \c northwind You are now connected to database "northwind" as user "yugabyte". northwind=# \i northwind_ddl.sql SET SET SET SET SET SET SET SET DROP TABLE DROP TABLE DROP TABLE DROP TABLE DROP TABLE DROP TABLE DROP TABLE DROP TABLE DROP TABLE DROP TABLE DROP TABLE DROP TABLE DROP TABLE DROP TABLE CREATE TABLE CREATE TABLE CREATE TABLE CREATE TABLE CREATE TABLE CREATE TABLE CREATE TABLE CREATE TABLE CREATE TABLE CREATE TABLE CREATE TABLE CREATE TABLE CREATE TABLE CREATE TABLE northwind=# \d List of relations Schema | Name | Type | Owner --------+------------------------+-------+---------- public | categories | table | yugabyte public | customer_customer_demo | table | yugabyte public | customer_demographics | table | yugabyte public | customers | table | yugabyte public | employee_territories | table | yugabyte public | employees | table | yugabyte public | order_details | table | yugabyte public | orders | table | yugabyte public | products | table | yugabyte public | region | table | yugabyte public | shippers | table | yugabyte public | suppliers | table | yugabyte public | territories | table | yugabyte public | us_states | table | yugabyte (14 rows) northwind=# \i northwind_data.sql ... ... ... INSERT 0 1 INSERT 0 1 INSERT 0 1 northwind=# select * from products; product_id | product_name | supplier_id | category_id | quantity_per_unit | unit_price | units_in_s tock | units_on_order | reorder_level | discontinued ------------+----------------------------------+-------------+-------------+----------------------+------------+----------- -----+----------------+---------------+-------------- 4 | Chef Anton's Cajun Seasoning | 2 | 2 | 48 - 6 oz jars | 22 | 53 | 0 | 0 | 0 46 | Spegesild | 21 | 8 | 4 - 450 g glasses | 12 | 95 | 0 | 0 | 0 73 | Röd Kaviar | 17 | 8 | 24 - 150 g jars | 15 | 101 | 0 | 5 | 0 29 | Thüringer Rostbratwurst | 12 | 6 | 50 bags x 30 sausgs. | 123.79 | 0 | 0 | 0 | 1 70 | Outback Lager | 7 | 1 | 24 - 355 ml bottles | 15 | 15 | 10 | 30 | 0 25 | NuNuCa Nuß-Nougat-Creme | 11 | 3 | 20 - 450 g glasses | 14 | 76 | 0 | 30 | 0 54 | Tourtière | 25 | 6 | 16 pies | 7.45 | 21 | 0 | 10 | 0 ... ... ... 17 | Alice Mutton | 7 | 6 | 20 - 1 kg tins | 39 | 0 | 0 | 0 | 1 59 | Raclette Courdavault | 28 | 4 | 5 kg pkg. | 55 | 79 | 0 | 0 | 0 (77 rows) northwind=# ``` Finish with SQL data, it's about the time to populate column-wide - Cassandra data. ### NOSQL Column-wide Data - Apache Cassandra We will use a simple keyspace: one keyspace, consists of one table. Create a CQL script file (here, the file name is `zimera-employees.cql`): ```sql CREATE KEYSPACE zimera WITH replication = {'class':'SimpleStrategy', 'replication_factor' : 3}; USE zimera; CREATE TABLE employees( e_id int PRIMARY KEY, e_fullname text, e_address text, e_dept text, e_role text ); INSERT INTO employees (e_id, e_fullname, e_address, e_dept, e_role) VALUES(1,'Zaky A. Aditya', 'Dusun Medelan, RT 01, Umbulmartani, Ngemplak, Sleman, DIY, Indonesia', 'Information Technology', 'Machine Learning Developer'); ``` Execute the script: ```bash $ ycqlsh -f zimera-employees.cql $ ``` Check whether succeed or not: ```bash $ ycqlsh -u cassandra Password: Connected to local cluster at 127.0.0.1:9042. [ycqlsh 5.0.1 | Cassandra 3.9-SNAPSHOT | CQL spec 3.4.2 | Native protocol v4] Use HELP for help. cassandra@ycqlsh> use zimera; cassandra@ycqlsh:zimera> select * from employees; e_id | e_fullname | e_address | e_dept | e_role ------+----------------+----------------------------------------------------------------------+------------------------+---------------------------- 1 | Zaky A. Aditya | Dusun Medelan, RT 01, Umbulmartani, Ngemplak, Sleman, DIY, Indonesia | Information Technology | Machine Learning Developer (1 rows) cassandra@ycqlsh:zimera> $ ``` ## Python - Drivers Since we are going to use both PostgreSQL and Apache Cassandra data model, we need to install those two drivers: [psycopg2](https://www.psycopg.org/) for PostgreSQL and [Python Driver for Apache Cassandra](https://github.com/datastax/python-driver). > **Note**: currently, `psycopg` is still developing [psycopg3](https://www.psycopg.org/psycopg3/). We do not use psycopg3 since it is still in early development stage, but once `psycopg3` is released, there should be easy to migrate. **Install Cassandra Driver** ```bash $ conda install cassandra-driver ... ... ... added / updated specs: - cassandra-driver The following packages will be downloaded: package | build ---------------------------|----------------- cassandra-driver-3.25.0 | py39h27cfd23_0 3.0 MB ------------------------------------------------------------ Total: 3.0 MB The following NEW packages will be INSTALLED: blas pkgs/main/linux-64::blas-1.0-mkl cassandra-driver pkgs/main/linux-64::cassandra-driver-3.25.0-py39h27cfd23_0 intel-openmp pkgs/main/linux-64::intel-openmp-2021.3.0-h06a4308_3350 libev pkgs/main/linux-64::libev-4.33-h7b6447c_0 mkl pkgs/main/linux-64::mkl-2021.3.0-h06a4308_520 mkl-service pkgs/main/linux-64::mkl-service-2.4.0-py39h7f8727e_0 mkl_fft pkgs/main/linux-64::mkl_fft-1.3.0-py39h42c9631_2 mkl_random pkgs/main/linux-64::mkl_random-1.2.2-py39h51133e4_0 numpy pkgs/main/linux-64::numpy-1.20.3-py39hf144106_0 numpy-base pkgs/main/linux-64::numpy-base-1.20.3-py39h74d4b33_0 six pkgs/main/noarch::six-1.16.0-pyhd3eb1b0_0 Proceed ([y]/n)? y ... ... ... $ ``` **Install PostgreSQL Driver** ```bash $ conda install psycopg2 ... ... ... added / updated specs: - psycopg2 The following NEW packages will be INSTALLED: krb5 pkgs/main/linux-64::krb5-1.19.2-hac12032_0 libedit pkgs/main/linux-64::libedit-3.1.20210714-h7f8727e_0 libpq pkgs/main/linux-64::libpq-12.2-h553bfba_1 psycopg2 pkgs/main/linux-64::psycopg2-2.8.6-py39h3c74f83_1 Proceed ([y]/n)? y ... ... $ ``` > **Note**: I use `conda` for package management, but you don't need to. You can also use `pip`, in this case just `pip install psycopg2` and `pip install cassandra-driver`. ## Let's Code! ### Accessing SQL Data ```python # code-sql.py import psycopg2 conn = psycopg2.connect( host="localhost", database="northwind", user="yugabyte", port="5433", password="yugabyte") # Open a cursor to perform database operations cur = conn.cursor() # Execute a query cur.execute("SELECT * FROM products") # Retrieve query results records = cur.fetchall() print(records[0]) ``` Results: ```bash $ python code-sql.py (4, "Chef Anton's Cajun Seasoning", 2, 2, '48 - 6 oz jars', 22.0, 53, 0, 0, 0) $ ``` ### Accessing Cassandra Data Model ```python from cassandra.cluster import Cluster cluster = Cluster() session = cluster.connect('zimera') rows = session.execute('SELECT e_fullname, e_address, e_dept, e_role FROM employees') for row in rows: print(row.e_fullname, row.e_address, row.e_dept, row.e_role) ``` Results: ```bash $ python code-cassandra.py Zaky A. Aditya Dusun Medelan, RT 01, Umbulmartani, Ngemplak, Sleman, DIY, Indonesia Information Technology Machine Learning Developer $ ``` What if we want to use both data model in one python source code? Here you go: ```python # code-all.py import psycopg2 from cassandra.cluster import Cluster conn = psycopg2.connect( host="localhost", database="northwind", user="yugabyte", port="5433", password="yugabyte") # Open a cursor to perform database operations cur = conn.cursor() # Execute a query cur.execute("SELECT * FROM products") # Retrieve query results records = cur.fetchall() print(records[0]) cluster = Cluster() session = cluster.connect('zimera') rows = session.execute('SELECT e_fullname, e_address, e_dept, e_role FROM employees') for row in rows: print(row.e_fullname, row.e_address, row.e_dept, row.e_role) ``` Results: ```bash $ python code-all.py (4, "Chef Anton's Cajun Seasoning", 2, 2, '48 - 6 oz jars', 22.0, 53, 0, 0, 0) Zaky A. Aditya Dusun Medelan, RT 01, Umbulmartani, Ngemplak, Sleman, DIY, Indonesia Information Technology Machine Learning Developer $ ``` Aren't they cool? Happy coding!
oldstager
806,707
python: module has no attribute error
Problem I have a directory ~/dev/python3/pylib, which contains handy small modules. One of...
0
2021-08-29T02:42:12
https://dev.to/antlossway/python-module-has-no-attribute-error-4753
python
# Problem I have a directory ~/dev/python3/pylib, which contains handy small modules. One of them is DB.py, which defines functions to connect to different databases. If a script requires connection to a database, I can simply do ``` import site site.addsitedir('/home/xqy/dev/python3/pylib') import DB db = DB.connectlocaldb() ``` But why I got error like below? **AttributeError: module 'DB' has no attribute 'connectlocaldb'** I checked several times to make sure the lib dir is correct and the file DB.py includes function "connectlocaldb()", but the error still persists. # Reason: When importing a module, python will go through a list of directories included in **sys.path**, and searching for the specified module, the first one found will be used. xqy@voyager:~/dev/python3$ python Python 3.7.3 (default, Jan 22 2021, 20:04:44) [GCC 8.3.0] on linux Type "help", "copyright", "credits" or "license" for more information. >>> import sys >>> print("\n".join(sys.path)) '' /usr/lib/python37.zip /usr/lib/python3.7 /usr/lib/python3.7/lib-dynload /home/xqy/.local/lib/python3.7/site-packages /usr/local/lib/python3.7/dist-packages /usr/lib/python3/dist-packages **the empty entry '' means the current directory** There is another DB.py under ~/dev/python3/, as my current directory is ~/dev/python3, the module file ~/dev/python3/DB.py is used instead of /home/xqy/dev/python3/pylib/DB.py And there is no "connectlocaldb" function in ~/dev/python3/DB.py We can also find out sys.path using below command xqy@voyager:~/dev/python3$ python3 -m site sys.path = [ '/home/xqy/dev/python3', '/usr/lib/python37.zip', '/usr/lib/python3.7', '/usr/lib/python3.7/lib-dynload', '/home/xqy/.local/lib/python3.7/site-packages', '/usr/local/lib/python3.7/dist-packages', '/usr/lib/python3/dist-packages', ] USER_BASE: '/home/xqy/.local' (exists) USER_SITE: '/home/xqy/.local/lib/python3.7/site-packages' (exists) ENABLE_USER_SITE: True xqy@voyager:~/dev/python3$ cd ~ xqy@voyager:~$ python3 -m site sys.path = [ '/home/xqy', '/usr/lib/python37.zip', '/usr/lib/python3.7', '/usr/lib/python3.7/lib-dynload', '/home/xqy/.local/lib/python3.7/site-packages', '/usr/local/lib/python3.7/dist-packages', '/usr/lib/python3/dist-packages', ] USER_BASE: '/home/xqy/.local' (exists) USER_SITE: '/home/xqy/.local/lib/python3.7/site-packages' (exists) ENABLE_USER_SITE: True` Therefore, by deleting file ~/dev/python3/DB.py or changing current directory, the error will not appear any more.
antlossway
806,031
Create a Newsletter app with Twitter Revue, Next.js API Routes, and Tailwindcss
Hey there 👋, do you like to learn from video tutorials? This article is also available as video...
0
2021-08-28T06:15:10
https://blog.greenroots.info/create-newsletter-with-revue-nextjs-api-routes-tailwindcss
nextjs, tailwindcss, twitter, sideprojects
Hey there 👋, do you like to learn from video tutorials? This article is also available as video content. {% youtube XbtgjxWFssQ %} *Please feel free to [subscribe](https://www.youtube.com/tapasadhikary) for the future content* <hr /> Do you have an email newsletter, or consider starting one? An email newsletter gives your subscribers regular updates about your work, products, passion, life, journey, anything that you find suitable to share. We have some great vendors/products/sites that help us to instantly get started with an email newsletter service. Buttondown, Mailchimp, MailerLite, Substack are just a few to name here. Early this year, [Twitter announced](https://blog.twitter.com/en_us/topics/company/2021/making-twitter-a-better-home-for-writers) the acquisition of [Revue](https://www.getrevue.co/), a service that makes it free and easy for anyone to start and publish editorial newsletters. Not only that. Twitter has also made Revue’s Pro features free for all accounts. A few days back, a tweet from Revue's official account confirmed that they would allow people to subscribe to your Revue newsletter directly from your Twitter profile. Keeping some debates aside, I think it is a great move. {% twitter 1428371221524189186 %} As the owner of a newsletter, we can promote it in many ways. - We can link to the [newsletter page](https://www.getrevue.co/profile/tapasadhikary) from our website, blog. - We can embed the subscription form to our website using simple JavaScript, HTML, CSS snippets provided by vendors. - Lastly, if the newsletter vendor provides APIs to access data, we can create, manage the newsletter entirely within our control. It is a powerful usage that gives your users a feeling of `oneness` being part of the same website, similar look-and-feel. # So, What's the Plan? This tutorial will teach how to use the `Revue` APIs to fetch data into a `Next.js` application using the API routes(serverless functions). We will also use the `tailwindcss` to give the app a better look and feel. I am on my way to migrate [my website](https://tapasadhikary.com/) using `Next.js` and `tailwindcss`, and the newsletter will be a part of it. So, it is an excellent opportunity to share what I have implemented and learned. # TL;DR If you want to jump into the final app or the source code early, here are the links, - [The Newsletter App Link](https://next-starter-revue-tailwind.vercel.app/) - [The Entire Source Code on the GitHub](https://github.com/atapas/next-starter-revue-tailwind) - [(Again) The YouTube Link](https://www.youtube.com/watch?v=XbtgjxWFssQ) # Setup a Newsletter Service using Revue To set up a newsletter with `Revue`, sign up to [https://www.getrevue.co/](https://www.getrevue.co/) using your Twitter account or email. ![Revue Sign up](https://cdn.hashnode.com/res/hashnode/image/upload/v1629961288039/a9cLtdxcW.png?border=1,CCCCCC&auto=compress) Next, log in to your account to set up the newsletter by providing the name, description, layout, issues, and schedule. You can [integrate many services](https://www.getrevue.co/app/integrations) like Twitter, Facebook, Instagram with your Revue account to fetch content from them to add to the newsletter. Additionally, you can fetch the data using the RSS feeds. You can integrate your Hshnode or Dev blog's RSS feed as well. I've made my wish already 😆! {% twitter 1428744252532477955 %} The bottom of the [integration page](https://www.getrevue.co/app/integrations) shows your API key to access the newsletter data over HTTP requests. Please copy this key and keep it safe. ![API Key](https://cdn.hashnode.com/res/hashnode/image/upload/v1629961839803/kYd5WYoA7.png?border=1,CCCCCC&auto=compress) This API key will be part of the `Authorization` header value when using the Revue APIs. [Here is the link](https://www.getrevue.co/api#get-/v2/lists) to learn about all publicly available APIs. In this tutorial, we will use the following, - `POST /v2/subscribers`: Add a subscriber to the list. - `GET /v2/subscribers`: Returns a list of your active subscribers. - `GET /v2/issues`: Returns a list of your sent issues. But, before that, let us build the user interface of the Newsletter Subscription app. # Build a Newsletter Subscription App using Next.js and Tailwindcss There are plenty of starter projects available in GitHub to get started with Next.js and Tailwindcss. My personal favorite is [next-starter-tailwind](https://github.com/taylorbryant/next-starter-tailwind) because of its simplicity. I'll be using it as a template to create a repository for the newsletter subscription app. Please feel free to use any other starter project you are comfortable with. Please create a repo by clicking on the `Use this template` button of the `next-starter-tailwind` repository. ![image.png](https://cdn.hashnode.com/res/hashnode/image/upload/v1629963836334/CGyvzhFNu.png?border=1,CCCCCC&auto=compress) Provide required details and create a repository from the template. ![image.png](https://cdn.hashnode.com/res/hashnode/image/upload/v1629963928403/7fMP3ykgS.png?border=1,CCCCCC&auto=compress) Now clone the repository and browse to the project folder. Open a command prompt or terminal window to install dependencies using the following command, ```shell npm install # Or, yarn install ``` At this stage, please open the project with your favorite code editor(VS Code, in my case) and make minor code changes. Open the `header.js` file under the `components` folder and find the `Next.js Starter Tailwind` text. Change this text to `Newsletter demo powered by Next.js Revue Tailwind`. Additionally, you can change the creator name, GitHub information in the `footer.js` file. Now save your changes and use this command from your command prompt to launch the app. ```shell npm run dev # Or, yarn dev ``` Access the app using the URL `http://localhost:3000`. You should see the initial user interface coming up. ![Initial UI](https://cdn.hashnode.com/res/hashnode/image/upload/v1629964964534/ZAjQJYCfE.png?border=1,CCCCCC&auto=compress) ## Create the Subscription Form Let's create a basic subscription form with a single email field and a button to subscribe. Please create a new file called `Subscribe.js` under the `components` folder with the following content. ```js const Subscribe = () => { return ( <div className="border border-gray-200 rounded p-6 my-4 w-full bg-gray-50"> <p className="text-gray-900 mb-6 text-lg md:text-xl"> Want to keep your brain engaged with great UI/UX learning content? </p> <p className="text-gray-800 dark:text-gray-400 mb-10 text-base"> Enter your email address and you'll be be added to my email newsletter, of which you can opt out any time. </p> <form className="relative my-4"> <input aria-label="Email for newsletter" placeholder="john@email.com" type="email" autoComplete="email" required className="py-4 px-0 text-md bg-transparent w-9/12 text-gray-900 border-b-2 border-gray-600 dark:border-gray-400 dark:text-white focus:border-brand focus-visible:outline-none" /> <button className="flex justify-center px-5 py-4 mt-8 bg-green-600 text-white font-bold text-lg" type="submit" > Subscribe </button> </form> <p className="text-xl text-gray-800 dark:text-gray-200"> 14 subscribers . 3 issues </p> </div> ); }; export default Subscribe; ``` It is a react component with a simple form having one email field and a button. We have also hardcoded the subscribers and issues count. Later, we will make the API calls to fetch those. We have styled the HTML element using [tailwindcss classes](https://tailwindcss.com/docs). Now move over to the `index.js` under the `pages` folder. Replace the content of the file with the following, ```js import Subscribe from "@components/Subscribe"; export default function IndexPage() { return ( <Subscribe /> ); } ``` Here we are importing and using the `Subscribe` component so that when the app loads, it shows the newsletter subscription form. Let's refresh the page. You should see subscription forms like, ![Subscription Form](https://cdn.hashnode.com/res/hashnode/image/upload/v1630071552191/Kp8AMgDwD.png?border=1,CCCCCC&auto=compress) # Create Next.js API Routes to Subscribe, and Many More Now it's time to create `Next.js API Routes` to register a new subscriber, get the subscriber count, and list of issues. ## Next.js Serverless Functions With Next.js's [API Routes](https://nextjs.org/docs/api-routes/introduction), you can easily create API endpoints. In the background, it uses Node.js serverless functions. You need to create these functions inside the `pages/api` folder. So, let us first create a folder called `api` under the `pages` folder. We will need the Revue API key now. Please create `.env.local` file at the root of the project folder with the following line, ```js REVUE_API_KEY=<REPLACE_THIS_WITH_REVUE_API_KEY> ``` Please use your `API Key` you have copied from the revue integration page earlier. At this stage, you need to restart the local server for the environment variable to get loaded in our app. So stop the server and restart it using the `yarn dev` command. Let's create the API route to register a new subscriber. ## But, Hold On! Why Can't We use the Revue API Directly? You can. It is possible to use the Revue APIs directly in your React components. However, there are a few advantages of using it via the Next.js APIs. - In the future, if you want to use another newsletter service other than Revue, your user interface component code never changes. You just change the serverless function and redeploy. - There is an abstraction. It helps you to deploy and host just the API separately along with your own business use cases. Alright, let's move on. - Accessing these APIs directly on the client-side will leave you with the risk of the API key exposed that anyone can obtain easily by inspecting network requests. You do not want that! ## Create Next.js API Route to Register a New Subscriber Create a file called `subscribe.js` inside `pages/api` folder. It means our API route will be accessible from the UI components using the URI `/api/subscribe`. Please paste the following content in the `subscribe.js` file. ```js export default async function handler(req, res) { // 1. Get the email from the payload and // validate if it is empty. const { email } = req.body; if (!email) { return res.status(400).json({error: 'Please provide an email id.'}); } // 2. Use the Revue API Key and create a subscriber using // the email we pass to the API. Please note, we pass the // API Key in the 'Authorization' header. try { const API_KEY = process.env.REVUE_API_KEY; const response = await fetch( `https://www.getrevue.co/api/v2/subscribers`, { method: 'POST', body: JSON.stringify({email: email, double_opt_in: false}), headers: { 'Authorization': `Token ${API_KEY}`, 'Content-Type': 'application/json' } } ) // 3. We check in the response if the status is 400 // If so, consider it as error and return. Otherwise a 201 // for create if (response.status >=400) { const message = await response.json(); console.log(message.error.email[0]); return res.status(400).json({error: message.error.email[0]}); } // Send a JSON response res.status(201).json({ message: `Hey, ${email}, Please check your email and verify it. Can't wait to get you boarded.`, error: '' }); } catch (err) { // 4. If the control goes inside the catch block // let us consider it as a server error(500) return res.status(500).json({error: err.message || error.toString()}); } } ``` A few things are going on in the above function. 1. When someone invokes this API function, we expect an email part of the payload. So first, get the email from the payload and validate if it is empty. 1. Next, use the email and API_KEY to call the Revue API to register a subscriber. Note the payload here. We are passing the email value and `double_opt_in` value as `false`. In reality, you will NOT pass the double_opt_in value as false as you want your subscribers to verify email before confirming. We are doing it just for the demo's sake. 1. Then, we check in the `response` if the status is 400. If so, consider it as an error and return with an error message. Otherwise, a 201 for creating and return with a success message. 1. Last, If the control goes inside the catch block, let us consider it a server error(500). ### Update the UI Code to Register Subscribers We will update the `Subscribe` component to use the `/api/subscribe` API. Open the `Subscribe.js` file under the `components` folder and make these changes. 1. Import the `useState` hook from `react` to manage a few states. Add this line at the top of the file. ```js import { useState } from 'react'; ``` 1. Create three state variables to handle the email from the user input and the error, success message from the API call. Add these three lines at the beginning of the `Subscribe` function as, ```js const Subscribe = () => { const [email, setEmail] = useState(''); const [error, setError] = useState(''); const [success, setSuccess] = useState(''); return ( ..... {/* Rest of the code as is */} .... ) } ``` 1. Next, handle two events. One is to capture the user input in the email field, and the second is to handle the for submit. ```html ... ... <form className="relative my-4" onSubmit={subscribeMe}> <input onChange={changeEmail} ``` 1. Now is the time to define both `subscribeMe` and `changeEmail` methods. ```js const subscribeMe = async (event) => { event.preventDefault(); const res = await fetch("/api/subscribe", { body: JSON.stringify({ email: email }), headers: { 'Content-Type': 'application/json' }, method: "POST", }); const { error, message } = await res.json(); if (error) { setError(error); } else { setSuccess(message); } }; const changeEmail = (event) => { const email = event.target.value; setEmail(email); } ``` In the `subscribeMe` method, we call the API `/api/subscribe`, passing the email value as the payload. Then we handle the error and success message. 1. Last, let's show the success and error message in the UI. Add this code right after the form element. ```html {success ? <span className="flex items-center text-sm font-bold text-green-700"> {success} </span> : <span className="flex items-center text-sm font-bold text-red-800"> {error} </span> } ``` Great, now go to the app and provide an email id to register. As we have turned off the email verification, you can test it with an arbitrary email id. Please take a look into the entire source file [from here](https://github.com/atapas/next-starter-revue-tailwind/blob/master/components/Subscribe.js). ![Register Success](https://cdn.hashnode.com/res/hashnode/image/upload/v1630082649555/YLQNTgmsf.png?border=1,CCCCCC&auto=compress) To verify, the email address got added successfully, got to the [subscribers](https://www.getrevue.co/app/lists) page of your account. You should see this new email id added, ![Subascriber added](https://cdn.hashnode.com/res/hashnode/image/upload/v1629973057192/-Webt8GAm.png?border=1,CCCCCC&auto=compress) > Please make sure to use the email verification by turning on `double_opt_in: true` in the API function for production usage. Try the same email id again to attempt to register! ![register fail](https://cdn.hashnode.com/res/hashnode/image/upload/v1630082807675/muZ1jY72r.png?border=1,CCCCCC&auto=compress) Yep, you will get that error. That's all. The subscription works well. ## Get the Subscriber Count Alright, let's get the subscriber count. So we will now write a serverless function to fetch the subscriber count. Please create a file called `subscribers.js` under the `pages/api` folder with the following content. ```js export default async function handler(_, res) { const API_KEY = process.env.REVUE_API_KEY; const response = await fetch('https://www.getrevue.co/api/v2/subscribers', { headers: { Authorization: `Token ${API_KEY}`, 'Content-Type': 'application/json' }, method: 'GET' }); const data = await response.json(); const count = data.length; res.setHeader( 'Cache-Control', 'public, s-maxage=1200, stale-while-revalidate=600' ); return res.status(200).json({ count }); } ``` We use the Revue API to fetch the subscriber list and then return the count as a response. So, now we have to use the `/api/subscribers` URI to fetch the count. Let's do it. ### Update the UI Code to Fetch Subscriber Count We need to fetch the subscriber count when the `Subscribe` component loads. Also, if there is a new subscriber, we need to show the updated count in the UI. `Next.js` supports two kinds of `pre-rendering`, - `Static Generation(SSG)`: In this case, everything is precompiled, prebuilt and cached. You do not see changes in your content until there is another build. It works best when you deal with static data like blog articles. - `Server-Side Rendering(SSR)`: Here, the data for a page generates on demand for each request. We prefer static generation as much as possible but may not avoid the server-side rendering in some cases. For our app, we will use `SWR`. As described [here](https://swr.vercel.app/), > `SWR` is derived from `stale-while-revalidate` , a HTTP cache invalidation strategy popularized by `HTTP RFC 5861`. SWR is a strategy to first return the data from cache (stale), then send the fetch request (revalidate), and finally come with the up-to-date data. With Next.js `pre-rendering` support and `SWR`, you can pre-render the page for SEO and allow caching, revalidation, and re-fetching at intervals on the client side. 1. Install `swr` library using the command, ```js npm install swr #Or, yarn add swr ``` 1. The `swr` library gives us a hook called `useSWR`. It takes two parameters, a `key` and a fetcher function. The `key` is a string value, usually the API URL that we will pass to the `fetcher` function, and the `fetcher` function can be an asynchronous function. So, let us create a simple fetcher function. Please create a `utils` folder at the root of the project and create a `fetcher.js` file with the following content, ```js export default async function Fetcher(...args) { const res = await fetch(...args); return res.json(); } ``` Next, in the `components/Subscribe.js` file, include these two imports. ```js import useSWR from 'swr'; import fetcher from '../utils/fetcher'; ``` Now we can use the `useSWR` hook to pass the API(`api/subscribers`) and the fetcher function. ```js const Subscribe = () => { const [email, setEmail] = useState(''); const [error, setError] = useState(''); const [success, setSuccess] = useState(''); // --- above is old code --- const { data } = useSWR('/api/subscribers', fetcher); const subscriberCount = data?.count; ``` Please note, we use the `JavaScript optional chaining(?.)` feature to get the count value. It handles the `undefined` value much safely. Every time the data gets changed at the back-end, the `subscriberCount` variable will have the latest count. 1. Last is to use the `subscriberCount` state variable instead of the hardcoded value. ```html <p className="text-sm text-gray-800 dark:text-gray-200"> { subscriberCount } subscribers . 3 issues </p> ``` That's all. Refresh the app and see the actual count reflecting. ![Subscriber count](https://cdn.hashnode.com/res/hashnode/image/upload/v1630083167179/SbLVFz4lo.png?border=1,CCCCCC&auto=compress) ## Get the Issue List Now we need to get the issue list and the count of published issues. So we have to write a serverless function again to fetch these details. But wait, I'm not going to do that in this tutorial. Please take it as an exercise to try out. Hint: You need to use this Revue API to fetch the data => `GET /v2/issues`. If you need help, the [API code is here](https://github.com/atapas/next-starter-revue-tailwind/blob/master/pages/api/issues.js), and the [component changes](https://github.com/atapas/next-starter-revue-tailwind/blob/master/components/Subscribe.js) are here to refer to. In the end, the UI should have the actual issue count and a list of published issues like this(I have one test issue). ![final page](https://cdn.hashnode.com/res/hashnode/image/upload/v1630083249642/_OUZULeLh.png?border=1,CCCCCC&auto=compress) # Let's Deploy Congratulations!!! The app is ready to use. But, it is available only with you. Let's deploy it publicly. We will use the [Vercel](https://vercel.com/) platform to deploy our app. It is super easy to deploy a Next.js app on Vercel using a few simple steps. To make it happen, please commit and push all your code changes to the `GitHub` repository. 1. Create an account with Vercel, log in and click on the `New Project` button to get started. ![image.png](https://cdn.hashnode.com/res/hashnode/image/upload/v1629979553563/T5xJig9eN.png?border=1,CCCCCC&auto=compress) 1. Next, import your project from GitHub. ![image.png](https://cdn.hashnode.com/res/hashnode/image/upload/v1629979633056/Lwb0k4SFB.png?border=1,CCCCCC&auto=compress) 1. Now, you need to configure your project. For a Next.js project, you hardly need to make any changes to the build and other parameters. If your app is depending on any Environment Variables, you need to add them one by one. In our case, we have one. So let's add it. Then, click on the `Deploy` button. ![image.png](https://cdn.hashnode.com/res/hashnode/image/upload/v1629979696642/0buvXxOsn.png?border=1,CCCCCC&auto=compress) 1. Congratulations!!! You have deployed the app successfully on Vercel. Now you can access the app publicly using the URL generated by the deployment process. ![image.png](https://cdn.hashnode.com/res/hashnode/image/upload/v1629979809143/GeERj2HL8.png?border=1,CCCCCC&auto=compress) Post-deployment, you can perform many checks and additional configurations based on your needs. If your app has one or more serverless functions, you can see the live execution logs from your project's `Functions` tab. The image below shows the log for our functions. ![image.png](https://cdn.hashnode.com/res/hashnode/image/upload/v1629982080277/tl8GRrAec.png?border=1,CCCCCC&auto=compress) # In Summary - `Next.js` is the future(arguably?) for React-based projects. It is easy to set up, learn, and use. The `tailwindcss` is a developer-friendly CSS library to style the app. `Revue` is an amazing newsletter service. - Your users, customers like the `oneness` and the `belongingness`. Then why not get the newsletter service within the app/site itself and manage it? - `Next.js APIs` are the Node.js `serverless functions` in the background. It is a great way to fetch, interact with back-end services. - It is super easy to deploy and maintain your Next.js app(including serverless functions) using `Vercel`. - Similar to this, you can integrate many other services like GitHub, your blog, and many more that I'll cover in my upcoming post. <hr/> That's all. I hope you enjoyed building it with me. Please share/like this article and the video tutorial so that it reaches others as well. Let's connect. Please find me on [Twitter(@tapasadhikary)](https://twitter.com/tapasadhikary), sharing thoughts, tips, and code practices. Would you please give a follow?
atapas
806,040
On online public speaking
On March 14th, 2020, I landed home. I had planned the week before to be productive: one talk in...
0
2021-08-29T18:09:20
https://blog.frankel.ch/online-public-speaking/
publicspeaking, devrel, covid
On March 14<sup>th</sup>, 2020, I landed home. I had planned the week before to be productive: one talk in Pasadena, two talks in San Francisco, one in Bucharest, and one in Istanbul. Then, on the 16<sup>th</sup>, I was supposed to fly again to other events. Then, Covid happened. Governments started to close borders; in turn, organizers began to cancel events. I managed to do the talk in Pasadena with about ten people in the room. The organizer of one of the San Francisco talks managed to move my talk online. The respective conference organizers canceled the other events. The pandemics have had profound consequences on the state of the world. Whole industries have been disrupted. For some, working from home had become the norm. ---- Who led the digital transformation of your company? 1. CEO 2. CTO 3. CIO 4. CoVid ---- I think we are only starting to see some of the implications. I'm not a sociologist, so I'll keep my thoughts on conferences and public speaking. While public speaking is only part of Developer Advocacy, it can be a massive chunk of it, depending on one's situation. ## Is online speaking the new normal? At the start of the lockdown, I stumbled upon several discussions from established Developer Advocates. They were about speaking online being the new "normal". Most of them were pretty optimistic about the changes. As far as I remember, discussions were mainly centered around the following two arguments: * Less traveling: As events happen online, you don't need to waste time traveling. In turn, it leads to less time wasted and more time available for work, _e.g._, more talks and one's private life. Additionally, it involves much less pollution as most traveling is via airplanes. It's the same argument as for commuting regular work, on a much larger scale. * More metrics: Online speaking improves measurement compared to regular speaking, just as digital marketing does compare to traditional marketing. One can quickly get the number of attendees, but also their evolution over time during the talk. Feedback is more easily collected. Etc. ## Attending an online event is not the same experience There's no denying the first argument, so I'll focus on the second. The fact that online metrics are more easily collectible needs to be balanced because they are not more meaningful. Precisely, the number of attendees in the talk doesn't translate into their engagement. If you've attended an online meeting, you know what I'm writing about. There are tons of distractions when you're at home: pets, children, the mailman, etc. Moreover, your boss and the team can interrupt. While the latter can happen in an on-site conference, it's much less likely; the former cannot. The network can also be shaky. I'm pretty aware of that because my Internet connection is quite bad at the time being. Additionally, there's a psychological side to it. The most privileged among us have a room dedicated to work. When you enter the room, your mind switches to work mode. An on-site conference plays the same role and lets you focus on the content. ## Speaking online is not the same experience So far, I've written about the side of the attendees. Now, I'd like to mention the side of the speaker. Let me first tell you about one particular experience that I had two years ago. It was summer, the end of the conference season. I had traveled _a lot_ during the months before and faced personal issues simultaneously. I still had one conference to go to, but I didn't want to: I felt as if I had no more energy left. In hindsight, I believe it might have been the beginning of mild depression. Regardless, I had committed to speak, and I'm a professional - at least, that's how I see myself. I went to the airport and boarded the plane. Then, I went to the hotel that hosted the conference. In my room, I still felt the same lack of energy. I didn't want to leave the room, but I was already on-site, so that it would have been pointless. I headed to the conference hall, prepared everything as I'd done hundreds of times before, and gave my talk. Having done it, I felt alive again! Afterward, I wondered what the exact reason for this energy boost was. ## Feedback makes the difference I've done more than 120 online talks since last year at the time of this writing. But I believe I've come up with a plausible explanation. On-site, I can see people nodding back at me. If I notice that the attention is waning, I have several options to get it back: I can move around the stage, or make a joke, or pause for a moment. You can sum up all of the above in a single word: **interaction**. It's a feedback loop, from the audience to the speaker and from the speaker to the audience. None of it is available online. I'm talking to my screen. Compared to on-site, online speaking _always_ leaves me exhausted, like an empty husk because of this lack of interaction. We could discard it as a personal quirk, but all speakers I confided in told me they had the same experience. It's severe enough that some colleagues who do public speaking "for fun" actually prefer not to do it at all. For small meetups, I ask people to switch on their cameras **on a voluntary basis** to add some feedback. It's not a perfect solution - actually, only a handful of people do agree - but limited feedback is better than none. ## Conclusion Online is another option when it comes to conferences. Just as for desk jobs, it avoids commuting and optimizes one's time. Yet, it doesn't replace the on-site experience: being human beings, both attendees and speakers require face-to-face interactions. _Originally published at [A Java Geek](https://blog.frankel.ch/online-public-speaking/) on August 29 <sup>th</sup>, 2021_
nfrankel
806,083
Programming knowledge
programming knowledge had diminished to a point that it no longer was sufficient for him to get a...
0
2021-08-28T09:08:51
https://dev.to/iamvanshjain/programming-knowledge-1nkj
programming knowledge had diminished to a point that it no longer was sufficient for him to get a job. In the course of a five-hour interview, he was told he was the very best of the bunch, but, he said, he was not hired. When he contacted him years later, he said, the hiring manager wrote that he was sorry he had passed over Latko, but there was a vacancy at a much better company.
iamvanshjain
806,238
Github 101
Hey, if you are absolute beginner or just started to code recently, and have seen your peers...
0
2021-08-28T10:13:17
https://dev.to/rkganeshan/github-101-hda
github, beginners, opensource, webdev
Hey, if you are absolute beginner or just started to code recently, and have seen your peers showcasing their projects and works in platforms like GitHub, then you are at the right spot! I'll let you know some quick easy peasy tools online where in you can code and "PUSH" your code to github by just a click. Also, I will let you know how to push your entire codebase from your system to GitHub. (Now here I am assuming that you have created an account on GitHub, if not - do it first, it's simple , create an account directly from your Google Account.) 01 ) If you are quite new to web dev and just trying your hands on experimenting a few stuffs here and there, then try using platforms such as CodeSandbox and Repl. All you need to is , go to the github icon, connect your sandbox to your github by providing your credentials and after authorization(this is just a one time step) you just need to type out your repository name, a few words about your project and hit the Create button. Similar steps for Repl too. Isn't that easy? Now you are all set to show case your project. Bonus here is: You can copy the URL from the output sample browser in your sandbox, go to your Github repo, and in the about section,paste this link under the wesite input field. So, now your work is all set, pushed into github and your peers can also directly view your project up and running from the URL that you had provided from the Sandbox! 02) If you want to push your project from your System to Github, download GitBash terminal, it helps you to do this in no time. Now follow the steps: Step 0: Open the GitBash terminal in the directory wherein your desired project folder(s) exists. Now type the following commands. Step 01:git init Step 02:git add <folder1> <folder2> <etc.> Step 03:git commit -m "Your message about the commit" (Now go to GitHub, under repositories create a new Repo by hitting the New button and provide the name of your repository and give some description about it, and you may also set you repo to private or public) Step 04:git remote add origin https://github.com/yourUsername/yourRepository.git Step 05:git push -u origin master Step 06:git push origin master That's it, now you can check your repo(give a refresh maybe), and in the master branch you would be able to see the changes. Similar to 01) if you want to host it live, we'll that's for some other day , for sure!
rkganeshan
806,270
Introducing image download sites in the production of high quality content
Hello, we are at your service with another training and introduction. Today, we want to introduce...
0
2021-08-28T12:04:19
https://dev.to/amirrezakarimip/introducing-image-download-sites-in-the-production-of-high-quality-content-15pc
Hello, we are at your service with another training and introduction. Today, we want to introduce websites for you that you can download photos from these websites in good quality for free and for money, but it is necessary to mention that some of these Website in Iran is banned Freepik This site has two sections, free and paid, you can also download open layer images in vector format from this site for free, download from this site is only possible for its members. And some images are available for free on the free courier site. Picjumbo On this site you can find a lot of amazing and beautiful images in any subject and title that you do not need to get a license to use on your site. Pexels This site is one of the largest free image directories . This site has collected many images from various other sites, so you can have a large and diverse collection of images in one place. So if you do not have much time to search for images when producing blog content or copywriting, this site can be one of the best. Stocksnap The stocksnap.io site, like other photo download sites, has very good quality images that you can download by subscribing to the site and use it to produce your content. Flickr In this site, in addition to being able to access high quality photos, you can also share your own photos. You can also edit your images on this site. Of course, you can use the features of this site when you must register on this site. This site is also a social network Until the next training, God bless the producer Amir Reza Karimi
amirrezakarimip
806,295
Cara membuat custom command pada terminal
terkadang menuliskan banyak command untuk satu hasil sangatlah menyebalkan, disini saya akan...
0
2021-08-28T13:09:01
https://dev.to/alfarizzi/cara-membuat-custom-command-pada-terminal-4g9n
linux, zsh, bash
terkadang menuliskan banyak command untuk satu hasil sangatlah menyebalkan, disini saya akan memberikan sedikit tutorial untuk membuat custom command pada terminal - buka terminal dan jalankan perintah ```bash sudo gedit ~/.bashrc ``` - setelah itu tambahkan ``` alias custom-command='perintah1;perintah2;dst' ``` - sebelum ![Sebelum Menggunakan Custom Command](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/9mmhrwuj0bb6p0mxc6t3.png) - setelah ![Setelah Menggunakan Custom Command](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/3jkpi8melflu6ir3j5w7.png)
alfarizzi
806,416
Top 7 Games To Learn Coding
Initially, I had limited options for practicing my coding skills, including books, online tutorials,...
0
2021-09-05T06:03:52
https://koulurunandakishorereddy.tech/top-7-games-to-learn-coding
javascript, python, programming, beginners
Initially, I had limited options for practicing my coding skills, including books, online tutorials, coding challenges, and lots of experimentation. Today, other than interactive courses and tutorials, you can check out several free coding games to learn coding skills and enhance your programming skills. <h1> 1. CODE MONKEY </h1> <p><a href="https://www.codemonkey.com/">Website Link</a></p> ![CodeMonkey.jpg](https://cdn.hashnode.com/res/hashnode/image/upload/v1626100364103/kWqJOi4pt.jpeg) <p><b>Code monkey</b> covers text-based coding languages of CoffeeScript and Python. The programming language used in Coding Adventure is called CoffeeScript. It's a language that compiles to JavaScript, and similarly to JavaScript, it is used in the industry primarily for web applications.</p> <p>CodeMonkey is a leading, fun and intuitive curriculum where students learn to code in real programming languages. Through the game and project-based courses, students as young as 7 use real programming languages to solve puzzles and build games and apps. The majority of CodeMonkey’s courses do not require prior coding experience to teach. All courses are designed for school, extra-curricular and home-use.</p> <h1>2. CODINGAME </h1> <p><a href="https://www.codingame.com/start">Website Link</a></p> ![codingame-1024x438.jpg](https://cdn.hashnode.com/res/hashnode/image/upload/v1626101279308/hvsIgGocB.jpeg) <p><b>CodinGame</b> is a technology company editing an online platform for developers, allowing them to play with programming with increasingly difficult puzzles, to learn to code better with an online programming application supporting twenty-five programming languages, and to compete in multiplayer programming contests involving timed artificial intelligence, or code-golf challenges.</p> <p>CodinGame offers up to fun free games to help learn more than 25 programming languages, including JavaScript, PHP and Ruby. </p> <h1>3. FLEXBOX FROGGY </h1> <p><a href="https://flexboxfroggy.com/">Website Link</a></p> ![screenshot.png](https://cdn.hashnode.com/res/hashnode/image/upload/v1626147023499/mOKxLodF9Z.png) <p><b>Flexbox Froggy </b>, a game where you help Froggy and friends by writing CSS code! Guide this frog to the lilypad on the right by using the justify-content property, which aligns items horizontally </p> <p>Want to learn how CSS flexbox works? check out <a href="https://flexboxfroggy.com/">FLEXBOX FROGGY</a> . It has a simple interface that teaches you the basics of how things align in flexbox while you help Froggy and his friends</p> <h1>4. Robocode </h1> <p><a href="https://robocode.sourceforge.io/">Website Link</a></p> ![programming-game-robocode.png](https://cdn.hashnode.com/res/hashnode/image/upload/v1626148427926/iWsxrkYnL.png) <p><b>Robocode</b> is a complex programming game where you code robot tanks that fight against each other. Your job is to write the artificial intelligence that drives your robots to success---using real languages like Java, Scala, C#, and more. To get started, check out the Robocode Basics and Tutorials.</p> <p>The Robocode installer comes with a development environment, built-in robot editor, and Java compiler. You're actually writing real code! Despite launching back in 2000, Robocode is still regularly updated and maintained, helped along by the fact that it's open-source and addictive.</p> <h1>5. Codecombat </h1> <p><a href="https://codecombat.com/">Website Link</a></p> ![Screen-Shot-2020-04-23-at-2.46.48-PM.png](https://cdn.hashnode.com/res/hashnode/image/upload/v1626148650812/Ir50QmM0i.png) <p><b>Codecombat</b> is another web app for game-like puzzles and challenges that can only be solved by writing code. But whereas Codingame is more entertaining, Codecombat has a significant educational bent with a "Classroom Edition" that teachers can use to help their students learn how to code. As of this writing, three course paths are available: Computer Science, Web Development, and Game Development.</p> <h1>6. Codewars </h1> <p><a href="https://www.codewars.com/">Website Link</a></p> ![programming-game-codewars.png](https://cdn.hashnode.com/res/hashnode/image/upload/v1626150051517/utyc-Unyd.png) <p><b>Codewars </b> isn't so much a game as it is a gamified way to practice coding and solving algorithmic challenges. You get points for completing puzzles and point values are determined by how efficient your solutions are. Codewars lets you view solutions submitted by others, which you can study and learn from. I believe it's one of the best ways to learn a new programming language and its idioms.</p> <h1>7. CheckiO </h1> <p><a href="https://checkio.org/">Website Link</a></p> ![share.jpg](https://cdn.hashnode.com/res/hashnode/image/upload/v1626150538733/xW4-kwUwh.jpeg) <p><b>CheckiO</b> is web-based Python learning resource, where your task is to learn through playing games and solving intertesting quizzes. CheckiO features it's own feature complete web-based development environment, but many users prfer using desktop IDE's.</p> <hr> <b><p> To all my readers out here I have an interesting thing to share with you. There's a hackathon going on there. For more information, keep reading.</p> <p> A hackathon might be an alternative for you if you are a computer science student or an upcoming developer. The benefit of participating in an online or physical hackathon is that you can develop coding skills, work with developers, develop a resume, and meet peers.</p> <hr> ![Alt Text](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/ly1s7y7p8hrpxlx7vv4v.png) <p> I recommend Hack This Fall 2.0 if you are interested in such an event. The event takes place between 22nd and 24th of October. A 48-Hour Virtual Hackathon is taking this to the next level this year, with the aim of promoting hackers and helping them to develop new ideas and prototypes in various domains. A part of their mission is also to support beginners to hack our society and bring a positive change.</p> If you want to register for this wonderful hackathon you can do it:<a href ="https://hackthisfall.devpost.com/">click here</a>.don't forget to use my referral code : HTFHE068. Over a thousand hackers have already signed up.</b>
koulurunandakishorereddy
806,419
How on earth does this work?
I was browsing the internet the other day and came across a site known as spur.us. The site claims to...
0
2021-08-28T15:28:32
https://dev.to/riversiderocks/how-on-earth-does-this-work-11e
security
I was browsing the internet the other day and came across a site known as spur.us. The site claims to "Stops fraud and abuse on the internet" by collecting and indexing IP usage, VPN IPs, and proxy IPs. Its a very interesting site, you can get info on any IP by visiting spur.us/context/youriphere. My question is, how does it work? How does a site collect data on every IP address out there? How do they know that X amount of people are on my IP address? How do they know that I have connected to the Tor network or used ProtonVPN?
riversiderocks
806,428
.NET Core 2.1 container images were deleted from Docker Hub!
If you started receiving errors when pulling old versions of dotnet docker images (like the .NET...
0
2021-08-28T16:03:20
https://luizlelis.com/blog/dotnet-docker-images-deleted
docker, dotnet
If you started receiving errors when pulling old versions of dotnet docker images (like the `.NET 2.1`), it's because Microsoft deleted them from Docker Hub on August 21st, 2021. That date is not a coincidence, the `.NET Core 2.1` reached end of support in the same date. For more details take a look at the official [dotnet announcement](https://github.com/dotnet/announcements/issues/197) or also the [dotnet blog](https://devblogs.microsoft.com/dotnet/net-core-2-1-container-images-will-be-deleted-from-docker-hub/). In my case, the error below was thrown when pulling the `microsoft/dotnet:2.2-aspnetcore-runtime` image: ```bash Error response from daemon: pull access denied for microsoft/dotnet, repository does not exist or may require 'docker login': denied: requested access to the resource is denied ``` As mentioned before, the reason was: microsoft moved the `out of support` images from docker hub to [microsoft container registry](https://github.com/microsoft/containerregistry) (MCR). To solve that problem, I updated the image to `mcr.microsoft.com/dotnet/core/runtime:2.2`. So, instead of pulling images from docker hub (`microsoft/dotnet`) you should pull them from MCR (`mcr.microsoft.com`), just like described below: ```bash microsoft/dotnet:2.1-sdk -> mcr.microsoft.com/dotnet/sdk:2.1 microsoft/dotnet:2.1-aspnetcore-runtime -> mcr.microsoft.com/dotnet/aspnet:2.1 microsoft/dotnet:2.1-runtime -> mcr.microsoft.com/dotnet/runtime:2.1 microsoft/dotnet:2.1-runtime-deps -> mcr.microsoft.com/dotnet/runtime-deps:2.1 ``` > **NOTE**: see the full list of `from docker hub to MCR images` [here](https://devblogs.microsoft.com/dotnet/net-core-2-1-container-images-will-be-deleted-from-docker-hub/#pulling-images-from-mcr) Maybe you're asking yourself: why microsoft announced that they removed the 2.1 images from docker hub but not the 2.2 images? The response is simple: `.NET 2.2` was deprecated in December 23, 2019, so microsoft don't need to announce as they are not supporting it anymore 🤷‍♂️ > **NOTE**: it's strongly recommended move to later `.NET` versions instead of using `out of support` versions like 2.1 or 2.2
luizhlelis
806,444
lntroduction to Laravel Livewire
Introduction This article introduces Livewire and how it can be implemented into a Laravel...
0
2021-08-30T08:12:59
https://dev.to/osejudith/lntroduction-to-laravel-livewire-aif
laravel, livewire, beginners, php
**Introduction** This article introduces Livewire and how it can be implemented into a Laravel application. A modern full-stack web app can be a bit complex to build especially with tools like Vue and React and this is the problem Livewire aims to solve. Livewire is a full-stack framework for Laravel that enables a developer to build a dynamic interface that is less complex within the Laravel environment. **Prerequisites** Basic knowledge of Laravel is needed **Takeaways** After going through this article, you will understand: * What Livewire is? * What problem does Livewire aim to solve, and * How to get started with Livewire with that being said, the following steps will enable us to get started with Livewire and how we can implement it into our Laravel application. **Steps** a) Install a new Laravel project using `composer create-project laravel/laravel laravel-livewire` b) cd into laravel-livewire c) Run `composer require livewire/livewire` d) Include `@livewireStyles` and `@livewireScripts` in the head and body tag of your `views/welcome.blade.php` file. ```php <!DOCTYPE html> <html lang="{{ str_replace('_', '-', app()->getLocale()) }}"> <head> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1"> <title>Laravel | Livewire</title> <!-- Fonts --> <link href="https://fonts.googleapis.com/css2?family=Nunito:wght@400;600;700&display=swap" rel="stylesheet"> <!-- Styles --> <style> body { font-family: 'Nunito', sans-serif; } </style> @livewireStyles </head> <body class="antialiased"> @livewireScripts </body> </html> ``` once that is done, we have all we need to start using Livewire in our Laravel application. e) Next, run `php artisan serve` f) Let make our first Livewire component for a simple counter to increase and decrease a value using the `php artisan make livewire counter` command. if that is successful, you should see a screen like the one below in your terminal ![livewire](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/zlqddghj4tlyodc4t4s0.PNG) Looking into our project structure, the above command created two new files in `app/Http/Livewire/Counter.php` ```php <?php namespace App\Http\Livewire; use Livewire\Component; class Counter extends Component { public function render() { return view('livewire.counter'); } } ``` and `resources\views/livewire/counter.blade.php` ``` <div> .... </div> ``` g) Next, we want to render a simple text to our browser to ensure our component is working, modify your counter Livewire blade file ```php <div> <h1>I am learning Livewire</h1> </div> ``` h) Before that, we need to include `<livewire: counter /> ` component in our welcome blade file ```php <!DOCTYPE html> <html lang="{{ str_replace('_', '-', app()->getLocale()) }}"> <head> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1"> <title>Laravel | Livewire</title> <!-- Fonts --> <link href="https://fonts.googleapis.com/css2?family=Nunito:wght@400;600;700&display=swap" rel="stylesheet"> <!-- Styles --> <style> body { font-family: 'Nunito', sans-serif; } </style> @livewireStyles </head> <body class="antialiased"> <livewire:counter /> @livewireScripts </body> </html> ``` we can now preview it on our browser ![image2](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/lqhbgrg3jpki9djt5rgy.PNG) Whola!, we have our component rendered to the browser successfully. i) We can now implement our simple counter ```php <?php namespace App\Http\Livewire; use Livewire\Component; class Counter extends Component { public $count = 0; public function increase() { $this->count++; } public function decrease() { $this->count--; } public function render() { return view('livewire.counter'); } } ``` Here, we declared a public property `$count` initialized to zero, a method to increase and decrease the number. Public property in Livewire is automatically made available to the view. ```php <div style="text-align: center"> <h1>Counter using Laravel Livewire</h1> <button type="submit" wire:click="increase">+</button> <button type="submit" wire:click="decrease">-</button> <h2>{{$count}}</h2> </div> ``` we used the livewire template directive in our buttons to increase and decrease the number. ![image](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/ztjduc3trk9any0rnyun.PNG) we have successfully implemented a simple counter to increase and decrease numbers using Livewire. A lot can be still be gotten from Livewire to enable you to build that full-stack modern web application. To read and get more on Livewire, visit [livewire documentation](https://laravel-livewire.com/docs/2.x/quickstart) The code snippet for this tutorial can be found in my [GitHub repo](https://github.com/ojudith/laravel-livewire) Feel free to say hi via [LinkedIn](https://www.linkedin.com/in/oikujudith/)
osejudith
806,474
HTML Features, probably you never knew existed.
Hello again from codereaper08! Thanks again to all my followers, who always motivate me to write...
0
2021-08-28T19:29:19
https://dev.to/codereaper08/html-features-you-never-knew-existed-54ii
webdev, todayilearned, html, todayisearched
Hello again from codereaper08! Thanks again to all my followers, who always motivate me to write blogs weekly, in spite of my tight academic schedules. Back again with a good article, I hope. In this post, we are going to discuss 5 features in HTML, which probably we never knew existed. So let's get into it. ## 1. WBR Tag: Let's start from the first one in our list, `wordbreak` tag, abbreviated as `<wbr>`. You may think, what's the meaning of its existence, well It's not like the handy `br` tags we use. `<wbr>` just doesn't force words to break unless there's a necessary situation to do so. `wbr` tag is an empty tag (Doesn't have a closing tag). We'll see a comparison between `<wbr>` and `<br>`, resize the browser-window to see how `wbr` breaks itself on necessary situations. {% jsfiddle https://jsfiddle.net/VishwaR/3bsw7vq8 result,html,css %} ## 2. address Tag: Using `div`'s for enclosing contact info? HTML gives a good semantic way of doing that using `<address>` tag. So what's different in using `<address>` tags, well, It renders the text in _Italics_ with line-breaks above and below the `<address>` tags. It also has a by default display property of `block`. Take a look at the below JSFiddle. {% jsfiddle https://jsfiddle.net/VishwaR/f2Lnpuhz/ result,html,css %} ## 3. optgroup Tag: `<optgroup>` tag is used when you need to group the options into categories. This makes selecting an option from a very large list of options easy! User can look into the relevant category and select an option in that particular category. I've created a superhero `optgroup` for demonstration in the below JSFiddle. {% jsfiddle https://jsfiddle.net/VishwaR/vm9jnwe4/ result,html,css %} ## 4. portal Tag: Now things get interesting! What we are going to see is a tag called `<portal>`. This was launched by **Google** in I/O 2019 DevCon, where they mentioned that, `<portal>` will be an upgrade to `<iframe>`. `<portal>` allows seamless navigation inside the embedded content, too!. One sad thing, It is not supported by many browsers, including the normal **Google Chrome** too. Currently, only the [Chrome canary](https://www.google.com/chrome/canary/) supports the `<portal>` tag. Check out the demo video below. {% youtube 4JkipxFVE9k %} ## 5. capture attribute for Input element: ![camera](https://images.unsplash.com/photo-1488240339625-c4014e114224?ixid=MnwxMjA3fDB8MHxwaG90by1wYWdlfHx8fGVufDB8fHx8&ixlib=rb-1.2.1&auto=format&fit=crop&w=1079&q=80) <figcaption> Photo by <a href="https://unsplash.com/@lucabravo?utm_source=unsplash&utm_medium=referral&utm_content=creditCopyText">Luca Bravo</a> on <a href="https://unsplash.com/s/photos/camera?utm_source=unsplash&utm_medium=referral&utm_content=creditCopyText">Unsplash</a> </figcaption> Lastly, we are going to see about `capture` attribute for the input elements. `capture` added as an attribute to an input element opens the camera for taking shots of the user(front camera) or the scene(rear camera). This tag only works on mobile, and it simply falls back to a file picker in Desktop. `capture` attribute has two values, — user --> Opens User facing Camera (Front) — environment --> Opens Environment (Rear) Take a look at the below JSFiddle. {% jsfiddle https://jsfiddle.net/VishwaR/7r0ec9g1/ result,html,css %} And, that's it for today, Feel I missed out something? Write down in comments, I'll be happy to include. Love it? Give a 💖 for the article. Thanks for reading and have a good time 😄
codereaper08
806,484
Prisma for beginners
About Prisma Prisma is an ORM with an introspect and migrations feature that reflects...
0
2021-08-28T18:31:01
https://dev.to/aritik/prisma-for-beginners-2ffi
webdev, node, database, postgres
#### About Prisma > Prisma is an ORM with an introspect and migrations feature that reflects changes across SQL definitions and GraphQL Types. When you're working with GraphQL , it can become tedious to make changes to your Type Schema and subsequently make those very same changes to your Database Schema. Therefore it becomes a necessity to find a tool that can persist these changes. However , Prisma needn't always be used with GraphQL. It's a great tool on its own even if you're building standard REST APIs. **Prerequisites** - PostGRES Installed locally (psql) - NodeJS Installed - npm Installed #### Setting up Prisma Initialise a Node Project using `npm`. ``` npm init -y ``` Install the Prisma CLI Tool that is used to generate the `schema.prisma` file. ``` npm install @prisma/cli --save-dev ``` Install the Prisma Client that is used to interface with the Database ``` npm install @prisma/client ``` Let's generate a Prisma project next. ``` npx prisma init ``` This generates a _prisma_ folder containing the `schema.prisma` file. Prisma differs in the sense that it offers its very own `schema.prisma` file with a specialised syntax for defining your schema. However , we'll not be editing this schema file now. We'll generate a schema using SQL first. We've also generated a `.env` file. You can edit the `DATABASE_URL` variable to connect to your PostGRES Database. ``` #.env DATABASE_URL="postgresql://username:password@localhost:5432/dbname?schema=public" ``` Replace `username` , `password` with your PostGRES credentials and replace `dbname` with any name you wish to give to your Database. (Database does not have to be created yet) I will name this Database as 'test'. ## Migrations and Introspection > Prisma offers two approaches to persist changes across Type Schema and Database Schema. 1. Introspect (SQL → Data Model) 2. Migration (Data Model → SQL) #### Migration Let's generate a Data Model in our `schema.prisma` file first , using SQL. Login to psql. Create the Database first. ```SQL -- Create a Database CREATE DATABASE test ``` Connect to the database using `\c test`. Proceed to execute the following SQL commands to generate our `users` and `posts` table along with our custom user type. ```SQL -- Create a custom type CREATE TYPE "user_role_enum" AS ENUM ('user', 'admin', 'superadmin'); -- Create a table CREATE TABLE "users"( "id" BIGSERIAL PRIMARY KEY NOT NULL, "name" VARCHAR(255) NOT NULL, "email" VARCHAR(255) UNIQUE NOT NULL, "role" user_role_enum NOT NULL DEFAULT('user') ); -- Create a table CREATE TABLE "posts"( "id" BIGSERIAL PRIMARY KEY NOT NULL, "title" VARCHAR(255) NOT NULL, "body" TEXT, "userId" INTEGER NOT NULL, FOREIGN KEY ("userId") REFERENCES "users"("id") ); ``` #### Generating Data Models using Introspect Once the table has been succesfully created , run the introspect command to generate Prisma Models. ``` npx prisma introspect ``` This will generate an equivalent Data Model in the schema.prisma file. ``` //schema.prisma model posts { id Int @id @default(autoincrement()) title String body String? userId Int users users @relation(fields: [userId], references: [id]) } model users { id Int @id @default(autoincrement()) name String email String @unique role user_role_enum @default(user) posts posts[] } enum user_role_enum { user admin superadmin } ``` As you can see , with the `introspect` feature , we've managed to convert our SQL commands into an equivalent Data Model. Prisma also provides a GUI tool called _prisma studio_ to view and interact with our Database. ``` npx prisma studio ``` This will open the GUI tool in your browser. ## Migrations in Prisma We've seen how we can convert our SQL commands to Data Models. Now let's look at how we can do the opposite. Delete your Database. ```SQL DROP DATABASE test; ``` This would have deleted the Database. Enter `\l` into psql to check if it has been successfully deleted. Migrations are used to generate SQL commands for given Prisma Data Models. Describe your model in the `schema.prisma` file as necessary. ```Javascript model User { @@map(name: "users") id Int @default(autoincrement()) @id uuid String @default(uuid()) @unique email String @unique name String? role UserRole @default(USER) createdAt DateTime @default(now()) @map("created_at") updatedAt DateTime @updatedAt @map("updated_at") posts Post[] } model Post { @@map(name: "posts") id Int @default(autoincrement()) @id uuid String @default(uuid()) @unique title String body String? user User @relation(fields: [userId], references: [id]) createdAt DateTime @default(now()) @map("created_at") updatedAt DateTime @updatedAt @map("updated_at") userId Int } enum UserRole { USER ADMIN SUPER_ADMIN } ``` You can read more about the Data Model's syntax [here](https://www.prisma.io/docs/concepts/components/prisma-schema/data-model#models-in-prisma-client) The Model above is a slightly modified version of the model we generated previously. Let's generate a table and its equivalent SQL commands next. Run the following command to generate a Prisma migration. ``` npx prisma migrate dev --preview-feature ``` You can give your migration any name you wish to. This will generate a `migrations` folder with all the necessary documentation and commands that were run in sequence to generate the SQL tables. *Migration can create a Database if the Database doesn't exist already* We can check if our tables were successfully created using `psql`. Therefore we've looked at the two main approaches to persisting changes in schema. Finally , Let's look at the _Prisma Client_. ## Prisma Client Run the following command to generate a Prisma Client ``` npx prisma generate ``` The Prisma Client helps us interact with our PostGRES Database. ``` const { PrismaClient } = require("@prisma/client"); const prisma = new PrismaClient(); async function main() { const users = await prisma.users.findMany(); console.log(users); } main(); ``` We can send queries to perform `CRUD` operations on our Database. Read more about these operations [here](https://www.prisma.io/docs/concepts/components/prisma-client/crud). **Note:** Don't forget to generate the Prisma Client every time an introspection or migration is performed.
aritik
806,519
Git alias to checkout & pull the default branch of GitHub repositories
Short post here. In my daily job, I switch between different projects/repositories quite...
0
2021-09-04T15:50:51
https://mmazzarolo.com/blog/2021-08-28-git-alias-to-checkout-default-branch-github/
git, productivity, github, bash
--- title: Git alias to checkout & pull the default branch of GitHub repositories published: true date: 2021-09-04 15:48:00 UTC tags: #git #productivity #github #bash canonical_url: https://mmazzarolo.com/blog/2021-08-28-git-alias-to-checkout-default-branch-github/ cover_image: https://dev-to-uploads.s3.amazonaws.com/uploads/articles/mbwonzf0orasdtd9f59r.png --- Short post here. In my daily job, I switch between different projects/repositories quite often. These projects can have different _default_ branches (`master`, `main`, `develop`), and they’re all GitHub repositories. Something I do frequently is checking out the repositories’ default branch and pulling down the most recent updates. Since I don’t remember what each repo’s default branch name is, I’m using a GitHub alias that automatically detects it: ```bash # .gitconfig [alias] # checkout and pull the default branch m = !git rev-parse --abbrev-ref origin/HEAD | cut -c8- | xargs -n 1 git checkout && git pull origin $(git rev-parse --abbrev-ref HEAD) ``` I invoke it with `git m`. It took me a bit to write this alias, mixing a few answers from this StackOverflow thread: [git - how to get default branch?](https://stackoverflow.com/questions/28666357/git-how-to-get-default-branch). I went through some trial and error. I played with GitHub’s `gh` CLI, `git symbolic-ref`, and a few other options, but it looks like there’s no silver-bullet solution for this problem yet. Still, this command is working well for my use cases. On the same topic, I’ve also found [this reply](https://stackoverflow.com/a/65710958/4836602) to the [“How to get the default for the master branch in Git?” StackOverflow question](https://stackoverflow.com/questions/65703168/how-to-get-the-default-for-the-master-branch-in-git) quite insightful.
mmazzarolo
806,565
How to use the PPMT function in excel office 365?
In this tutorial, we will guide you on how to use the PPMT Function In Excel Office 365. Let’s get...
0
2021-08-30T07:26:30
https://geekexcel.com/how-to-use-the-ppmt-function-in-excel-office-365/
tousetheppmtfunction, excel, excelfunctions
--- title: How to use the PPMT function in excel office 365? published: true date: 2021-08-28 15:38:30 UTC tags: ToUseThePPMTFunction,Excel,ExcelFunctions canonical_url: https://geekexcel.com/how-to-use-the-ppmt-function-in-excel-office-365/ --- In this tutorial, we will guide you on **how to use the PPMT** **Function In Excel Office 365**. Let’s get them below!! Get an official version of MS Excel from the following link: **[https://www.microsoft.com/en-in/microsoft-365/excel](https://www.microsoft.com/en-in/microsoft-365/excel)** ## PPMT Function Excel **PPMT function** returns the **amount of interest portion** for a **specific period**. ## PPMT Function Syntax ``` =PPMT (rate, per, nper, pv, [fv], [type]) ``` **Syntax Explanation:** - **Rate:** Interest rate per period. - **Per:** payment period of interest. - **nper:** total no. of the payment period. - **pv:** present value or the total loan amount. - **fv [optional]:** Extra cash balance if required. Default to 0. - **type [optional]:** When payments are due. Default is 0. ## Example - You need to **create a sample data** with **input values**. ![](https://geekexcel.com/wp-content/uploads/2021/08/Sample-data-42-1024x271.png)<figcaption>Sample data</figcaption> - Then, you have to find the **principal amount for 4 different months** mentioned in the Period column. - Now, you need to use this **formula** to get the **principal amount for the first month**. ``` =IPMT( B2/12 , 1 , C2 , -A2 ) ``` **Explanation:** - **B2/12:** rate is divided by 12 as we are calculating interest for monthly periods. - **1:** per is 1 as we are calculating for the first month. If you wish to find for any specific period. Mention the number for the period you wish to find the interest amount. - **C2:** total period to pay the amount. - **-A2:** negative sign indicates money is credited to the bank. ![](https://geekexcel.com/wp-content/uploads/2021/08/Use-formula-4-1024x559.png)<figcaption>Use IPMT Formula</figcaption> - Here, the **argument** to the function is given as **cell reference**. - Finally, you have to **change the per value** to find the **principal amount for the specific period**. ![](https://geekexcel.com/wp-content/uploads/2021/08/All-month-values-1024x546.png)<figcaption>Principal Amount values</figcaption> **Check this too:** [How to Use Excel SORTBY Function in Excel Office 365?](https://geekexcel.com/how-to-use-excel-sortby-function-in-excel-office-365/) ## Closure We hope that this short tutorial gives you guidelines to **use the PPMT** **Function In Excel Office 365. ** Please leave a comment in case of any **queries,** and don’t forget to mention your valuable **suggestions** as well. Thank you so much for Visiting Our Site!! Continue learning on **[Geek Excel](https://geekexcel.com/)!! **Read more on [**Excel Formulas**](https://geekexcel.com/excel-formula/) **!!** **Further Reference:** - **[Excel Formulas to Calculate the Principal for Given Period ~ Easily!!](https://geekexcel.com/excel-formulas-to-calculate-the-principal-for-given-period/)** - **[Formulas to Calculate the Cumulative Loan Principal Payments!!](https://geekexcel.com/excel-formulas-to-calculate-the-cumulative-loan-principal-payments/)** - **[Excel Formulas to Calculate the Interest for Given Period ~ Quickly!!](https://geekexcel.com/excel-formulas-to-calculate-the-interest-for-given-period/)** - **[Formulas to Calculate the Simple Interest ~ A Complete Guide!!](https://geekexcel.com/excel-formulas-to-calculate-the-simple-interest/)** - **[Excel Formulas to Calculate Loan Interest in Given Year ~ Simple Tips!!](https://geekexcel.com/excel-formulas-to-calculate-loan-interest-in-given-year/)**
excelgeek
806,644
AxleJS - Fetch, supercharged.
AxleJS Why? Good'ol Fetch API. Simple and easy, but bad error handling, long...
0
2021-08-29T00:49:59
https://dev.to/ksplatdev/axlejs-fetch-supercharged-36f9
javascript, typescript, webdev
# AxleJS ## Why? Good'ol Fetch API. Simple and easy, but bad error handling, long options, and doesn't always follow redirects. Thats where AxleJS ***supercharges*** fetch, with better error handling, easier to use options, can automatically follow redirects, and an easier way to manage and view headers and search queries! ## Features * Functions for all HTTP Restful Methods * Middleware and Middleware Options for code reusabilty. * Only ~9KB minified and ~15KB unminified * Custom, Extended Response and Request classes * Built-in way to cancel requests * Still keeps Fetch simple and easy to use * Fully written in TypeScript * Includes Type definitions * And a lot more.. ## GitHub Repository AxleJS is free and open-source using the [MIT License](https://github.com/ksplatdev/AxleJS/blob/main/LICENSE)! <https://github.com/ksplatdev/AxleJS>
ksplatdev
806,785
Create a Netflix clone from Scratch: JavaScript PHP + MySQL Day 34
Netflix provides streaming movies and TV shows to over 75 million subscribers across the globe....
0
2021-08-29T05:50:26
https://dev.to/cglikpo/create-a-netflix-clone-from-scratch-javascript-php-mysql-day-34-f2i
php, javascript, webdev, tutorial
Netflix provides streaming movies and TV shows to over 75 million subscribers across the globe. Customers can watch as many shows/ movies as they want as long as they are connected to the internet for a monthly subscription fee of about ten dollars. Netflix produces original content and also pays for the rights to stream feature films and shows. In this video,we will be creating category edit functionalities {% youtube gyjn97EWJuo %} If you like my work, please consider [![Buy me a coffee](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/jm11knj7d8zwcvo150q2.png)](https://www.buymeacoffee.com/cglikpo) so that I can bring more projects, more articles for you If you want to learn more about Web Development, feel free to [follow me on Youtube!](https://www.youtube.com/c/ChristopherGlikpo)
cglikpo
806,875
Dev.to Analytic
Hello, I like the analytic system on dev.to, which I believe was made using javascript, and I'd like...
0
2021-08-29T07:11:06
https://dev.to/yongdev/dev-to-analytic-33no
Hello, I like the analytic system on dev.to, which I believe was made using javascript, and I'd like to make one like it. Can anybody guide me through the process? I'm working on a php blog project that requires analytic, but I don't want to use Google Analytics because it's not detailed.
yongdev
806,908
How to Export All iCloud Note From Macbook to Markdown or Txt File
How to Export All iCloud Note From Macbook to Markdown or Txt File If you’re using a...
0
2021-08-29T09:23:50
https://dev.to/shijiezhou/how-to-export-all-icloud-note-from-macbook-to-markdown-or-txt-file-2o4e
apple, machinelearning, ios, node
![](https://cdn-images-1.medium.com/max/5872/1*0DkVZKNJ8cEgLMJ1dsWvXw.png) ## How to Export All iCloud Note From Macbook to Markdown or Txt File If you’re using a MacBook to store all the apple notes on your device, how do you migrate all other notes to different applications such as Evernotes, Microsoft Notes, or some other app? Here is the most simple way and safe way to help you ensure all the files and information is transferred. ## **Download the Exporter from App Store** [**‎Exporter**](https://apps.apple.com/us/app/exporter/id1099120373?mt=12) ![](https://cdn-images-1.medium.com/max/5524/1*qAwlS200_z_8zFZzo5hBxg.png) Once you download and install, just go-ahead to open the app ![](https://cdn-images-1.medium.com/max/2000/1*AukbmJ8d1wZXPfiJ24PVMQ.png) Once you download it, you can just click on the export button and it will scan and analyze all the note files on the mac. ![](https://cdn-images-1.medium.com/max/2000/1*9c5SPQJBQN4o91JmRZinXQ.png) You will see all your files under your selecting location. Now you will see all the files in the mdformat. you can change it to txtif you are not familiar with .md ![](https://cdn-images-1.medium.com/max/2832/1*z3p7WHWmg-5Knoht9OqGrA.png) Congratulation! now you can drag the folder or zip it importing to Evernotes, Bear, Microsoft Notes. This is not about the promotion but the way to save your time .
shijiezhou
807,018
Head First Design Pattern : 8 of 10
I just learnt a new design from the Head First Design Pattern book. Today, I learnt about the...
0
2021-08-29T11:01:10
https://dev.to/sanmiade/head-first-design-pattern-8-of-10-4d65
kotlin, programming
I just learnt a new design from the Head First Design Pattern book. Today, I learnt about the Iterator pattern. According to the head-first design pattern, the Iterator pattern is a pattern that allows you to access the elements of a collection sequentially without exposing its underlying representation. It allows you to extract the transversal logic of collections. It does so in a way that it makes transversing elements of any collection easier. Implementing the Iterator is pretty straightforward 1. Define an iterator interface ``` interface Iterator<out T> { fun hasNext() : Boolean fun next() : T } ``` The Iterator interface below has two methods. The `hasNext` and the `next`. The `hasNext` is used to check if the collection has items remaining while the `next` is used to get the next item from the collection. Instead of creating your implementation of the Iterator interface, you can also use the Iterator interface in Java. 2.Create a class that implements the Iterator interface. As you can see they all contain different kinds of collections. Without the Iterator pattern, you'll have to transverse each collection separately. ``` class MangaIterator(val mangas: List<Manga>) : Iterator<Manga> { var position: Int = 0 private set override fun hasNext(): Boolean { return if (position >= mangas.size || mangas.getOrNull(position) == null) false else true } override fun next(): Manga { val manga = mangas[position] position += 1 return manga } } ``` ``` class AnimeIterator(val animes: Array<Anime>) : Iterator<Anime>{ var position: Int = 0 private set override fun hasNext(): Boolean { return if (position >= animes.size || animes.getOrNull(position) == null) false else true } override fun next(): Anime { val manga = animes[position] position += 1 return manga } } ``` ``` class NovelIterator(val novels: HashMap<String, Novel>): Iterator<Novel> { var position: Int = 0 private set override fun hasNext(): Boolean { return if (position >= novels.values.size || novels.values.elementAt(position) == null) false else true } override fun next(): Novel { val novel = novels.values.elementAt(position) position += 1 return novel } } ``` ``` class TrackerApp() { fun <T> print(iterator: Iterator<T>) { while (iterator.hasNext()) { println(iterator.next()) } } } ``` ``` fun main() { val manga = listOf<Manga>( Manga("Relife", "Slice of Life"), Manga("Koe no katachi", "Slice of Life"), Manga("Vagabond", "Action") ) val anime = arrayOf(Anime("Konosuba", "Comedy"), Anime("Miss Koyobashi's Dragon maid", "Comedy")) val novels = hashMapOf<String, Novel>("Markus Zusak" to Novel("The book thief"), "Brandon Sanderson" to Novel("Mistborn")) val mangaIterator = MangaIterator(manga) val animeIterator = AnimeIterator(anime) val novelIterator = NovelIterator(novels) val trackerApp = TrackerApp() trackerApp.print(mangaIterator) trackerApp.print(animeIterator) trackerApp.print(novelIterator) Manga(name=Relife, genre=Slice of Life) Manga(name=Koe no katachi, genre=Slice of Life) Manga(name=Vagabond, genre=Action) Anime(name=Konosuba, genre=Comedy) Anime(name=Miss Koyobashi's Dragon maid, genre=Comedy) Novel(name=The book thief) Novel(name=Mistborn) } ``` Since the logic for transversing the collection has been encapsulated within an Iterator class. The TrackerApp can traverse any kind of collection so fat they implement the Iterator interface. The Iterator pattern shines when you have transverse different kinds of collections.
sanmiade
807,022
mysql 101
Hello fams, I started learning a relational database (Sequel Query Language) and I decided to make a...
0
2021-08-30T11:27:44
https://dev.to/drsimplegraffiti/mysql-101-1n6n
mysql, sql, database, beginners
Hello fams, I started learning a relational database (Sequel Query Language) and I decided to make a post to document my continuous progress. I stem from a NoSQL background (MongoDb). My choice software is Mysql and the Operating system used is windows. All commands should be the same. I have included examples in the <mark>Basic Queries Section </mark> ![minons](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/8l0zd9j7oy6ytcankk9r.gif) Table of Content 🎯 * [Installation (windows)](#installation) 🎯 * [Setup (Windows)](#setup) 🎯 * [Path Variable setup](#path) 🎯 * [Basic Queries](#queries) 🎯 * [Conclusion](#conclusion) 🎯 * [References](#references) <a name="installation"></a> Let's get right to it. Click the link [Download Link](https://dev.mysql.com/downloads/mysql/) to navigate to MySQL and download the MSI ![msi](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/3urum2u7yx0sjcftg070.PNG) <a name="setup"></a> I use Windows, and to run my SQL commands from my command prompt we need to add the download path (containing the binary) to our Environment variable. (Highlighted in red) ![path](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/k4r59qb4tvw38z8jhiv0.PNG) <a name="path"></a> Go to system properties 👉 Environmental Variables 👉 System variable 👉 Click on path 👉 click on edit 👉 click new 👉 paste the copied path highlighted in red earlier 👉 Ok. Now we have successfully added this path to our environment variable. ![system 5](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/exe6zom44pj9cb6b4umz.PNG) ![system3](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/e4n9fphkoixbq43scivq.PNG) ## Check if MySQL is running `$ mysql --version ` 📌 You should get ```MYSQL C:\Program Files\MySQL\MySQL Server 8.0\bin\mysql.exe Ver 8.0.25 for Win64 on x86_64 (MySQL Community Server - GPL) ``` --- With that out of the way let's login to our Mysql with the commands below <a name="queries"></a> ``` login to mysql from terminal (command prompt) mysql -u root -p mysql -u joseph -p ``` --- ## 🔗 **Create a specific user for a DataBase** `CREATE USER 'joseph'@'localhost' IDENTIFIED BY 'password';` 🔗 **To see selected users** `SELECT user, host FROM mysql.user;` 🔗 **Give privileges i.e full access** GRANT ALL PRIVILEGES ON * . * TO 'user'@'localhost'; `GRANT ALL PRIVILEGES ON * . * TO 'joseph'@'localhost';` 🔗 **Flush privileges after granting privileges** `FLUSH PRIVILEGES;` 🔗 **Check privileges for certain users** SHOW GRANTS FOR 'user'@'localhost'; SHOW GRANTS FOR 'joseph'@'localhost'; 🔗 **Exit mysql terminal to windows terminal by:** `exit;` ``` Login into mysql terminal mysql -u joseph -p ``` 🔗 **Actions** `SELECT * FROM users;` Note: Actions are mostly written in Capitals.( not compulsory just a convention). 🔗 **Create DB** `CREATE DATABASE ximple;` 🔗 **Show DB** `SHOW DATABASES;` 🔗 **To use the actual db** USE <database name> `USE ximple;` 🔗 ** Show tables** `SHOW TABLES;` 🔗 **Create table🔗 ** `CREATE TABLE employees( id INT AUTO_INCREMENT, first_name VARCHAR(100), last_name VARCHAR(100), email VARCHAR(75), password VARCHAR(255), location VARCHAR(100), dept VARCHAR(75), is_admin TINYINT(1), register_date DATETIME, PRIMARY KEY(id) );` NB: MAX LENGTH FOR VARCHAR is 255. 🔗 **Delete table** DROP TABLE <tablename>; `DROP TABLE users;` 🔗 **Delete Database** DROP DATABLE <databasename> `DROP DATABASE ximple;` 🔗 **Inserting single data** `INSERT INTO bands (name) VALUES ('Abayomi Joseph');` 🔗 **Insert** `INSERT INTO users (first_name, last_name, email, password, location, dept, is_admin, register_date) values ('James', 'Pork','james@gmail.com', '1234', 'Lagos', 'backend', 1, now());` 🔗 **Insert multiple values separated with commas** `INSERT INTO users (first_name, last_name, email, password, location, dept, is_admin, register_date) values ('John', 'Pork','john@gmail.com', '1234', 'Ibadan', 'frontend', 0, now())<mark>,</mark>('bale', 'mario','mario@gmail.com', '1234', 'Uyo', 'backend', 1, now());` 🔗 **Select values** `SELECT first_name, last_name FROM users;` 🔗 **WHERE clause** `SELECT* FROM users WHERE location = 'sagamu';` 🔗 **Multiple Conditions** `SELECT* FROM users WHERE location = 'sagamu' AND dept = "graphics";` 🔗 **ALTER TABLE test** `ADD another_column VARCHAR(255);` 🔗 **Bands table** `CREATE TABLE bands( id INT NOT NULL AUTO_INCREMENT, name VARCHAR(255) NOT NULL, PRIMARY KEY (id) );` 🔗 **Albums table linked to bands** `CREATE TABLE albums( id INT NOT NULL AUTO_INCREMENT, name VARCHAR(255) NOT NULL, release_year INT, band_id INT NOT NULL, PRIMARY KEY (id), FOREIGN KEY(band_id) REFERENCES bands(id) );` 🔗 **Inserting multiple data** `INSERT INTO bands (name) VALUES ('Abayomi Joseph'), ('the maxess'), ('blues');` 🔗 **Selecting with limits** `SELECT * FROM bands LIMIT 2;` 🔗 **Selecting specific property** `SELECT name FROM bands;` 🔗 **Renaming using the AS alias** `SELECT id AS 'ID', name AS 'Band Name' FROM bands;` 🔗 **Ordering and sorting data** `SELECT * FROM bands ORDER BY name;` 🔗 **Ordering and sorting data Descending order** `SELECT * FROM bands ORDER BY name DESC;` 🔗 **Ordering and sorting data ascending order** `SELECT * FROM bands ORDER BY name ASC;` 🔗 **Ordering and sorting data Descending order II ** `SELECT * FROM bands ORDER BY name;` 🔗 ** Multiple insert** `INSERT INTO albums(name, release_year, band_id) VALUES('the beast', 1990, 1), ('power shell', 1986, 2), ('the shark', 2009, 3), ('boom',NULL, 3);` 🔗 **Querying data** `SELECT * FROM albums; SELECT name FROM albums;` 🔗 **Selecting distinct data without duplicate** `SELECT DISTINCT name FROM albums;` 🔗 **Updating data** `UPDATE albums SET release_year= 1677 WHERE id = 1;` 🔗** Filtering data using the WHERE ** `SELECT * FROM albums WHERE release_year < 2000;` or `SELECT * FROM albums* WHERE release_year > 2000;` 🔗** Selecting using the string filter** `SELECT * FROM albums WHERE name LIKE '%er%';` ``` The above example is saying filter any string which has 'er' inside ``` 🔗 **The <mark>OR</mark> operator** `SELECT * FROM albums WHERE name LIKE '%er%' OR band_id=3;` 🔗 **The <mark>AND</mark> clause** `SELECT * FROM albums WHERE release_year=1986 AND band_id=1;` 🔗 **Filtering between two different values** `SELECT *FROM albums WHERE release_year BETWEEN 2000 AND 2009;` 🔗 ** Filtering NULL SELECT *FROM albums** `WHERE release_year IS NULL;` 🔗 **Delete clause** `DELETE FROM albums WHERE id = 4;` 🔗 **Join tables together** `SELECT * FROM bands JOIN albums ON bands.id = albums.band_id;` 🔗** Inner join work as above** `SELECT * FROM bands INNER JOIN albums ON bands.id = albums.band_id;` 🔗** LEFT JOIN** `SELECT * FROM bands LEFT JOIN albums ON bands.id = albums.band_id;` 🔗 **RIGHT JOIN** `SELECT * FROM albums RIGHT JOIN bands ON bands.id = albums.band_id;` --- ## AGGREGRATE FUNCTION 🔗 **AVERAGE** `SELECT AVG(release_year) FROM albums;` 🔗 **SUM** `SELECT SUM(release_year) FROM albums;` 🔗 **COUNT BY GROUP** `SELECT band_id, COUNT(band_id) FROM albums GROUP BY band_id;` 🔗 **Complex grouping** `SELECT b.name AS band_name, COUNT(a.id) AS num_albums FROM bands AS b LEFT JOIN albums AS a ON b.id = a.band_id GROUP BY b.id;` 🔗 **HAVING** `SELECT b.name AS band_name, COUNT(a.id) AS num_albums FROM bands AS b LEFT JOIN albums AS a ON b.id = a.band_id WHERE b.name = 'blues' GROUP BY b.id HAVING num_albums = 1;` --- <a name="conclusion"></a> ## Conclusion: This is a quick guide into using SQL if I miss any command or you have a better way of querying kindly drop it in the comment section. Thanks 🙌🏽 for reading <a name="reference"></a> ## References: 🍄 [Mike Dane Video](https://www.youtube.com/watch?v=HXV3zeQKqGY&t=58s) 🍄 [Traversy Media Video](https://www.youtube.com/watch?v=9ylj9NR0Lcg) {% github drsimplegraffiti/drsimplegraffiti %}
drsimplegraffiti
822,902
The PHP for loop
If you have something you want to repeat then consider using a PHP for loop, saving you from copying...
0
2021-09-13T19:57:52
https://www.csrhymes.com/2021/09/13/the-php-for-loop.html
php, beginners, tutorial, webdev
--- title: The PHP for loop published: true date: 2021-09-13 19:00:07 UTC tags: PHP,beginners,tutorial,webdev canonical_url: https://www.csrhymes.com/2021/09/13/the-php-for-loop.html cover_image: https://www.csrhymes.com/img/for-loop.jpg --- If you have something you want to repeat then consider using a PHP for loop, saving you from copying and pasting the same code multiple times. Adding the code into a loop means you only have to write it once, and you also only have to maintain the code in one place in future. The PHP for loop allows you to loop a defined number of times, until a defined condition is no longer true. ```php for ($i = 0; $i < 10; $i++) { echo $i; } // 0123456789 ``` This is what is happening: - Define a variable `$i` as zero `$i = 0;` - Keep looping if the variable `$i` is less than 10 `$i < 10;` - Each loop, add 1 to `$i` (increment) `$i++;` - If `$i` is no longer less than 10, then stop the loop and don’t add 1 to `$i` ## Breaking a for loop You can also break out of a for loop using the `break` keyword. In the example below, if the variable `$i` is equal to 5 then it will break out of the loop, ignoring the `$i < 10;` that we set previously in the loop definition. ```php for ($i = 0; $i < 10; $i++) { echo $i; if ($i === 5) { break; } } // 012345 ``` ## Without any expressions If you really wanted to you can leave the expressions empty in the for loop and define the variable before the loop, define the break inside the loop and increment the variable inside the loop as well. ```php $i = 0; for (; ; ) { if ($i === 5) { break; } echo $i; $i ++; } // 01234 ``` I honestly can’t think of a reason why you would do this though, except maybe if you don’t like your work colleagues very much… ## Looping through an array You can loop through an existing array using a for loop if we wanted to, using `$i` as the array key. The for loop variable needs to be initially defined as zero as array keys begin at zero `$i = 0;`. We can then use php’s `count()` function to count the length of the array. ```php $trees = ['oak', 'ash', 'birch', 'maple']; for ($i = 0; $i < count($trees); $i++) { echo $trees[$i] . ' '; } // oak ash birch maple ``` The downside to this code is that the `count($trees)` runs before each loop to check if the condition is still true. Instead, we can calculate the length of the array once and then pass that into the for loop. ```php $trees = ['oak', 'ash', 'birch', 'maple']; $treesCount = count($trees); for ($i = 0; $i < $treesCount; $i++) { echo $trees[$i] . ' '; } // oak ash birch maple ``` Also consider using a foreach loop for looping through an array as this will loop over the length of the array without calculating the length. ## Avoid using $i Many examples use `$i` as a variable in for loops, such as the php.net docs (also this article, oops), but try and use a more descriptive name as it will help you out when reading your code at a later date, and more importantly, if you have a for loop inside another for loop then you could end up overwriting the original `$i` variable, causing an infinite loop. ```php // Don't do this for ($i = 1; $i <= 10; $i++) { echo $i; // Some more code here for ($i = 0; $i <= 10; $i ++) { echo $i; } } // 1012345701234570123457012345701234570123457012345701234570123457012345701234570123457012345 etc, etc, ``` Instead, use descriptive variable names for you loop so you can better distinguish each variable in each loop. In this example we have 5 trees and each tree has 10 leaves. Don’t worry about the `<br />` tag, that is just for formatting. ```php for ($trees = 1; $trees <= 5; $trees++) { echo 'Tree ' . $trees . ' has leaves '; for ($leaves = 1; $leaves <= 10; $leaves ++) { echo $leaves . ', '; } echo '<br />'; } // Tree 1 has leaves 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, // Tree 2 has leaves 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, // Tree 3 has leaves 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, // Tree 4 has leaves 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, // Tree 5 has leaves 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, ``` For loops are very powerful tools, allowing you to save time and write cleaner and more maintainable code. Hopefully this introduction will get you thinking about how you could benefit from using them in future.
chrisrhymes
823,058
Bits of Good Bootcamp Lecture 3: JavaScript
So far you have been practicing with HTML and CSS to build simple static web pages. However, most...
0
2021-09-14T04:21:02
https://dev.to/luke9kim8/bits-of-good-bootcamp-lecture-3-javascript-1k2d
So far you have been practicing with HTML and CSS to build simple static web pages. However, most websites (or web apps) are more dynamic. Today, we will take our first step to make our websites dynamic using JavaScript. Unfortunately, before we could start using JavaScript on browsers, we need to go over the basics. This lecture will focus on helping you to get comfortable with the JavaScript syntax and get ready to apply it on your HTML/CSS web pages in the next lecture. ## Language Overview Here are some things you should know about JavaScript. First, JavaScript is loosely typed, meaning you don’t have to specify the exact type for variables and functions you use. Every modern browser should have some sort of JavaScript Engine that can run your JavaScript code. (include an image of browser - js engine) However, JavaScript can also be used as a server side language to build backend APIs. This means that you don’t have to depend on your browser to run your JavaScript. You can just run it on your computer and Node.js will act as the JavaScript engine. You can install Node.js from here https://nodejs.org/en/download/. For Windows people, pay attention to where you install your applications like Node.js, Git, Python, etc. Windows installers do not add your installed programs to path directly, which might give you an error when you try to run it on the command line. They will most likely be installed at `C:/Users/[your name]/Program Files`. If you ever get an error trying to run an application x, consider googling “How to add x to PATH Windows”. Let’s get started! Open up your VS Code and create a new file called `lecture3.js` ## Hello World Like all programs, we first start with Hello World. To print a line to the console, you would use `console.log("Hello World");`. ``` // lecture3.js // On your terminal or cmd, run "node lecture3.js" console.log("hello world"); ``` ## Declarations You don't have to explicitly declare the type of the variable like Java or C++ with JavaScript. However, it has its own keywords, which note the **scope** and the **mutability** of the variable. These keywords are `const`, `let`, and `var`. ### const When you don't want to change the variable's assignment, you use `const`. Once the variable is declared as `const`, you cannot change or reassign it! ``` const pixar = "Cars"; pixar = "Ratatouille"; // Illegal! Can't reassign! const pixar = "Coco"; // Illegal! Cant' redeclare! ``` ### var `var` used to be the default declaration for most variables. Any variables that are declared with the `var` keyword can be updated. ``` var x = 10; // After initializing x, if (x > 0) { x = 20; // You can update it b.c. x is declared with var } ``` But people don't use `var` anymore! That is because var is function scoped. As long as it is declared in a function, it can be accessed/updated/reassigned within the function. ``` var x = 10; var x = 20; if (x > 10) { var y = "I live in `if` block!"; } console.log(y); // This is totally legal with var! ``` ### let `let` was introduced on ES6 to replace some of `var`'s quirks. Unlike `var`, `let` is block scoped. This means the above example would be illegal with `let` because `y` is bounded within the if block. If you try to access it outside of its scope, you will get a reference error. ``` let x = 10; let x = 20; // Illegal! Syntax Error! Already declared! if (x > 10) { let y = "I live in `if` block!"; } console.log(y); // Illegal! Reference error! ``` **Conclusion** > When in doubt, use `let` over `var` to avoid breaking your code Before we move onto other JS topics, I'd like to quickly note a unique behavior of `const` objects and arrays. While you can't reassign a const object and arrays with new instances, you can modify its attribute or add new elements to it. When you declare a variable `const x = ["hello", "world"]`, you are assigning the reference to the array. This might confuse new programmers, but for now understand that modifying the values of const objects and array is possible. ``` // Arrays const array = [1,2,3,4]; array[0] = -1; // OK! array.push(5); // OK! array = [4,5,6,7]; // Not OK! This is reassigning! // Objects const teacher = { name: "Mr. Hendrix", subject: ["Math", "Physics"] age: 29 } teacher.age = 30; // OK! teacher.subject = ["Calculus", "Chemistry"] // OK! ``` ## Strings In JavaScript, Strings are immutable. This means you cannot modify any character of the string or append another string to it. ## Objects Objects in Java ## Functions ## Arrays
luke9kim8
823,259
[TensorFlow] Resolve CUDA DLL missing warning
*This article is written on Sep 14th 2021. It will be old in the future. Summary I got a...
0
2021-09-14T08:10:47
https://dev.to/ku6ryo/solve-cuda-dll-missing-warning-3819
tensorflow
*This article is written on Sep 14th 2021. It will be old in the future. ## Summary I got a CUDA DLL missing warning when I ran my TensorFlow program and tried to use GPU on Windows 11. Adding DLL import code in my program solved the issue. ```python import os os.add_dll_directory("C:/Program Files/NVIDIA GPU Computing Toolkit/CUDA/v11.2/bin") ``` *The CUDA toolkit version may be different for you. ## What happened to me I'm a beginner of TensorFlow. While setting up GPU binding, I encountered the following warning message. It means that GPU feature is not enabled because a CUDA DLL is missing. ``` W tensorflow/stream_executor/platform/default/dso_loader.cc:64] Could not load dynamic library 'cudart64_110.dll'; dlerror: cudart64_110.dll not found I tensorflow/stream_executor/cuda/cudart_stub.cc:29] Ignore above cudart dlerror if you do not have a GPU set up on your machine. ``` Then I realized I should install [CUDA toolkit](https://developer.nvidia.com/cuda-toolkit) and [cuDNN](https://developer.nvidia.com/cudnn) to use GPU to run ML code. I've read instructions provided by TensorFlow, NVIDIA and other developers and found that the versions of tools are very important. - [TensowFlow GPU support manual](https://www.tensorflow.org/install/gpu) - [cuDNN installation guide v8.1.0](https://docs.nvidia.com/deeplearning/cudnn/archives/cudnn-810/install-guide/index.html) Even by installing required version on the doc, it did not solve the problem. Finally I found a key comment in [a Github issue](https://github.com/tensorflow/tensorflow/issues/48868#issuecomment-841396124). ``` I was able to get past this error by doing os.add_dll_directory("C:/Program Files/NVIDIA GPU Computing Toolkit/CUDA/v11.2/bin") before importing tensorflow ``` *Even required version of tools are installed and PATH env variable is set as required. There is a case that DLLs are NOT imported as expected !!* My setup is like the below. ``` GPU: GeForce RTX 2080 Windows Edition: Windows 11 Pro Windows Version: 21H2 Python: 3.9.7 TensorFlow: 2.6.0 CUDA Toolkit: 11.2 cuDNN: v8.1.0 (January 26th, 2021), for CUDA 11.0,11.1 and 11.2 ``` ## Tips ### Message example when GPU feature is enabled ``` I tensorflow/core/common_runtime/gpu/gpu_device.cc:1510] Created device /job:localhost/replica:0/task:0/device:GPU:0 with 5967 MB memory: -> device: 0, name: NVIDIA GeForce RTX 2080, pci bus id: 0000:01:00.0, compute capability: 7.5 ``` ### Message example when cuDNN library it not appropriate ``` E tensorflow/stream_executor/cuda/cuda_dnn.cc:362] Loaded runtime CuDNN library: 8.0.5 but source was compiled with: 8.1.0. CuDNN library needs to have matching major version and equal or higher minor version. If using a binary install, upgrade your CuDNN library. If building from sources, make sure the library loaded at runtime is compatible with the version specified during compile configuration. ``` ### How to avoid Already installed error If CUDA toolkit installer shows the following error and you cannot install. You should uninstall a program pointed out in the error message. When I was installing several versions of CUDA Toolkit, it occurred. ![already_installed](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/xilwl9ia5gbg9u853xg1.png) ### PATH is important but you do not have to do anything CUDA Toolkit installer cares the PATH setting so you do not have to do anything. Just in case, I show my setup. CUDA_PATH ``` C:\Program Files\NVIDIA GPU Computing Toolkit\CUDA\v11.2 ``` CUDA_PATH_V11_2 ``` C:\Program Files\NVIDIA GPU Computing Toolkit\CUDA\v11.2 ``` *The version number may be different for your case. ### How to check if PATH is set correctly for DLLs. Run one of following commands if your error message says `cudart64_110.dll` is missing. If the command returns the absolute path to the file, your PATH setting is fine. The cause is another. Command Prompt ``` where cudart64_110.dll ``` PowerShell ``` Get-Command cudart64_110.dll ``` ## Traps ### cuDNN architecture support description is wrong [cuDNN archive v8.1.0 for 11.0 for windows](https://developer.nvidia.com/rdp/cudnn-archive#:~:text=Download%20cuDNN%20v8.1.0%20(January%2026th%2C%202021)%2C%20for%20CUDA%2011.0%2C11.1%20and%2011.2) shows download link for x86 but actually it's for x64.
ku6ryo
823,456
How to Reduce React App Loading Time By 70%
Steps to decrease your React app initial loading time using code splitting. We build large-scale...
0
2021-09-14T14:30:59
https://javascript.plainenglish.io/speed-up-your-react-app-initial-load-using-code-splitting-f2de58c01ed2
react, javascript, webdev, beginners
Steps to decrease your React app initial loading time using code splitting. We build large-scale apps using React. When building these apps, the major issue we face is app performance. When the app grows larger and larger, the performance might deteriorate. Particularly the initial loading time of the app will be affected more. Initial app loading needs to be fast without showing a blank screen for few seconds to the user. As taking more time to load will create a bad impression for the user. The major cause for this issue is adding too many components into a single bundle file, so the loading of that bundle file might take more time. To avoid this kind of issue, we need to structure our components in an optimized way. To solve this react itself has a native solution, which is code-splitting and lazy loading. Which allows splitting bundle files into a smaller size. The best place to introduce code splitting is in routes. Route-based code splitting solve half of the issues. But most of the apps are utilizing only 50% of the advantages of code splitting. Are we structuring the components properly when using code splitting? We can see why and how to fix it using some code samples. For that, we are going to use a sample React app with some UI components. In the below screenshot, we can see a dashboard component, which has multiple tabs. Each tab has multiple components. ![dashboard component](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/m86yxfplki8f6m4y85ps.png) The Dashboard component uses route-based code splitting as the below code. {% gist https://gist.github.com/Nilanth/afd17cb0cb15b014efb99048f44553b0 %} The Dashboard component contains some sub-components like Sales, Profit, Chart, Tiles and Trends like the below code {% gist https://gist.github.com/Nilanth/5ed60b31397d81103e1252d71230d396 %} We have split the code into routes. so when the app is bundled, we get a separate build file for each route as below ![build-files](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/ilf5k7rggx1l1zv2zccb.png) From the above image, the file with a size **405.1 KB** is the dashboard component and other files are for the Header, sidebar, other components and CSS. I have hosted the app in [Netlify](https://www.netlify.com/) to test the performance. As if we test the app locally we cannot find the difference. When I tested the hosted app with [GTmetrix](https://gtmetrix.com/), the dashboard screen took **2.9 seconds** to load, Check the below image for frame by frame loading. ![frames](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/dfgai6a0xk1w7gfbvz10.png) The dashboard component is the initial page for this app, so when we hit the App URL **405.1KB** file will be loaded along with the header and sidebar. Initially, the User will view only the **Sales** tab, But our sample app dashboard component has multiple tabs. So the browser is downloading other tabs code also, it is delaying the first paint for the user. To decrease the initial load time, we need to make some changes to the dashboard component as below {% gist https://gist.github.com/Nilanth/f4236862a5748873bc9e53fec9689239 %} Here I have imported each tab component with lazy loading and wrapped the component with suspense. > Here I have added multiple suspense for better understanding, but you can use single suspense for all the components. I have not done any changes to route level code-splitting. When we build the app, some extra files are added as we have lazy-loaded each tab in the dashboard component. Check the below image for build file separation. ![build-splitcoding](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/268n08iakvetd2hd0b5k.png) Now let's test the app with GTmetrix again with the above changes. See the App performance in the below image ![frames-code](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/hi2z7p6rtx8gp1h31fox.png) As you can see, Now our dashboard component is loaded in **1 second**, as **Sales** tab code only loaded now. We have reduced almost **2 seconds** by making some changes. Let see the comparison of route-based and route, component-based code-splitting in the below images. ![route-based-frames](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/refnafbfm38huv20sajl.png) <figcaption>Route Based Code Splitting</figcaption> ![component-based-frames](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/k2agdjoxwnu2h98543s6.png) <figcaption>Route and Component Based Code Splitting</figcaption> As you see, this is a huge improvement in the app initial load. Now we have reduced the React app initial load time by 70% with a few tweaks by using code splitting effectively in the dashboard component. ## Reference 1. [Code Splitting](https://reactjs.org/docs/code-splitting.html#code-splitting) 2. [First Contentful Paint](https://gtmetrix.com/blog/first-contentful-paint-explained/) ## Conclusion Structuring components in an optimized way and using React APIs effectively will increase the performance of large-scale apps. Thank you for reading. Get more updates on [Twitter](https://twitter.com/Nilanth). **You can support me [by buying me a coffee](https://buymeacoffee.com/nilanth) ☕** ## eBook [Debugging ReactJS Issues with ChatGPT: 50 Essential Tips and Examples](https://nilanth.gumroad.com/l/ztehh) [ReactJS Optimization Techniques and Development Resources](https://nilanth.gumroad.com/l/NYkdN) ## More Blogs 1. [Twitter Followers Tracker using Next.js, NextAuth and TailwindCSS](https://dev.to/nilanth/twitter-followers-tracker-using-nextjs-nextauth-and-tailwindcss-1em7) 2. [Don't Optimize Your React App, Use Preact Instead ](https://dev.to/nilanth/dont-optimize-your-react-app-use-preact-instead-30og) 3. [Build a Portfolio Using Next.js, Tailwind, and Vercel with Dark Mode Support](https://dev.to/nilanth/build-a-portfolio-using-next-js-tailwind-and-vercel-4dd8) 4. [No More ../../../ Import in React](https://dev.to/nilanth/no-more-import-in-react-2mbo) 5. [10 React Packages with 1K UI Components ](https://dev.to/nilanth/10-react-packages-with-1k-ui-components-2bf3) 6. [Redux Toolkit - The Standard Way to Write Redux](https://dev.to/nilanth/redux-toolkit-the-standard-way-to-write-redux-2g32) 7. [5 Packages to Optimize and Speed Up Your React App During Development](https://dev.to/nilanth/5-packages-to-optimize-and-speed-up-your-react-app-during-development-4h5f) 8. [How To Use Axios in an Optimized and Scalable Way With React](https://dev.to/nilanth/how-to-use-axios-in-an-optimized-and-scalable-way-with-react-518n) 9. [15 Custom Hooks to Make your React Component Lightweight](https://dev.to/nilanth/15-custom-hooks-to-make-your-react-component-lightweight-17cd) 10. [10 Ways to Host Your React App For Free](https://dev.to/nilanth/10-ways-to-host-your-react-app-for-free-27ga) 11. [How to Secure JWT in a Single-Page Application](https://dev.to/nilanth/how-to-secure-jwt-in-a-single-page-application-cko)
nilanth
823,475
What is AWS Lambda?
Hello, in this article I wanted to talk about what is AWS Lambda and why we should use it; AWS...
0
2021-09-16T12:03:23
https://dev.to/ozersubasi/what-is-aws-lambda-d1k
aws, serverless, awslambda
Hello, in this article I wanted to talk about what is AWS Lambda and why we should use it; AWS Lambda is a serverless computing service to run written code without the need to provision and manage servers. Thanks to AWS Lambda, *our code runs only when needed* and is *charged according to the processing time*, **there is no charge when the code is not running**. The need can vary from a few requests per day to thousands of requests per second, in which case AWS Lambda automatically *scales* to prevent any loss in performance. AWS Lambda, runs the written code on a highly available infrastructure and *performs all the operations* such as capacity and automatic scaling, system maintenance and logging. We just need to write our code in one of the languages that AWS Lambda supports. ## Why we should use AWS Lambda? AWS Lambda is an ideal service for many standart scenarios. We need to create an infrastructure before starting application development. Hosting a server, performing the necessary installations, coding and running the application; these are mean seperate workloads. Wouldn't be nice to do only code and run the application without dealing with all these? Well, that's the best part of working serverless! We write the code, upload as a ZIP or container image and application is ready to go! Now all we need is trigger this Lambda function. Function will run only whenever triggered and will not charge when it is not running! ![image](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/5l5zolwduhyk62ztrk2x.png) Of course, it may be easy to do these steps now, there may be questions in mind such as what is what makes AWS Lambda attractive? But wait! we just ran the application! In the free version of AWS Lambda, the first 1 million request per month are free, then it is calculated according to milliseconds and the number of times the code is triggered and the cost will only $0.20 per 1 million request. >*In other words, the cost of implementing an idea quickly and testing whether it will work is almost zero!* In addition, there is a discount up to %17 with plans such as the *Compute Savings Plan* on the services you will use on production. *Scalability* is the most important thing that makes AWS Lambda attractive. There is no matter how many instant request your application getting, even if there are hundreds of thousands of instant request, AWS Lambda scales through the need and you don't need to worry about inaccessibility and continue without any problems. The good side of that is no need to spend lots of money for the server and don't need to consider the risk of inaccessibility if the application suddenly get thousands of instant requests or more. The run time of the code can be also optimized by select appropriate memory size for the function to be executed. In this way, function will perform consistently at the appropriate scale. The following workflow example demonstrates the operation steps of weather application; ![image](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/bzzmatimig7zzqypql9i.png) User, clicks the link to find out the weather conditions in their area. Amazon API Gateway makes API call to the related endpoint. Lambda is triggered here. Lambda function gets weather condition information of the region requested by the user from DynamoDB and returns to the user. Besides, there are many scenarios where AWS Lambda used on AWS.Here you can see the Todo application source code folders as an example. AWS Cognito used as the user authentication method, and you can see that each required function for Todo App is foldered separately in the below image. ![image](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/96x4zl37nsjjbc4zjyaq.png) Source: https://aws.amazon.com/tr/lambda/
ozersubasi
823,567
An Introduction to Metaprogramming in Elixir
In this world, there are many mysteries — but few are as elusive as metaprogramming in Elixir. In...
14,604
2021-09-14T12:28:26
https://blog.appsignal.com/2021/09/07/an-introduction-to-metaprogramming-in-elixir.html
elixir
In this world, there are many mysteries — but few are as elusive as metaprogramming in Elixir. [In this four-part series](https://blog.appsignal.com/category/under-the-hood-of-metaprogramming.html), we'll start by looking at core concepts and then explore how metaprogramming operates in Elixir specifically. Let's develop an understanding of metaprogramming and uncover some Elixir metaprogramming secrets! ## Introducing Metaprogramming in Elixir According to Harald Sondergaard, metaprogramming is: > a programming technique in which computer programs have the ability to treat other programs as their data; meaning that > a program can be designed to read, generate, analyze, or transform other programs, and even modify itself while > running. In essence, metaprogramming — much like metadata — revolves around "a set of programs that describe and give information about other programs" (adapted from the [Oxford dictionary definition of metadata](https://www.lexico.com/definition/metadata)). ## Types of Metaprogramming There are two types of metaprogramming that prescribe varying degrees of control over a given program: ### Introspection Introspection refers to a program revealing metadata about other programs or itself. This definition broadly covers the first part of the definition of metaprogramming: "a program can be designed to read...[and] analyze...other programs". The program has access to information about itself or other programs. ### Reflection Reflection refers to a program modifying other programs or itself. If a program can modify other programs or itself, it — by definition — has access to the metadata of the program, revealing information like names of functions. By looking at the two types of metaprogramming, we can conclude that reflection encompasses introspection, or introspection is a subset of reflection: ![Types of metaprogramming](https://blog.appsignal.com/images/blog/2021-09/metaprogramming-types.png) ## Why Do Metaprogramming? We will look at how to use metaprogramming specifically in Elixir. But first, let's cover some general concepts and benefits of metaprogramming. According to Wikipedia, metaprogramming can be used to (but not limited to) achieve the following: 1. Move computations from run-time to compile-time 2. Generate code using compile-time computations 3. Enable self-modifying code Observe that among these use cases (as well as across metaprogramming), the terms "run-time" and "compile-time" are used frequently. Let's see what they mean. ## Defining Run-time and Compile-time We can broadly classify metaprogramming into two categories: compile-time and run-time metaprogramming. But what exactly are run-time and compile-time? They both refer to stages of a program's life cycle. Compile-time is the stage at which source code converts to binary code or intermediate binary code for a machine or virtual machine to execute. Run-time refers to when code executes. The program life cycle includes the following steps: ![Typical program lifecycle](https://blog.appsignal.com/images/blog/2021-09/program-lifecycle.png) *Source: https://en.wikipedia.org/wiki/Program_lifecycle_phase* Note that this is not a complete representation of the entire program life cycle, just a simplified one. Compilation "sets the program in stone" by converting it into binary code. Metaprogramming exposes this process to allow developers to "move computation from run-time to compile-time" or "generate code using compile-time computations". This essentially allows the modification of the source code before/during compile-time, meaning that the generated binary code is slightly different. Self-modifying code is rather unique. In essence, it performs reflection during run-time. The life cycle of a self-modifying program looks a little different: ![Program lifecycle of a self-modifying program](https://blog.appsignal.com/images/blog/2021-09/self-modifying-program-lifecycle.png) **Note:** You can substitute the "binary" for any intermediate language generated by the compiler, such as JVM bytecode or, in Elixir's case, BEAM VM bytecode. ## Interesting Uses of Metaprogramming The general definition of metaprogramming also encompasses the tools used in a program's life cycle. For instance, a language compiler is a metaprogramming application designed to receive another program as input and generate binary as output. We can narrow down broad metaprogramming use cases to the following, more specific, applications in a programming language context: ### Code generation By generating code dynamically during compile-time, it's available during run-time. When the nature of the code that's generated is not fixed, this can prove especially useful. For instance, you can use code generation to design domain-specific languages (DSLs) or generate functions based on input such as files or APIs. ### Code instrumentation Code instrumentation refers to the measure of a program's performance, error diagnosis, and logging of trace information. Metaprogramming enables this through dynamic program analysis — software analysis performed by running software through a real or virtual processor. Code instrumentation enables features like code coverage, memory error detection, fault localization, and concurrency errors. ### Behavioral changes This refers to changing the behavior of a program through metaprogramming. Behavioral changes can include [feature toggling](https://martinfowler.com/articles/feature-toggles.html), where a given feature is toggled on/off through a flag that is read during compile-time/run-time. This article series is about metaprogramming within Elixir, so our key focus will be on code generation. ## Metaprogramming in Elixir: The Basics Elixir applies a style of metaprogramming known as macro system metaprogramming (also used in other languages like Rust and Lisp). In Elixir, metaprogramming allows developers to leverage existing features to build new features that suit their individual business requirements. The foundation of metaprogramming in Elixir is macros. ## Defining Macros According to the [official documentation](https://hexdocs.pm/elixir/1.12/Macro.html): > Macros are compile-time constructs that are invoked with Elixir's AST as input and a superset of Elixir's AST as > output. There are two critical components to this definition. Let's break them down: - **Compile-time constructs** - evaluated and available during compile-time - **Elixir's AST** - Abstract Syntax Trees (ASTs) are tree representations of the abstract syntax structure of the source code We use the representations of the source code as building blocks for compile-time constructs. Since the compiler reasons with the source code through ASTs, we effectively "speak" the compiler's language to build constructs that it can directly reason with. In Elixir, ASTs are [tuples](https://hexdocs.pm/elixir/2.12/Tuple.html), so we reason with the compiler in a manner that is familiar to us. We do not need to deviate from Elixir's syntax to begin writing macros - lowering our barrier to entry of learning macros. On top of that, we do not even need to write ASTs ourselves. There are constructs in Elixir to handle all of that heavy lifting for us. The above definition also mentions how a macro receives an AST as input and returns a superset of AST as output. So, you can think of a macro as a regular function with inputs, behavior, and an output. The overall goal is to use a given AST to generate a new AST for the compiler to use. There is more to come on the compilation process of Elixir programs in part two of this series. ## Starting Small with Macros Now that we understand macros, let's dip our toes into the water and implement a basic macro. We'll start with a very basic comparison of a macro to a regular function. The [Elixir documentation](https://hexdocs.pm/elixir/1.12/Macro.html) inspires this code example: ```elixir defmodule Foo do defmacro macro_inspect(value) do IO.inspect(value) value end def func_inspect(value) do IO.inspect(value) value end end ``` To define a macro, we use `defmacro` and declare the parameters just as we would a regular function. Running the macro in [IEX](https://hexdocs.pm/iex/IEx.html) yields the following results: ```elixir iex(1)> import Foo iex(2)> macro_inspect(1 + 2) {:+, [context: Elixir, import: Kernel], [1, 2]} 3 iex(3)> func_inspect(1 + 2) 3 3 ``` Observe that rather than printing the result of `1 + 2`, the macro prints a tuple instead (the AST as input that we defined earlier). When a macro is first declared, the arguments of that macro are automatically converted into AST so that you don't need to parse the arguments manually. The arguments will not be evaluated beforehand. However, when the value of the macro is returned, it yields the result of `1 + 2`. The macro should return an AST as output (and it is). However, this AST as output is compiled and executed once the macro is called. The expression `1 + 2` is evaluated first, then returned. Once we understand the basic syntax and declaration of a macro, we can explore the structure of the AST. ## AST Structure As mentioned earlier, the AST is the representation of the source code as a syntax tree. In the example above, we inspect the AST of the expression `1 + 2`. We can break down the AST structure into three components: 1. Atom — representing the name of the operation 2. Metadata of the expression 3. Arguments of the operation ```elixir { :+, # operation name, [context: Elixir, import: Kernel], # metadata, [1, 2] # operation arguments } ``` While you must understand what comprises an AST, we rarely need to read/write raw ASTs. Elixir makes it ridiculously easy to interface with macros, so we hardly even need to think about the structure of the AST that we are working on — everything is handled for us. ## Interacting with ASTs As mentioned earlier, ASTs represent the source code and are the input and output of macros. They are the cornerstone of macros. We need to interact with the AST representations of expressions freely, without getting bogged down by reading and writing the ASTs ourselves. This is where `quote` and `unquote` come into the picture. To generate the AST representation of an expression or body, we use `quote`: ```elixir quote do 1 + 2 * 3 end {:+, [context: Elixir, import: Kernel], [1, {:*, [context: Elixir, import: Kernel], [2, 3]}]} ``` When we use `quote`, we build an AST. While the example above is relatively simple, we will soon discover that `quote` can be used to build much more complex ASTs. What if we have a value we want to use in our `quote`, such as the arguments? We attempt to introduce an external (outside of `quote`) variable into `quote`, by using `unquote`. `unquote` evaluates its argument, which is an expression, and injects the result (as an AST) into the AST being built. As [everything in Elixir is an expression](https://elixir.bagwanpankaj.com/2014/02/25/introduction-to-elixir/), we evaluate expressions to inject the results. For instance, if `unquote` receives a variable, we will evaluate that expression as the underlying expression referenced by the variable and inject that. If `unquote` receives a full expression like `1 + 2 * 3`, we will evaluate that to `7` and inject that. `unquote` expects that the result of the expression is a valid AST. In part two of this series, we'll discuss the consequences of having an invalid AST and delve into macros more deeply. Do you recall that macros automatically convert arguments into their AST forms? We will leverage that behavior: ```elixir defmodule Foo do defmacro foo(exp) do quote do doubled = unquote(exp) * 2 doubled end end end Foo.foo(1 + 2 * 3) 14 ``` As you can see, we have built a macro called `foo` which receives an expression as an argument. Then, we begin to build an AST for the macro in `quote`. We use `unquote(exp)` to inject the value of the `exp` argument into the AST. You might ask yourself: How do I know that the expression is injected and not evaluated right away? Well, we can use a handy tool to inspect the AST of the macro and understand how it works under the hood: ```elixir iex(1)> require Foo iex(2)> ast = quote do: Foo.foo(1 + 2 * 3) iex(3)> ast |> Macro.expand(__ENV__) {:__block__, [], [ {:=, [], [ {:doubled, [counter: -576460752303423358], Foo}, {:*, [context: Foo, import: Kernel], [ {:+, [context: Elixir, import: Kernel], [1, {:*, [context: Elixir, import: Kernel], [2, 3]}]}, 2 ]} ]}, {:doubled, [counter: -576460752303423358], Foo} ]} ``` First, we generate the AST of the macro call and assign it to a variable. Then, with our `ast` variable, we will use `Macro.expand` to expand the AST to its fullest form. We'll look at macro expansion next time. For now, think of it as peeling back the layers of an AST to its most fundamental components. As you can see, the expanded form of the `Foo.foo` call contains the AST of `1 + 2 * 3`. This proves that `unquote` only injected the AST of the expression into the `quote` AST, but didn't evaluate it. The evaluation is performed later on (we will get into this in part two as well). **Note:** `Macro.expand` will only attempt to perform expansion on the root node of the AST. [You can find more information about `Macro.expand`in the docs](https://hexdocs.pm/elixir/1.12/Macro.html#expand/2). ## `quote` Options in Elixir Now that we understand the fundamentals of macros, we can start to look at our `quote` options. While [there are several options with `quote`](https://hexdocs.pm/elixir/1.12/Kernel.SpecialForms.html#quote/2-options), we will focus on the three most frequently used and introduce the concepts behind each option. - **`unquote`** Toggles the unquoting behavior in `quote`. By disabling it, any `unquote` call is converted to an AST of the macro call (as with any other macro/function call). This defers the evaluation of `unquote` to a later point. I'll explain why you'd want to do so in the next part of this series. For now, let's look at the following example: ```elixir iex(1)> a = [foo: 1, bar: 1] iex(2)> ast = quote do: unquote(a) [foo: 1, bar: 1] iex(3)> ast = quote unquote: false, do: unquote(a) {:unquote, [], [{:a, [], Elixir}]} ``` When we leave the unquoting behavior enabled (`iex(2)`), `unquote(a)` will evaluate `a` as an expression. This returns the keyword list, which is then injected into the `quote` AST — and the result is as expected. However, when we disable the unquoting behavior (`iex(3)`), `unquote(a)` is converted into another AST expression, which is injected into the `quote` AST as-is. - **`bind_quoted`** Disables unquoting behavior in the `quote` and binds given variables in the body of `quote`. Binding moves the variable initialization into the body of `quote`. We can observe this behavior using `Macro.to_string`: ```elixir iex(1)> a = [foo: 1, bar: 2] iex(2)> ast = quote bind_quoted: [a: a], do: IO.inspect(a) iex(3)> ast |> Macro.to_string |> IO.puts ( a = [foo: 1, bar: 2] IO.inspect(a) :ok ) :ok ``` As you can see, `bind_quoted` adds a "copy" of `a` into the body of `quote` by assigning it in the body of `quote`. In a macro, this is equivalent to binding the variable to the caller context, as the variable is initialized during the evaluation of the callsite. **Note:** Contexts will be discussed in greater detail next time. ```elixir defmodule Foo do defmacro foo(x) do quote bind_quoted: [x: x] do IO.inspect(x) end end end ``` - **`location`** This option controls whether run-time errors from a macro are reported from the caller or inside the quote. By setting this option to `:keep`, error messages report specific lines in the macro that cause the error, rather than the line of the callsite. [You can see a code example in the docs](https://hexdocs.pm/elixir/Kernel.SpecialForms.html#quote/2-stacktrace-information). ## Build a Simple Macro in Elixir We should now be able to build a simple macro that mimics the behavior of an `if` statement. Recall that an `if` statement is comprised of the following components: ```elixir if (condition) do # body else # body end ``` We can replicate this structure using our own macro: ```elixir defmodule NewIf do defmacro if?(condition, do: block, else: other) do quote do cond do unquote(condition) == true -> unquote(block) unquote(condition) == false -> unquote(other) end end end end iex(1)> require NewIf iex(2)> NewIf.if? 4 == 5, do: :yes, else: :no :no ``` This macro can receive three arguments: - `condition` - predicate to evaluate `if?` statement against - `do` - block to execute when `condition` is true - `else` - block to execute when `condition` is false In Elixir, such blocks can be declared as arguments if they follow the following syntax: `<formal name>: <variable name>`. The formal name is the name used when you call the macro. The variable name is the name used in the macro when you're attempting to reference the block. After receiving these three arguments, we start by building an AST using `quote`. Using a `cond` statement, we determine which body `if?` should execute. We use `unquote` to inject the values of `condition`, `block`, and `other` into the AST we are building. In doing so, when the macro is evaluated, the condition is evaluated to be `true`/`false`, and, based on that result, we will either execute `block` or `other`. We wrap up this behavior into an AST returned by `quote` (which is the return value of the macro). ## Next Up: Macros in Detail Now we have a good grasp on the foundations of metaprogramming in general and specifically in Elixir. Join me for the next part of this series, where we'll look into the intricacies behind macros and how everything works. Until next time! **P.S. If you'd like to read Elixir Alchemy posts as soon as they get off the press, [subscribe to our Elixir Alchemy newsletter and never miss a single post!](https://blog.appsignal.com/category/elixir-alchemy.html#elixir-alchemy)** *Jia Hao Woo is a developer from the little red dot - Singapore! He loves to tinker with various technologies and has been using Elixir and Go for about a year. Follow his programming journey at [his blog](https://woojiahao.github.io/blog) and on [Twitter](https://twitter.com/woojiahao_).*
woojiahao
823,572
Mobile Charging cable – Can be an EVIL, Can Send Data to a Remote Attacker
A new and upgraded version of a malicious Lightning cable that can steal user data and remotely send...
0
2021-09-14T12:40:19
https://dev.to/gopinarayanasw3/mobile-charging-cable-can-be-an-evil-can-send-data-to-a-remote-attacker-3j3m
A new and upgraded version of a malicious Lightning cable that can steal user data and remotely send it to an attacker illustrates the threat of untrusted accessories. Security researcher Mark Green, (who goes by MG) has revealed to the Vices team at Motherboard that he and his team have upgraded their version of a hacked Lightning cable in a way that allows a hacker to record keystrokes and then to send the data to a designated site. This would allow the device to be used to steal passwords and other sensitive information. The OMG Cable, which looks exactly like a standard lightning to USB cable, was first demoed back in 2019 by security researcher MG. Since then, MG was able to work with cyber security vendor Hak5 to mass-produce the cables for researchers and penetration testers. It can hack both Android, Apple devices and hack your systems If you have a device and you plug it in there, there's a possibility that your confidential information will be hacked. The data will be sent to the remote attacker. There are USB charging cable with IP Address included also a vulnerable to attackers and can be operate from miles away. The attackers can exploit the user's device by obtaining their data when the cable was connected. So please aware, while borrowing USB cable from someone or charging in a public place
gopinarayanasw3
823,618
Accessibility testing
I was doing some accessibility work with a client a little while back. It was mostly giving their...
0
2021-11-07T07:48:04
https://adactio.com/journal/18458
a11y, testing, colour
--- title: Accessibility testing published: true date: 2021-09-14 10:59:06 UTC tags: accessibility,a11y,testing,colour canonical_url: https://adactio.com/journal/18458 --- I was doing some accessibility work with a client a little while back. It was mostly giving their site the once-over, highlighting any issues that we could then discuss. It was an audit of sorts. While I was doing this I started to realise that not all accessibility issues are created equal. I don’t just mean in their severity. I mean that some issues can—and should—be caught early on, while other issues can only be found later. Take [colour contrast](https://www.w3.org/TR/WCAG21/#distinguishable). This is something that should be checked before a line of code is written. When designs are being sketched out and then refined in a graphical editor like Figma, that’s the time to check the ratio between background and foreground colours to make sure there’s enough contrast between them. You _can_ catch this kind of thing later on, but by then it’s likely to come with a higher cost—you might have to literally go back to the drawing board. It’s better to find the issue when you’re at the drawing board the first time. Then there’s [the HTML](https://www.w3.org/TR/WCAG21/#navigable). Most accessibility issues here can be caught before the site goes live. Usually they’re issues of ommission: form fields that don’t have an explicitly associated `label` element (using the `for` and `id` attributes); images that don’t have `alt` text; pages that don’t have sensible heading levels or landmark regions like `main` and `nav`. None of these are particularly onerous to fix and they come with the biggest bang for your buck. If you’ve got sensible forms, sensible headings, `alt` text on images, and a solid document structure, you’ve already covered the vast majority of accessibility issues with very little overhead. Some of these checks can also be automated: `alt` text for images; `label`s for inputs. Then there’s [interactive stuff](https://www.w3.org/TR/WCAG21/#operable). If you only use native HTML elements you’re probably in the clear, but chances are you’ve got some bespoke interactivity on your site: a carousel; a mega dropdown for navigation; a tabbed interface. HTML doesn’t give you any of those out of the box so you’d need to make your own using a combination of HTML, CSS, JavaScript and ARIA. There’s plenty of testing you can do before launching—I always ask myself “[What would Heydon do?](https://inclusive-components.design/)”—but these components really benefit from being tested by real screen reader users. So if you commission an accessibility audit, you should hope to get feedback that’s mostly in that third category—interactive widgets. If you get feedback on document structure and other semantic issues with the HTML, you should fix those issues, sure, but you should also see what you can do to stop those issues going live again in the future. Perhaps you can add some steps in the build process. Or maybe it’s more about making sure the devs are aware of these low-hanging fruit. Or perhaps there’s a framework or content management system that’s stopping you from improving your HTML. Then you need to execute a plan for ditching that software. If you get feedback about colour contrast issues, just fixing the immediate problem isn’t going to address the underlying issue. There’s a process problem, or perhaps a communication issue. In that case, don’t look for a technical solution. A design system, for example, will not magically fix a workflow issue or route around the problem of designers and developers not talking to each other. When you commission an accessibility audit, you want to make sure you’re getting the most out of it. Don’t squander it on issues that you can catch and fix yourself. Make sure that the bulk of the audit is being spent on the _specific_ issues that are unique to your site.
adactio
823,622
The State of Taking Props to School
From my experience as an instructor state and props can really throw React beginners for a loop. The...
0
2021-09-18T11:41:03
https://dev.to/arynnboniface/the-state-of-taking-props-to-school-47j1
react, javascript, beginners
From my experience as an instructor state and props can really throw React beginners for a loop. The good news is that loop doesn't need to be endless (😅). ### State & Props: What Are They? ![Very Confused Little Girl](https://media.giphy.com/media/kaq6GnxDlJaBq/giphy.gif?cid=ecf05e47gs0a01ztemrj14vjzgarsrbjqj231vbvgg949xmp&rid=giphy.gif&ct=g) > `props` (short for “properties”) and `state` are both plain JavaScript objects. While both hold information that influences the output of render, they are different in one important way: `props` get passed to the component (similar to function parameters) whereas `state` is managed within the component (similar to variables declared within a function). [Reactjs.com - Component State](https://reactjs.org/docs/faq-state.html) Uh, yeah, okay... but what does that mean? Well, let's take a look at a real world example. Think way back to your grade school days. Remember field trips? And permission slips? Your mom, dad or parental guardian had to sign a permission slip in order for you to go on a field trip. You brought that permission slip to your teacher and showed it to them to prove that you were allowed to go. This is a great way to think about state and props. *I'm going to use hooks and functional components in these examples, but class components will work, too.* Starting out, the browser looks like this: ![Browser with two divs, "I am the parent." and "I am the child."](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/wkxxpiiesm16sqdq1s8q.png) The `Parent` component is rendered in `App.js`. Here is the starting code for both `Parent` and `Child`: ```js import Child from './Child'; const Parent = () => { return ( <div className="container"> <div className="parent"> <h2>I am the parent.</h2> </div> <div className="child"> <Child /> </div> </div> ); }; export default Parent; ``` and here is the starting code for `Child`: ```js const Child = () => { return ( <div className="child-component"> <h3>I am the child.</h3> </div> ); }; export default Child; ``` The first thing we're going to do is set up `state` in our `Parent` component. ```js const [isSigned, setIsSigned] = useState(false); const location = "the science museum"; ``` The permission slip for the science museum begins in an unsigned state. Now we need to set up some way for our `Parent` to sign the permission slip for their child. We'll stick to a simple click event on a button. The button will also render conditionally, based on the value of our `isSigned` state. ```js const handleClick = () => { isSigned ? setIsSigned(false) : setIsSigned(true); }; const renderButton = () => { return !isSigned ? <button onClick={handleClick}>Sign Permission Slip</button> : <button onClick={handleClick}>You're Grounded!</button> }; ``` We now want to invoke `renderButton` right under our `h2` tag in the `Parent` component. This is what we see in the browser now: ![Parent and Child component with button](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/w6hefq89rjadp33x0tpe.png) In order to make sure our button *actually works*, we're going to add `{console.log(isSigned)}` inside of our `Parent` component. Our code should look something like this: ```js const Parent = () => { const [isSigned, setIsSigned] = useState(false); const location = "the science museum"; const handleClick = () => { isSigned ? setIsSigned(false) : setIsSigned(true); }; const renderButton = () => { return !isSigned ? <button onClick={handleClick}>Sign Permission Slip</button> : <button onClick={handleClick}>You're Grounded!</button> }; return ( <div className="container"> {console.log(isSigned)} <div className="parent"> <h2>I am the parent.</h2> {renderButton()} </div> <div className="child"> <Child /> </div> </div> ); }; ``` This is what we should see after our first button click: ![Signed Permission Slip](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/u0nd5yts0zohjqkse23n.png) and if we click one more time: ![Field trip permission: revoked!](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/rh4g4jbpv9o0m27qwv1g.png) Now that we know everything is working correctly in our `Parent` component, we can start thinking about `props`! Our `Child` needs some way to tell their teacher whether they can or cannot go on the field trip. We need to pass this information down to our `Child`. ```js <div className="child"> <Child location={location} isSigned={isSigned} /> </div> ``` This is how we pass information from parent to child. In our `Child` component, we pass the `props` in as an argument. ```js const Child = (props) => { console.log(props) return ( <div className="child-component"> <h3>I am the child.</h3> </div> ); }; ``` With that `console.log`, we'll see this in browser console: ![Console log of props](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/l4zsi875771rlae43nnf.png) We can make things a little cleaner here by using destructuring! ```js const Child = ({ location, isSigned }) => { console.log(location) console.log(isSigned) return ( <div className="child-component"> <h3>I am the child.</h3> </div> ); }; export default Child; ``` ![Props with destructuring](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/iptmsfta37oto0egq7z4.png) Now that we have access to that data in our `Child` component, we can display that data! ![Functioning permission slip signing](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/13626f3tp4rs4xy1bkar.gif) In the `Child` component, we now have a function called `renderPermission`, which renders text conditionally based on the value of `isSigned`. ```js const Child = ({ location, isSigned }) => { const renderPermission = () => { if (isSigned) { return `I can go on the field trip to the ${location}!` } else { return `I'm not allowed to go on the field trip to the ${location}.` }; }; return ( <div className="child-component"> <h3>I am the child.</h3> {renderPermission()} </div> ); }; export default Child; ``` Remember that we can't change props! A kid can't forge their parent/guardians signature! Let's try it out. ```js const forgePermission = () => { console.log('Clicked') isSigned = true; }; return ( <div className="child-component"> <h3>I am the child.</h3> <button onClick={forgePermission}>Forge Signature</button> <br /> {renderPermission()} </div> ); ``` We're including a `console.log` so that we can be sure that our event listener is working. ![A child can't change props](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/t07tw5bwkm73jegb0j4z.gif) We can't do it! They're not changing! Our `Child` component is not re-rendering. Our parent component is in charge of the data and changing it (with state!) and our child component only has the ability to display that data (they're props!). Here is a look at our finished code: ```js import { useState } from 'react'; import Child from './Child'; const Parent = () => { const [isSigned, setIsSigned] = useState(false); const location = "the science museum"; const handleClick = () => { isSigned ? setIsSigned(false) : setIsSigned(true); }; const renderButton = () => { return !isSigned ? <button onClick={handleClick}>Sign Permission Slip</button> : <button onClick={handleClick}>You're Grounded!</button> }; return ( <div className="container"> <div className="parent"> <h2>I am the parent.</h2> {renderButton()} </div> <div className="child"> <Child location={location} isSigned={isSigned} /> </div> </div> ); }; export default Parent; ``` ```js const Child = ({ location, isSigned }) => { const renderPermission = () => { if (isSigned) { return `I can go on the field trip to the ${location}!` } else { return `I'm not allowed to go on the field trip to the ${location}.` }; }; const forgePermission = () => { console.log('Clicked') isSigned = true; }; return ( <div className="child-component"> <h3>I am the child.</h3> <button onClick={forgePermission}>Forge Signature</button> <br /> {renderPermission()} </div> ); }; export default Child; ``` That's it! That's `state` and `props` in React. It's as simple as that. *Cover image from [Austin Pacheco](https://unsplash.com/photos/uZkgI3opcvE?utm_source=unsplash&utm_medium=referral&utm_content=creditShareLink) on [Unsplash](https://unsplash.com)*
arynnboniface
823,688
How to Insert the Row after Every 5th Row through Excel VBA?
In this tutorial, we will guide you on how to insert the row after every 5th row through Excel VBA....
0
2021-09-15T02:18:07
https://geekexcel.com/how-to-insert-the-row-after-every-5th-row-through-excel-vba/
toinserttherowaftere, vbamacros
--- title: How to Insert the Row after Every 5th Row through Excel VBA? published: true date: 2021-09-14 11:27:00 UTC tags: ToInsertTheRowAfterE,VBAMacros canonical_url: https://geekexcel.com/how-to-insert-the-row-after-every-5th-row-through-excel-vba/ --- In this tutorial, we will guide you on **how to insert the row after every 5th row through Excel VBA**. Let’s get them below!! Get an official version of MS Excel from the following link: **[https://www.microsoft.com/en-in/microsoft-365/excel](https://www.microsoft.com/en-in/microsoft-365/excel)** ## Example - Firstly, you need to **create a sample data** in range **A1:F31** , in which column A contains Name, column B contains Street address, column C City, column D contains region, column E contains country name, and column F contains phone number. ![](https://geekexcel.com/wp-content/uploads/2021/09/Sample-data-9-1024x442.png)<figcaption>Sample data</figcaption> - In the Excel Worksheet, you have to go to the **Developer Tab.** - Then, you need to ** ** select the **Visual Basic** option under the **Code** section. ![Select Visual Basic option](https://geekexcel.com/wp-content/uploads/2020/09/11-3.png)<figcaption>Select the Visual Basic option</figcaption> - Now, you need to **insert a module**. ![Insert a module](https://geekexcel.com/wp-content/uploads/2021/09/Insert-a-module.png)<figcaption>Insert a module</figcaption> - You have to **copy and paste** the following code. ``` Sub InsertIT() x = 2 'Start Row Do Range("A" & x, "F" & x).Insert x = x + 5 Loop While x < 50 End Sub ``` - After that, you need to **save the code** by selecting it and then **close the window**. ![](https://geekexcel.com/wp-content/uploads/2021/09/Save-the-Code-36.png)<figcaption>Save the Code</figcaption> - Again, you have to go to the **Excel Spreadsheet** , and click on the **Developer Tab**. - You need to choose the **Macros option** in the Code section. ![Choose Macro option](https://geekexcel.com/wp-content/uploads/2021/09/Choose-Macro-option-11-1024x184.png)<figcaption>Choose Macro option</figcaption> - Now, you have to make sure that your **macro name is selected** and click the **Run ** button. ![](https://geekexcel.com/wp-content/uploads/2021/09/Run-the-Code-17.png)<figcaption>Run the Code</figcaption> - Finally, **rows will get inserted** till the 50th row in the data. ![](https://geekexcel.com/wp-content/uploads/2021/09/Output-10-1024x445.png)<figcaption>Output</figcaption> ## A Short Summary Here, we have explained the step-by-step procedure on how to **insert the row after every 5th row through Excel VBA**. Make use of this. Please share your worthwhile **feedback** in the below **comment** section. To learn more, check out our website **[Geek Excel](https://geekexcel.com/)!!** **Read Also:** - **[Count the Number of Words in a Cell or a Range in Excel Office 365!!](https://geekexcel.com/count-the-number-of-words-in-a-cell-or-a-range-in-excel-office-365/)** - **[Excel Formulas Check the Cell Contains Some Words but Not Others!!](https://geekexcel.com/excel-formulas-check-the-cell-contains-some-words-but-not-others/)** - **[Excel Formulas to Count Total Words in a Cell ~ Easy Guide!!](https://geekexcel.com/excel-formulas-to-count-total-words-in-a-cell/)** - **[Formulas for Counting the Number of Words in a Cell or Range in Excel!!](https://geekexcel.com/formulas-for-counting-the-number-of-words-in-a-cell-or-range-in-excel/)** - **[Excel Formulas to Count Total Words in a Range ~ Useful Tips!!](https://geekexcel.com/excel-formulas-to-count-total-words-in-a-range/)**
excelgeek
823,771
XOR in Python
ItsMyCode | XOR Operator in Python is also known as “exclusive or” that compares two binary...
0
2021-09-14T22:09:14
https://itsmycode.com/xor-in-python/
python, programming, codenewbie, tutorial
--- title: XOR in Python published: true date: 2021-09-14 13:21:07 UTC tags: #python #programming #codenewbie #tutorial canonical_url: https://itsmycode.com/xor-in-python/ --- ItsMyCode | XOR Operator in Python is also known as **“exclusive or”** that compares two binary numbers bitwise if two bits are identical XOR outputs as 0 and when two bits are different then XOR outputs as 1. XOR can even be used on booleans. XOR is mainly used in situations where we don’t want two conditions to be true simultaneously. In this tutorial, we will look explore multiple ways to perform XOR (exclusive OR) operations in Python with examples. ## Bitwise Operator Bitwise operators in Python are also called binary operators, and it is mainly used to perform Bitwise calculations on integers, **the integers are first converted into binary** , and later the **operations are performed bit by bit.** ## Python XOR Operator Let’s take a look at using the XOR **`^` ** Operator between 2 integers. When we perform XOR between 2 integers, the operator returns the integer as output. ```python a= 5 #0101 b = 3 #0011 result = (a ^ b) #0110 print(result) # Output # 6 (0110) ``` Let’s take a look at using XOR on two booleans. In the case of boolean, the true is treated as 1, and the false is treated as 0. Thus the output returned will be either true or false. ```python print(True ^ True) print(True ^ False) print(False ^ True) print(False ^ False) ``` **Output** ```python False True True False ``` ## XOR using Operator Module We can even achieve XOR using the built-in **`operator `** module in Python. The operator module has a **`xor()`** function, which can perform an XOR operation on integers and booleans, as shown below. ```python import operator print(operator.xor(5,3)) print(operator.xor(True,True)) print(operator.xor(True,False)) print(operator.xor(False,True)) print(operator.xor(False,False)) ``` **Output** ```python 6 False True True False ``` The post [XOR in Python](https://itsmycode.com/xor-in-python/) appeared first on [ItsMyCode](https://itsmycode.com).
srinivasr
823,779
Calculadora de média
A post by Ingrid
0
2021-09-14T14:14:06
https://dev.to/indgri/calculadora-de-media-520f
codepen
{% codepen https://codepen.io/indgri-i/pen/yLXXZep %}
indgri
823,795
Conversor de Moedas
A post by Ingrid
0
2021-09-14T14:43:51
https://dev.to/indgri/conversor-de-moedas-1e1j
codepen
{% codepen https://codepen.io/indgri-i/pen/OJgjKBe %}
indgri
823,805
Talking about JavaScript function
What is Function in JavaScript? In JavaScript, functions are defined with the 'function'...
0
2021-09-14T15:13:54
https://dev.to/injamulcse15/talking-about-javascript-function-2n9o
javascript, function
### What is Function in JavaScript? In JavaScript, functions are defined with the *'function'* keyword. * There is an another way to define a function, called *'Arrow Function'*. ### Declaration a Function *Syntax* ``` function firstFunction () { // Code here ... } ``` *Example* ``` function firstFunction () { console.log('JavaScript function'); } firstFunction(); // JavaScript function ``` ### Function Expressions A function expression can be stored in a variable. *Syntax* ``` let firstFunction = function () { // Code here ... } ``` *Example* ``` let firstFunction = function () { return "JavaScript function"; } firstFunction(); // JavaScript function ``` ### Arrow Function Arrow function allows a short syntax for writing function expressions. * We don't need the *'function'* keyword, the *'return'* keyword and the *'curly'* brackets. *Syntax* ``` let change = (argument1, argument2) => Code here ... ; ``` *Example:* ``` let add = (x , y) => x + y; add(4, 6); // Output will 10 ``` ### Function Parameters If you want to build a *dynamic function* then you have to use *parameters*. * Parameters are like an *input*. Based on your *input it gives you the output*. *Syntax with example* ``` function add(x, y) { return (x + y); } add(10, 5); // Output: 15, // Here, x is 10, y is 5. ``` ### Default Parameters If a function is called with *missing arguments*, the missing values are set to *undefined*. * It is better to assign a *default value* to the *parameter*. *Syntax* ``` function myFunction (argument1 = default value) { // Code here ... } ``` *Example* ``` function sum (x = 1, y = 1) { return (x + y); } sum(4, 6); // here x is 4, y is 6 sum(4); // here x is 4 but y is 1 (default value) sum(); // here x is 1, y is 1 ```
injamulcse15
823,806
Process Analytics - August 2021 Newsletter
Welcome to the Process Analytics monthly newsletter. The goal of the Process Analytics project is to...
16,624
2021-09-15T11:45:00
https://medium.com/@process-analytics/process-analytics-august-2021-newsletter-b793a647e35d
news, typescript, rlang, analytics
Welcome to the Process Analytics monthly newsletter. The goal of the Process Analytics project is to rapidly display meaningful Process Analytics components in your web pages using BPMN 2.0 notation and Open Source libraries. Although August is usually a time of vacation and rest, the project team worked hard to propose many new elements in our project: * a new website * the new logo * the new R library (BPMN Visualization) * the BPMN Visualization (JavaScript/TypeScript) library ## The Process Analytics Project website ![website first screenshot](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/fr0axx2te272gzhleowr.png) We finalized the first version of the Process Analytics project [website](https://process-analytics.dev/) :tada: This site brings together all the information related to the project, especially what is necessary to make it easier for you to get started: - the project goals - the available libraries and tools, - the related articles and posts In August, we worked specifically on better describing the goals of the project. We also added screenshots to illustrate some use cases that the project may already cover. Last but not least, we've tweaked the site to look good on mobile devices. ![website second screenshot](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/sr5lj5nod741gcl33hi4.png) ## New project logo We have also refreshed our logo which is now available in two flavors: blue and white. ![Project logo](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/wkonfs8ynegx9eirf8xn.png) ## BPMN Visualization - R Package library The Process Analytics team has also started a useful new project/library for the [<u>R</u>](https://www.r-project.org/) ecosystem: [BPMN Visualization - R Package](https://github.com/process-analytics/bpmn-visualization-R). Using this library, you can visualize a process on a BPMN diagram, along with its execution data, in R projects (RStudio, Shiny applications, etc) in Process Analytics or Process Mining. *BPMN Visualization - R Package* is based on the [experimental implementation](https://github.com/csouchet/bpmn-visualization-R-poc) we made in June. You can use this new package in place of the experimental one that has been archived. For the next months, we will be working on the following topics: - Release the first public version and make it available on [CRAN](https://cran.r-project.org/). - Ability to customize the style of the BPMN Diagram. - Ability to customize the style of overlays and choose their position on the BPMN Diagram. ## BPMN Visualization JS/TS library In August, we released 2 versions: [0.18.0](https://github.com/process-analytics/bpmn-visualization-js/releases/tag/v0.18.0) & [0.19.0](https://github.com/process-analytics/bpmn-visualization-js/releases/tag/v0.19.0). We provide better examples and have improved the BPMN support and rendering as shown below. ### New BPMN support: Group ![BPMN Group](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/4ek8v8tod2zwz2hn74b9.png) ### New BPMN support: Call Activity calling Global Task The Call Activity icon is based on the one for Global Task. ![Call Activity icons](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/pbwhr1n34j0rc73x66gx.png) ### BPMN rendering improvement All activities have the same rounding whatever their size. | Before | Now | | :----------------------------------------------------------: | :----------------------------------------------------------: | | ![rounded activity in past versions](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/fz8vcmppwida4zqr7hhp.png) | ![rounded activity now](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/04y9xvaohruhz0avnffb.png) | ## Plans for the future Here are the topics we will be managing in the coming months: - Create new examples to demonstrate other Process analytics / Process Mining use cases. - Be ready to receive contributions for [Hacktoberfest 2021](https://hacktoberfest.digitalocean.com/) - Add more tests to be able to upgrade mxGraph (the technical library in charge of the final rendering) to the latest version. ## That’s All Folks! We hope you enjoyed the August project news and are looking forward to what September will bring. In the meantime, to stay on top of the latest news and releases, follow us through: - Website: https://process-analytics.dev - Twitter: [@ProcessAnalyti1](https://twitter.com/ProcessAnalyti1) - GitHub: https://github.com/process-analytics *Cover photo by [Robert Collins](https://unsplash.com/photos/1l4OZzMZ_IU) on [Unsplash](https://unsplash.com/)*
tbouffard
823,821
Les Conditions
Catégorie de la personne selon son âge.
0
2021-09-14T15:40:59
https://dev.to/abderrahim85/les-conditions-1ggl
Catégorie de la personne selon son âge.
abderrahim85
823,860
All about selectors in CSS
What are selectors? CSS, or Cascading Style Sheets, is a design language that simplifies...
0
2021-09-14T17:00:53
https://dev.to/anshulraheja/all-about-selectors-in-css-3iem
## What are selectors? CSS, or Cascading Style Sheets, is a design language that simplifies the process of making web pages presentable. Selectors are used to choose elements and apply styles to them. ## Types of selectors There are different categories of selectors. Each category has various types. I'll be talking about 3 categories - Basic, Combination, Attribute ### 1.BASIC SELECTORS There are majorly 4 Basic Selector which are mentioned below:- ```html <!-- refer this html to understand basic selector --> <div class="container"> <h1>CSS Selectors</h1> <h2>Lorem ipsum dolor sit amet consectetur adipisicing elit. Iure, maiores.</h2> <p id="mainPara">Lorem ipsum dolor sit amet consectetur adipisicing elit. Laborum, corporis.</p> </div> ``` #### -Universal selector It applies rules to all the elements in HTML except the pseudo-element - ::before and ::after. (*) is used as a universal selector ```css * { font-family: "Poppins", sans-serif; /* font is applied to all elements */ } ``` #### -Element selector It selects all the elements of that type ```css h1 { font-size: 3rem; text-align: center; /* this style applies to all h1 elements */ } ``` #### -Class selector This rule is only applied to elements with the corresponding class attribute, dot (.) is prefixed to the class name in CSS. ```css .container { background-color: rgb(255, 235, 201); padding: 1rem; margin: 1rem; /* this style is applied to element with class container */ } ``` #### -ID selector ID selectors are a more restrictive version of class selectors. They work in a similar fashion, except that each page can only have one element with the same ID, which means you can't reuse styles.(#) is prefixed to ID value in a CSS ID selector. ```css #main { color: rgb(117, 52, 34); /* this style is applied to element with ID main */ } ``` #### Output after all the above CSS ![Basic](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/6fhrjbev399a2m8cghvy.jpg) ### 2.COMBINATIONS SELECTORS ```html <!-- html to understand combination of selector --> <div class="list-container"> <span>This is the span element</span> <ul> <li>Child 1 of ul element</li> <li>Child 2 of ul element</li> </ul> <ol> <li>Direct Child of ol element</li> <span> <li>Indirect Child of ol Element</li> </span> </ol> <div>This is a div </div> <a href="/">Link 1</a> <span> <a href="/">Link 2</a> </span> <a href="/">Link 3</a> <section>This is the section element</section> <a href="/">Link 1</a> <a href="/">Link 2</a> <a href="/">Link 3</a> </div> ``` #### -AND selector Selects element that match the specified combination ```css div.list-container { background-color: rgb(255, 235, 201); /* apply style to div with class list-container */ } ``` #### -OR selector Either of the element/class, separated with comma(,) ```css span, h2 { background-color: rgb(117, 52, 34); /* apply style to all span and h2 elements */ } ``` #### -Descendant selector Selects all the child of the element syntax: parentElement (space) childElement {} ```css ul li { background-color: orange; /* select all childs of ul */ } ``` #### -Direct Child selector Selects only the direct child of the specified element syntax: parentElement > childElement {} ```css ol > li { background-color: yellow; /* select the direct child of ol */ } ``` #### -All Siblings selector Selects all the siblings (element at same level) after the first element is encountered. syntax: firstElement ~ ssecondElement{} ```css div ~ a { color: rgb(255, 0, 0); /* selects only link1, link3 */ } ``` #### -Next Sibling selector Only selects the very next/adjacent sibling to the first element syntax: firstElement + ssecondElement{} ```css section + a { color: black; /* selects only link1 under section elementalign-content*/ } ``` #### Output after all the above CSS ![Image2](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/6kj3v6bwe0z9lzr364yf.jpg) ### 3.ATTRIBUTE SELECTORS ```html <!-- html to understand attribute selector --> <div class="list-container"> <span type="text">This is the span element</span> <ul> <li flag="true">Child 1 of ul element</li> <li flag="T">Child 2 of ul element</li> </ul> <ol> <li data="happy">Direct Child of ol element</li> <span> <li data="hello">Indirect Child of ol Element</li> </span> </ol> <div data="world">This is a div </div> <a href="/" link="direct">Link 1</a> <a href="/" link="indirect">Link 2</a> <a href="/">Link 3</a> ``` #### -Has attribute Selects element with the specified attribute syntax: [attribute]{} ```css [type]{ background-color: red; } ``` #### -Exact attribute Selects element which has the exact same attribute and value. syntax: [attribute = "value"]{} ```css [flag="T"]{ background-color:yellow; } ``` #### -Begin attribute Selects element whose attribute's value begins with specified text syntax: [attribute^ = "value"]{} ```css [data^="h"]{ background-color:pink; } ``` #### -End attribute Selects element whose attribute's value ends with specified text syntax: [attribute$ = "value"]{} ```css [data$='d']{ background-color: grey; } ``` #### -Substring attribute Selects element who specified text anywhere in the attribute value syntax: [attribute* = "value"]{} ```css [link*="dir"]{ background-color: blue; color:white; } ``` ##### Output after all the above CSS ![attribute](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/142xv7vvxhyvqlt28zp7.jpg) ## BONUS ### Some random examples to have more clarity ```css .container * { /* selects everything inside container class*/ } .c1 .c2 + .c3 { /* Lets break it into 2 steps 1. .c1 .c2 - selects all c2 class elements in c1 class element 2. point 1 + .c3 - selects all c3 class elements that are next sibling of (.c1 .c2) */ } ```
anshulraheja
841,006
The .NET Stacks #63: 🗞 .NET 6 is for real now
Happy Monday! This week, we're talking about .NET 6 RC1 and some other topics. Oh, and if you're...
0
2021-09-26T14:27:59
https://www.daveabrock.com/2021/09/26/dotnet-stacks-63/
csharp, dotnet, azure
--- title: The .NET Stacks #63: 🗞 .NET 6 is for real now published: true date: 2021-09-26 06:00:00 UTC tags: csharp, dotnet, azure canonical_url: https://www.daveabrock.com/2021/09/26/dotnet-stacks-63/ --- ![Alt Text](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/6dnn4qyfnjlp928lmflk.png) Happy Monday! This week, we're talking about .NET 6 RC1 and some other topics. Oh, and if you're using Travis CI, [maybe you shouldn't](https://arstechnica.com/information-technology/2021/09/travis-ci-flaw-exposed-secrets-for-thousands-of-open-source-projects/). * * * ## 🔥 My favorites from last week [Announcing .NET 6 Release Candidate 1](https://devblogs.microsoft.com/dotnet/announcing-net-6-release-candidate-1/) Richard Lander [ASP.NET Core updates in .NET 6 Release Candidate 1](https://devblogs.microsoft.com/aspnet/asp-net-core-updates-in-net-6-rc-1/) Daniel Roth [Migration to ASP.NET Core in .NET 6](https://gist.github.com/davidfowl/0e0372c3c1d895c3ce195ba983b1e03d) David Fowler [Update on .NET Multi-platform App UI (.NET MAUI)](https://devblogs.microsoft.com/dotnet/update-on-dotnet-maui/) Scott Hunter [Visual Studio 2022 Preview 4 is now available!](https://devblogs.microsoft.com/visualstudio/visual-studio-2022-preview-4-is-now-available/) Mads Kristensen As expected, .NET 6 Release Candidate (RC) 1 rolled out last week. It's the first of two RC releases deemed "go-live" ready and supported in production. .NET 6 has been feature-complete for a while now, and [as Richard Lander states](https://devblogs.microsoft.com/dotnet/announcing-net-6-release-candidate-1/), for this release the "team has been focused exclusively on quality improvements that resolve functional or performance issues in new features or regressions in existing ones." Still, the blog post is worth a read to understand .NET 6's foundational features. As for [the ASP.NET Core side of things](https://devblogs.microsoft.com/aspnet/asp-net-core-updates-in-net-6-rc-1/), we're seeing quite a bit. The team is rolling out the ability to [render Blazor components from JS](https://devblogs.microsoft.com/aspnet/asp-net-core-updates-in-net-6-rc-1/#render-blazor-components-from-javascript), [Blazor custom elements](https://devblogs.microsoft.com/aspnet/asp-net-core-updates-in-net-6-rc-1/#render-blazor-components-from-javascript) (on an experimental basis), the ability to [generate Angular and React components with Blazor](https://devblogs.microsoft.com/aspnet/asp-net-core-updates-in-net-6-rc-1/#generate-angular-and-react-components-using-blazor), [.NET to JavaScript streaming](https://devblogs.microsoft.com/aspnet/asp-net-core-updates-in-net-6-rc-1/#generate-angular-and-react-components-using-blazor), and [template improvements](https://devblogs.microsoft.com/aspnet/asp-net-core-updates-in-net-6-rc-1/#template-improvements)—including the ability to opt-in to implicit usings—and much more. Of course, it wouldn't be an ASP.NET Core release without talking about Minimal APIs. RC1 [brings a lot of updates](https://devblogs.microsoft.com/aspnet/asp-net-core-updates-in-net-6-rc-1/#minimal-api-updates): better support for OpenAPI for defining metadata, parameter binding improvements (like allowing optional parameters in endpoint actions), and the ability to use multiple calls to `UseRouting` to support more middleware. David Fowler also [dropped a nice guide](https://gist.github.com/davidfowl/0e0372c3c1d895c3ce195ba983b1e03d) for migrating ASP.NET Core to .NET 6. You'll want to check it out to understand how the new hosting model works. Have a sad trombone ready? .NET MAUI will not be making it into .NET 6's official release in November, [according to a Microsoft Scott](https://devblogs.microsoft.com/dotnet/update-on-dotnet-maui/). It's now looking like it'll be released in early Q2 of 2022. There was a lot to be done, and a slight delay beats a buggy release any day. You can also check out Scott's post for an overview on features rolled out with .NET MAUI Preview 8. Going hand-in-hand with the .NET 6 releases, [Visual Studio 2022 Preview 4 is now available](https://devblogs.microsoft.com/visualstudio/visual-studio-2022-preview-4-is-now-available/). This release promises personal/team productivity improvements (like finding files) and thankfully a big update for the Blazor and Razor editors. You can now use VS 2022 to hot reload on file save in ASP.NET Core and also apply changes to CSS live. [Check out the blog post](https://devblogs.microsoft.com/visualstudio/visual-studio-2022-preview-4-is-now-available/) for details. ## 📢 Announcements [HTTP/3 support in .NET 6](https://devblogs.microsoft.com/dotnet/http-3-support-in-dotnet-6/) Sam Spencer Along with all the other announcements last week, [Sam Spencer writes about HTTP/3 support in .NET 6](https://devblogs.microsoft.com/dotnet/http-3-support-in-dotnet-6/). As a refresher, Sam explains why HTTP/3 is important: "We have all gone mobile and much of the access is now from phones and tablets using Wi-Fi and cellular connections which can be unreliable. Although HTTP/2 enables multiple streams, they all go over a connection which is TLS encrypted, so if a TCP packet is lost all of the streams are blocked until the data can be recovered. This is known as the head of line blocking problem." "HTTP/3 solves these problems by using a new underlying connection protocol called QUIC. QUIC uses UDP and has TLS built in, so it’s faster to establish connections as the TLS handshake occurs as part of the connection. Each frame of data is independently encrypted so it no longer has the head of line blocking in the case of packet loss." The RFC for HTTP/3 is not yet finalized and subject to change, but you can start to play around with HTTP/3 and .NET 6 [if you're up for getting your hands dirty](https://devblogs.microsoft.com/dotnet/http-3-support-in-dotnet-6/#http-3-support-in-net-6). You can use the `HttpClient` as well [if you enable a runtime flag](https://devblogs.microsoft.com/dotnet/http-3-support-in-dotnet-6/#http-3-support-in-net-6). [Check out the post](https://devblogs.microsoft.com/dotnet/http-3-support-in-dotnet-6) for details. More from last week: - Some releases: WinUI 2.7 [is out](https://docs.microsoft.com/en-us/windows/apps/winui/winui2/release-notes/winui-2.7), Dapr v1.4 [is now out](https://blog.dapr.io/posts/2021/09/16/dapr-v1.4-is-now-available/), and so is [Uno Platform 3.10](https://platform.uno/blog/uno-platform-3-10-day-0-support-for-net-6-rc1-winui-infobadge-windows-11-fluent-styles/). Also, [CoreWCF has a new release](https://corewcf.github.io/blog/2021/09/13/corewcf-0_3_0_release). - Leslie Richardson [writes about the future of Visual Studio extensibility](https://devblogs.microsoft.com/visualstudio/the-future-of-visual-studio-extensibility-is-here). - Vasu Jakkal [writes about passwordless personal Microsoft accounts](https://www.microsoft.com/security/blog/2021/09/15/the-passwordless-future-is-here-for-your-microsoft-account/). - The NuGet folks [introduce package source mapping](https://devblogs.microsoft.com/nuget/introducing-package-source-mapping/). ## 📅 Community and events [Announcing the Candidates .NET Foundation Election 2021](https://dotnetfoundation.org/blog/2021/09/01/announcing-net-foundation-elections-2021) Nicole Miller This post isn't new but if you're a member of the .NET Foundation, they are [looking to fill a couple of seats on the Board of Directors](https://dotnetfoundation.org/blog/2021/09/01/announcing-net-foundation-elections-2021). Browse the blog post to learn more about the candidates (Nicole has interviewed each candidate, as well). Voting ends by the end of today (September 20) at 11:59 PST in the USA. (Disclaimer: I was [on the Election Board](https://dotnetfoundation.org/about/election/) and would love to hear feedback about the process if you have it. We aren't perfect but are trying!) More from last week: - The Netflix Tech Blog [continues their practical API design series](https://netflixtechblog.com/practical-api-design-at-netflix-part-2-protobuf-fieldmask-for-mutation-operations-2e75e1d230e4), and also [writes about securing at scale](https://netflixtechblog.com/the-show-must-go-on-securing-netflix-studios-at-scale-19b801c86479). - For community standups: ASP.NET [talks about Blazor .NET 6 RC1 updates](https://www.youtube.com/watch?v=cpt0Ljs35YA), Machine Learning [walks through TorchSharp](https://www.youtube.com/watch?v=s3Epe3ox72s), and .NET Tooling [discusses updates for Visual Studio for Mac](https://www.youtube.com/watch?v=4kwvcufEAk4). - The .NET Docs Show [hosts a .NET IoT AMA](https://www.youtube.com/watch?v=kuJc6HsRbJk). ## 🌎 Web development [WebSocket per-message compression in ASP.NET Core 6](https://www.tpeczek.com/2021/09/websocket-per-message-compression-in.html) Tomasz Pęczek New with ASP.NET Core 6, you can compress WebSocket messages. Tomasz Pęczek has been working with it so far [and has a nice post](https://www.tpeczek.com/2021/09/websocket-per-message-compression-in.html) with a GitHub repository you can reference. It ships with a `WebSocketAcceptContext` object, which includes a `DangerousEnableCompression` property. Why? "You might be wondering why such a "scary" property name. It's not because things may fail. If the client doesn't support compressions (or doesn't support compression with specific parameters), the negotiated connection will have compression disabled. It's about security. Similarly to HTTPS, encrypted WebSocket connections are subject to _CRIME/BREACH_ attacks. If you are using encryption, you should be very cautious and not compress sensitive messages." Also from last week: - Scott Hanselman [writes more about Minimal APIs in .NET 6](https://www.hanselman.com/blog/minimal-apis-at-a-glance-in-net-6). - Visual Studio Magazine [confirms that PHP runs the world](https://visualstudiomagazine.com/articles/2021/09/14/backend-web.aspx). - Thomas Ardal [writes about async processing of long-running tasks in ASP.NET Core](https://blog.elmah.io/async-processing-of-long-running-tasks-in-asp-net-core/). - Khalid Abuhakmeh [uses .NET to validate JSON with JSON Schema](https://khalidabuhakmeh.com/using-dotnet-to-validate-json-with-json-schema). - David Grace [works on .NET 6 Blazor updates in Visual Studio 2022](https://www.roundthecode.com/dotnet/blazor/blazor-updates-dotnet-6-visual-studio-2022). - Matthew MacDonald asks: [is Blazor the future or just another walled garden?](https://medium.com/young-coder/is-blazor-the-future-or-just-another-walled-garden-441842cc249d) ## 🔧 Tools [Advanced Git Workflow Tips](https://blog.jetbrains.com/dotnet/2021/09/13/advanced-git-workflow-tips/) Khalid Abuhakmeh Over at the JetBrains blog, Khalid Abuhakmeh writes about ways to make working with Git easier, armed with some JetBrains Rider tips as well. I learned about cleaning your repository of non-tracked artifacts by using `git clean -xdf`. An irreversible command, you can use it to prevent folder bloat that occurs in new repos when you're working with non-tracked files like dependencies and build items. - Chinedu Imoh [introduces GitHub Codespaces](https://www.telerik.com/blogs/introduction-github-codespaces). - Khalid Abuhakmeh [offers advanced Git workflow tips](https://blog.jetbrains.com/dotnet/2021/09/13/advanced-git-workflow-tips/). - Ryan Staatz [writes about 5 things developers need to know about Kubernetes management](https://thenewstack.io/5-things-developers-need-to-know-about-kubernetes-management/). - Davide Bellone [customizes fields generation in Visual Studio 2019](https://www.code4it.dev/blog/auto-creating-fields-vs). - Patrick Smacchia [debugs a .NET App on Linux from Windows Visual Studio with WSL](https://blog.ndepend.com/debugging-a-net-app-on-linux-from-windows-visual-studio-with-wsl/). ## 🏗 Design, testing, and best practices - Anwar Al Jahwari [works on the Strategy pattern](https://better-dev.io/strategy-pattern/). - Steve Fenton [offers a perspective on the laws of software development](https://www.stevefenton.co.uk/2021/09/a-perspective-on-laws-of-software-development/). - Steve Smith asks: [should controllers reference repositories or services?](https://ardalis.com/should-controllers-reference-repositories-services/) - Mahesh Chand [offers some productivity tips](https://www.c-sharpcorner.com/article/top-10-tips-to-increase-productivity/). ## ⛅ The cloud - Brian Weeteling [writes about semantic search with Azure Cognitive Search](https://www.getadigital.com/blog/semantic-search-with-azure-cognitive-search). - The CNCF asks: [is serverless the right way to the cloud](https://www.cncf.io/blog/2021/09/15/is-serverless-the-right-way-to-cloud/)? - Justin Yoo [works on MS Graph, Blazor WebAssembly, and Azure Static Web Apps](https://dev.to/azure/ms-graph-blazor-webassembly-and-azure-static-web-apps-3p1d). ## 🥅 The .NET platform - Andrew Lock [looks inside the ConfigurationManager in .NET 6](https://andrewlock.net/exploring-dotnet-6-part-1-looking-inside-configurationmanager-in-dotnet-6/). - The Code Maze blog [introduces System.Text.Json](https://code-maze.com/introduction-system-text-json-examples/). ## 📔 Languages - Something I missed a while back: Sam Walpole [introduces F# for OO developers](https://samwalpole.com/a-brief-introduction-to-f-for-object-oriented-developers). - Maarten Hus writes about [pipeline operator possibilities in F#](https://www.maartenhus.nl/blog/pipeline-operator-hack-vs-fsharp/). ## 📱 Xamarin - Luis Matos [works on password validation rules with Xamarin Forms](https://luismts.com/password-validation-rules-xamarin-forms/). - Almir Vuk [writes about the .NET MAUI compatibility packages for the Xamarin Community Toolkit](https://www.infoq.com/news/2021/09/community-toolkit-maui-compat/). ## 🎤 Podcasts and Videos - Coding Blocks [discusses Docker licensing, career, and coding questions](https://www.codingblocks.net/podcast/docker-licensing-career-coding/). - .NET Rocks [talks about going from software developer to software engineer](https://www.dotnetrocks.com/default.aspx?ShowNum=1757), and The Overflow [talks about the roadmap from engineer to manager](https://stackoverflow.blog/2021/09/17/podcast-376-writing-the-roadmap-from-engineer-to-manager/). - Merge Conflict [discusses how not to monetize an app](https://www.mergeconflict.fm/271). - Adventures in .NET ask: [how do you grow?](https://devchat.tv/adventures-in-dotnet/how-do-you-grow-net-086/) - The .NET MAUI Podcast [provides an update](https://www.dotnetmauipodcast.com/98). - The Working Code Podcast asks: [are database transactions overrated?](https://www.bennadel.com/blog/4114-working-code-podcast-episode-040-are-database-transactions-overrated.htm) - The 6-Figure Developer Podcast [talks to Jesse Liberty about Git](https://6figuredev.com/podcast/episode-211-git-for-programmers-with-jesse-liberty/). - The Unhandled Exception Podcast [talks about Git with Jesse Liberty and James World](https://unhandledexceptionpodcast.com/posts/0023-git/). - The Changelog [discusses GitHub Codespaces](https://changelog.com/podcast/459). - The Azure DevOps Podcast [talks to Daniel Roth about web dev on .NET 6](http://azuredevopspodcast.clear-measure.com/daniel-roth-on-web-development-with-net-6-episode-158). - The ASP.NET Monsters [walk through DateOnly and TimeOnly in .NET 6](https://www.youtube.com/watch?v=9c_qdEA_I6k). - The On .NET Show [discusses accepting online payments with Stripe](https://channel9.msdn.com/Shows/On-NET/Accepting-online-payments-with-Stripe) and [performance and load testing with k6](https://www.youtube.com/watch?v=PYHZLCTC7i0).
daveabrock
823,866
How to change or add text to the browser tab using JavaScript?
Originally posted here! To change or add a text to the browser tab, we can set the value of the...
0
2021-08-28T00:00:00
https://melvingeorge.me/blog/change-add-text-title-of-browser-tab-using-javascript
javascript
--- title: How to change or add text to the browser tab using JavaScript? published: true tags: JavaScript date: Sat Aug 28 2021 05:30:00 GMT+0530 (India Standard Time) canonical_url: https://melvingeorge.me/blog/change-add-text-title-of-browser-tab-using-javascript cover_image: https://melvingeorge.me/_next/static/images/main-f96ae3dfee04b45cf724555f239a3679.jpg --- [Originally posted here!](https://melvingeorge.me/blog/change-add-text-title-of-browser-tab-using-javascript) To change or add a text to the browser tab, we can set the value of the `title` property of the global `document` object to the text we need to show in the browser tab using JavaScript. For example, consider we want to show a text called `Home` in the browser tab when the user visits the home page of your website. So for that, we can use the `document.title` property and set its value to the string `Home`. It can be done like this, ```js // Change or add text to the browser tab // using the document.title property document.title = "Home"; ``` Now the browser tab text will be changed to the text `Home`. See the above code live in [JSBin](https://jsbin.com/ninokifeye/3/edit?js,output). That's all 😃! ### Feel free to share if you found this useful 😃. ---
melvin2016
824,084
Create Redis in Azure and Integrate in API and check performance | E2E Demo | Beginner Series
A post by SoftWizCircle
0
2021-09-14T21:54:18
https://dev.to/softwizcircle/create-redis-in-azure-and-integrate-in-api-and-check-performance-e2e-demo-beginner-series-46le
azure, cloud, performance, redis
{% youtube npBGXYuf1JA %}
softwizcircle
824,391
Next.js 10
Talking with Guillermo Rauch about Next.js 10 and Vercel. Including plans for 2021.
25,851
2021-09-15T02:37:33
https://codingcat.dev/podcast/1-4-next-js-10-with-guillermo-rauch
webdev, javascript, beginners, podcast
Original: https://codingcat.dev/podcast/1-4-next-js-10-with-guillermo-rauch {% youtube https://www.youtube.com/watch?v=Xr4wqU5FyMI %} ## Since we last talked a year ago 1. Zeit became Vercel and gained $21M in funding. 2. Vercel’s $40M Series B happened in December. 3. Next.js 9 added (to name a few) 4. Preview Mode 5. Environment Variables 6. Fast Refresh * Static Regeneration 1. Next.js Analytics / Commerce 2. Next.js 10 released 3. next/image 4. @next/mdx ## Vercel * We are now using Vercel and Next.js in our next version of codingcat.dev. It has taken me a little bit of getting used to the CI/CD flow coming from Amplify and Google Cloud Build for Firebase hosting. Can you tell me more about Deploy Preview? * https://rauchg.com/2020/vercel#preview ## NextJS 1. I have seen a lot of movement to NextJS in the Jamstack community in the last year. What do you think is driving this move from Gatsby to Next? – Brittney 2. What is in store for NextJS in 2021? – Brittney 3. In browser navigation not working in Firefox and editing in dev tools requires the server to be restarted. 4. Images must be in the public folder. ## CodingCat.dev on Next.js Currently we are running on Firebase as a backend with two separate Next.js sites 1. Admin – Next.js, React, MaterialUI, backed by Firebase 2. Main – Next.js, React, Tailwindcss, backed by Firebase How can we statically build only our important pages, and then rely on regeneration for the rest? Is it as simple as saying build latest 50 pages and let page props do the rest? Lighthouse vs. Vercel Analytics how to get 100? I have read what I will call “way” too much about the Next.js chunks and that Lighthouse complaining about them is basically a non-issue, but is this true? So in looking at the P99 on Vercel we actually get 100, so what gives, what is this actually showing? ## Guillermo Rauch “Impossible just takes longer”
codercatdev
824,395
SocialBee with Ove and Vlad
A discussion with SocialBee founders Ovi Negrean and Vlad Hosu. We talk about the SAAS product SocialBee and how it is used for people to save time posting to socials. The architecture and technology used to create the platform.
25,851
2021-09-15T02:51:27
https://codingcat.dev/podcast/1-7-socialbee-with-ovi-negrean-and-vlad-hosu
webdev, javascript, beginners, podcast
Original: https://codingcat.dev/podcast/1-7-socialbee-with-ovi-negrean-and-vlad-hosu {% youtube https://www.youtube.com/watch?v=XR3U3CoUCDo %} ## About **SocialBee: The All-in-One Social Media Management Tool** [SocialBee](https://socialbee.com) is an all-in-one social media management tool that helps you create, schedule, publish, and analyze your social media content from one place. With SocialBee, you can: * Create and schedule posts for all of your social media accounts in one place. * Use AI to generate engaging content that is tailored to your audience. * Track your social media performance and see what's working and what's not. * Collaborate with team members or virtual assistants to manage your social media accounts. SocialBee is a powerful tool that can help you save time and grow your social media presence. Whether you're a small business owner, a freelancer, or a social media manager, SocialBee can help you take your social media marketing to the next level. **Here are some of the key features of SocialBee:** * **Create and schedule posts:** SocialBee makes it easy to create and schedule posts for all of your social media accounts. You can use the built-in editor to create posts, or you can import content from other sources like Canva or Google Drive. * **Use AI to generate content:** SocialBee's AI-powered content generator can help you create engaging content that is tailored to your audience. Simply enter a keyword or phrase, and SocialBee will generate a list of potential posts for you. * **Track your social media performance:** SocialBee's analytics tools give you insights into how your social media accounts are performing. You can see how many people are seeing your posts, how many people are clicking on your links, and how many people are engaging with your content. * **Collaborate with team members:** SocialBee makes it easy to collaborate with team members or virtual assistants to manage your social media accounts. You can assign tasks, leave comments, and approve posts before they go live. **SocialBee is a powerful tool that can help you save time and grow your social media presence. If you're looking for a social media management tool that can help you take your social media marketing to the next level, then SocialBee is a great option.** **Here are some of the benefits of using SocialBee:** * Save time: SocialBee can help you save time by automating many of the tasks involved in social media management, such as creating and scheduling posts, tracking performance, and collaborating with team members. * Grow your audience: SocialBee can help you grow your audience by providing you with the tools to create engaging content, track your performance, and target your audience. * Improve your results: SocialBee can help you improve your social media results by providing you with insights into how your content is performing and how you can improve your strategy. **If you're looking for a social media management tool that can help you save time, grow your audience, and improve your results, then SocialBee is a great option.** thumb_upthumb_down upload Google it more_vert
codercatdev
825,544
Laravel Livewire: Multiple Images Upload with Preview
Laravel Livewire Multiple Image Upload - In this article, I will share the steps or ways to create a...
0
2021-09-16T00:42:11
https://codelapan.com/post/laravel-livewire-multiple-images-upload-with-preview
laravel, livewire, webdev
**Laravel Livewire Multiple Image Upload** - In this article, I will share the steps or ways to create a multiple image upload feature with images preview using [laravel 8](https://codelapan.com/tag/laravel) and livewire. The multiple image upload feature is usually used or needed to add images or photos of more than one file for data such as products, properties, or others. Okay, let's get straight to the steps 👇 👨‍💻 ##Step 1: Install Laravel ``` //via Laravel Installer composer global require laravel/installer laravel new livewire-multiple-image-upload //via Composer composer create-project laravel/laravel livewire-multiple-image-upload ``` In this first step, we need to install the latest version of laravel (currently version 8) which we will try to implement to create a multiple image upload feature. For laravel installation, you can use the laravel installer or use composer like the example above. Please choose one method you want to use for laravel installation. From the two examples of laravel installation commands above, they will both generate or generate a laravel project with the name livewire-multiple-image-upload. Wait until the installation process is complete and when it's finished, don't forget to enter the project directory using the command **cd livewire-multiple-image-upload**. ##Step 2: Setup Database ``` DB_CONNECTION=mysql DB_HOST=127.0.0.1 DB_PORT=3306 DB_DATABASE=livewire_multiple_image_upload DB_USERNAME=root DB_PASSWORD= ``` Next, create a new database to experiment with making multiple image upload features with laravel 8 and livewire. If you use xampp as local server, please create a new database at localhost/phpmyadmin. Here I give an example, I created a new database with the name livewire_multiple_image_upload. Then don't forget to also adjust the DB_DATABASE in the .env file as in the example above. ##Step 3: Create Model & Migration File ``` php artisan make:model Image -m ``` Okay, then in the third step we need to create model and migration files for Image. Please run the command as above to generate Image model and migration files. ```php public function up() { Schema::create('images', function (Blueprint $table) { $table->id(); $table->string('image'); $table->timestamps(); }); } ``` Next, open the file database/migrations/xxxx_xx_xx_xxxxxx_create_images_table.php. We add an image field in the images table like the code above. If so, save and run the php artisan migrate command to migrate all migration files. ``` protected $guarded = []; ``` Don't forget, in the Models/Image.php file, we need to add `protected $guarded = [];` like the code above. ##Step 4: Install Livewire ``` composer require livewire/livewire ``` After installing laravel and creating a database, we continue by installing livewire in our laravel project. Run the command as above to [install livewire](https://codelapan.com/tag/livewire). ##Step 5: Create Livewire Components ``` php artisan make:livewire MultipleImageUpload ``` Okay, next we need to create a livewire component to create a view and logic for uploading multiple images. Please run the artisan command as above. From this command, it will generate two files located in the directory as below. ``` CLASS: app/Http/Livewire/MultipleImageUpload.php VIEW: resources/views/livewire/multiple-image-upload.blade.php ``` ###Step 5.1: MultipleImageUpload.php ```php <?php namespace App\Http\Livewire; use Livewire\Component; use Livewire\WithFileUploads; use App\Models\Image; class MultipleImageUpload extends Component { use WithFileUploads; public $images = []; public function save() { $this->validate([ 'images.*' => 'image|max:1024', // 1MB Max ]); foreach ($this->images as $key => $image) { $this->images[$key] = $image->store('images'); } $this->images = json_encode($this->images); Image::create(['image' => $this->images]); session()->flash('success', 'Images has been successfully Uploaded.'); return redirect()->back(); } public function render() { return view('livewire.multiple-image-upload'); } } ``` We have created the livewire components, then we need to update the code in those components to our needs. For that, please open the file in app/Http/Livewire/MultipleImageUpload.php and change the existing code to be like the code above. To add the file upload feature in the livewire component, we need to add the use Livewire\WithFileUploads; trait. In the code above, we add the $images method with an array data to retrieve or read input from wire:model="images" in the view file (livewire components). In addition, we also use a foreach loop to save all uploaded files to the images folder (in the storage/app directory) and save them as JSON format (using json_encode()) in the image field in the images table. ###Step 5.2: multipe-image-upload.blade.php ```php <div class="card"> <div class="card-body"> <form wire:submit.prevent="save"> @if (session()->has('success')) <div class="alert alert-success"> {{ session('success') }} </div> @endif @if ($images) Photo Preview: <div class="row"> @foreach ($images as $images) <div class="col-3 card me-1 mb-1"> <img src="{{ $images->temporaryUrl() }}"> </div> @endforeach </div> @endif <div class="mb-3"> <label class="form-label">Image Upload</label> <input type="file" class="form-control" wire:model="images" multiple> <div wire:loading wire:target="images">Uploading...</div> @error('images.*') <span class="error">{{ $message }}</span> @enderror </div> <button type="submit" class="btn btn-primary">Save Image</button> <div wire:loading wire:target="save">process...</div> </form> </div> </div> ``` Livewire handles multiple file uploads automatically by detecting the multiple attribute in the <input> tag. In this livewire component multiple-image-upload.blade.php file, we add a form with an action to the save method in the MultipleImageUpload.php file. Then we add a success session that displays a success message when we successfully upload multiple images. In the form, we add only one input field, which is to upload multiple images with an additional loading display when uploading multiple images. In addition, we also add code to display or preview the image for the selected image file and before submitting it, use ->temporaryUrl(). So, overall, the code in the multiple-image-upload.blade.php file will be like the code above. ##Step 6: Create Master View ```php <!doctype html> <html lang="en"> <head> <!-- Required meta tags --> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1"> <!-- Bootstrap CSS --> <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.1.1/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-F3w7mX95PdgyTmZZMECAngseQB83DfGTowi0iMjiWaeVhAn4FJkqJByhZMI3AhiU" crossorigin="anonymous"> <title>Livewire - Multiple Image Upload</title> @livewireStyles </head> <body> <div class="container mt-5"> <div class="row"> <h1 class="text-center my-2">Livewire - Multiple Image Upload</h1> @livewire('multiple-image-upload') </div> </div> <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.1.1/dist/js/bootstrap.bundle.min.js" integrity="sha384-/bQdsTh/da6pkI1MST/rWKFNjaCP5gBSY4sEBT38Q/9RBh9AH40zEOg7Hlq2THRZ" crossorigin="anonymous"></script> @livewireScripts </body> </html> ``` Then we create a master view file with additional scripts @livewireStyles, @livewireScripts and don't forget @livewire('multiple-image-upload'). So, please create a new view file with the file name master.blade.php, and add the code as above. ##Step 7: Define Route ```php Route::view('multiple-image-upload','master'); ``` In the last step, we need to register a new route in the routes/web.php file. For example, here we register Route::view('multiple-image-upload','master');. ##Step 7: Testing ![Livewire: Multiple image upload with preview](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/ht96162tdceyjwsdcuou.PNG) We have come to the end of the tutorial article on [how to create a multiple image upload feature with preview using laravel and livewire](https://codelapan.com/post/laravel-livewire-multiple-images-upload-with-preview). To test it, please run the server using the php artisan serve command, then open the project in a browser with a URL like 127.0.0.1:8000/multiple-image-upload. Next, click the input field and select some image files and click save image, then the image files will be stored in the storage/app/images folder and add new data in the images table. That's it for this tutorial article, until here we have both learned how to make the multiple image upload feature with laravel 8 and livewire. Good luck, hopefully this post can be useful and see you in the next article.👋 Get more articles about web development at [Codelapan.com](https://codelapan.com)
hilmi
824,628
Find Out What It Means to be a Data Scientist at Microsoft
Types of data positions, their salaries, roles and required experience, and interview...
0
2021-09-15T07:11:11
https://www.stratascratch.com/blog/microsoft-data-scientist-position-guide/
datascience, database, dataanalytics, sql
*Types of data positions, their salaries, roles and required experience, and interview process.* Microsoft Corporation was founded in 1975 by Bill Gates and Paul Allen. It is a multinational technology company mainly in the computer software business, as well as personal computers, consumer electronics products, and related products and services. According to the Forbes Global 2000 list for 2019, Microsoft is the largest company in the software and programming industry. It’s one of the biggest US IT [companies to work in as a data scientist](https://www.stratascratch.com/blog/ultimate-guide-to-the-top-5-data-science-companies/?utm_source=blog&utm_medium=click&utm_campaign=dev.to), along with Facebook, Amazon, Apple, and Google. Microsoft’s most famous products are Microsoft Windows, Microsoft Office, Skype, LinkedIn, Internet Explorer, and Edge web browser. As someone working in the data field, you’re probably familiar with the Microsoft SQL Server, SQL Server Reporting Services (SSRS), Power BI, and Azure SQL Database too. Microsoft’s current OS, Windows 10, is running on more than 1.3 billion devices globally. Overall, Windows’s share of the operating system market is around 70%. However, their main revenue generator is the Intelligent Cloud segment, consisting of Azure, SQL Server, Windows Server, and Visual Studio products. Speaking of revenue, Microsoft Corporation boasts $168 billion annual revenue as of the 2021 fiscal year ended June 30. This is an increase of 18% compared to the previous year. It currently employs around 163,000 people. Considering that the company’s revenue comes mainly from the Intelligent Cloud segment, which is based on the (cloud) handling of data, maybe it’s unnecessary to stress how important data is to Microsoft. A wide variety of other products, ranging from the most dominant operating system (Windows) to client & server software (Office), social media (LinkedIn), and software development Internet hosting (GitHub), shows its importance to Microsoft. Data is not used only for getting products to customers. It’s also used to change or develop products according to the end user’s behavior. And this behavior is again – data. Creating data-handling tools without knowing how data works is not possible. At the time of this writing, there were 9,392 job openings at Microsoft in total. Around a third of the total jobs is in the data field. You can find more information about the openings at Microsoft on their [Careers page](https://careers.microsoft.com/us/en/search-results?from=20&s=1). #Microsoft Data Scientist Salaries Here’s a quick overview of the general types of data positions at Microsoft, the experience they require, with their respective salaries compared to the national average. ![Microsoft Data Scientist Salaries](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/13yohmb8m3vijcvoreoh.png) The table shows that Microsoft’s average salaries for these positions are above the US national’s salary upper limit. Along with cash and stock bonus, Microsoft gives many other benefits to their employees. For example, health, dental, disability, and life insurance, 401k, student loan repayment plan, 15 days PTO (increased to 20 days in years 7-12, and 25 days beyond that), maternity & paternity leave, 10 days sick time, family sickness leave, etc. One benefit unique to Microsoft is Childcare/Babysitting Reimbursement, which reimburses 160 hours of childcare fees per year. In total, the estimated value of all those benefits is 12k. Below are the examples of the qualifications required for the three types of data positions mentioned in the table: ![Data Analyst Position at Microsoft](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/blek0a1u3mthqswghdwa.png) ![Data Scientist Position at Microsoft](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/jd04wb7x5vsy5iloyh30.png) ![Data Engineer Position at Microsoft](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/p237zuqdstxgaqec2f03.png) Microsoft is a huge company, so a job description and requirements could differ according to the department. For example, some positions can require better financial, legal, or product knowledge. Or maybe knowing some other programming languages, besides the standard of SQL/R/Python and being versed in cloud technology. Also, the seniority of the position can influence the job requirements. Usually, the higher in the hierarchy, the soft skills start to take over the [technical skills](https://www.stratascratch.com/blog/most-in-demand-data-science-technical-skills/?utm_source=blog&utm_medium=click&utm_campaign=dev.to). Aside from that, there are also some “crossover” data positions between data and sales positions or data and customer support positions. In the next table, there’s a summary of the most commonly required qualifications and experience by role. Since this can differ within the same position, it’s important that you carefully read a job ad to see if it fits you. ##Roles and Required Experience ![Roles and Required Experience for the data position at Microsoft](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/eplh9pw3qjmbdsc1eawx.png) ##Types of Data Positions Data positions in Microsoft are spread across multiple company teams. There are 26 teams, and most of them require some kind of a data professional. Due to that, these three data positions above can vary significantly in their requirements from team to team. Here’s the overview of all the teams that require data job positions and their descriptions. Below is a little more detailed info about what every team does and what your job description could be. ![Types of Data Positions at Microsoft](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/7q1v4ab8qrk40nypfatw.png) ###Business Development and Strategy This team is in charge of honing partnerships and transactions that will contribute to the company’s growth. It means they work with enterprises of various sizes to find areas for collaboration. Your work in this department will most probably consist of: • Analyzing the financial statements and reports. • Contributing to developing reporting and dashboards. • Provide insights that will support the team’s proposals and decisions. ###Business Programs and Operations The mission of this team is to provide the effective operational execution of the business programs. Its employees work on planning, designing, and implementing solutions for business programs. If you get a job in this team, you will do something along the following: • Conduct analyses across the business segments for future improvements. • Create metrics, reports, and dashboards for monitoring the effectiveness of the program’s implementation. • Provide insights that will support the team’s proposals and decisions. ###Consulting Services The Consulting Services team provides technical consulting to the customers who are using or maintaining the Microsoft technology. The team advises, educates, and supports customers to gain and maintain knowledge of their products according to Microsoft best practices. Data jobs in this team are a crossover between technical data jobs and consulting jobs. For sure, you have to have the relevant technical knowledge to advise and teach others. As a member of the team, your tasks will include: • Deliver training and presentations. • Learn new technologies. • Participate in challenging business and technological conversations. • Help formulate the solutions for the customers according to their needs. ###Customer Success This team is assigned the role of supporting customers in their digital transformation. They do that by helping them make the most of the Microsoft technologies they use. To achieve that, they also need technically skilled employees who will: • Use that skills and customers’ insights to develop the customer digital transformation plan. • Ensure all implemented changes show the highest possible levels of security, performance, and reliability. • Collaborate with others involved to create end-to-end solutions. ###Data Center It’s a department in charge of physical security, maintenance, monitoring of servers, workstations, ICS systems, etc. They ensure the non-stop availability of data to support services for the customers and businesses. Even though there is no huge requirement for data analysts in this team, they are sometimes needed. In that case, this is what you’ll probably do: • Create analytical models (and implement them) to improve understanding of the Data Center needs. • Analyze data and provide insights that will support staffing and other decisions. ###Engineering Engineering is Microsoft’s production line in a way. The design, code, build and test the products. If you’re looking for a data job, here you’ll find plenty of possibilities as a data analyst and data scientist : • Create analytics solutions. • Set up the reporting and create insights. • Use BI tools to visualize data. • Model data. • Use algorithms to solve business problems. ###Finance The Finance team delivers their financial knowledge on several levels. They analyze the product from the financial perspective and generally collaborate company-wide to ensure the overall profitability and growth of the company. As a data analyst in this team, you will: • Analyze markets and gain insights on their influence on the current and new products. • Perform quantitative analysis and provide insights and forecasts. • Create reports and financial models for supporting business decisions. • Use Machine Learning, AI, and/or Predictive Analytics to solve business problems. • Communicate insights and provide recommendations. ###Marketing Marketing team in Microsoft is taking care of various segments of marketing: advertising, PR and communication, brand image. They act internally and externally by reaching out to customers and businesses, as well as their own employees, and make sure all the products and services have the best possible marketing effect. As a data analyst, there’s a place for you there. You’ll support marketing decisions by: • Analyzing business proposals. • Gain insights about the product performance, current, and future marketing strategies. • Analyze various data to help develop product monetization and pricing. ###Research This is a team where you’ll probably feel at home. The Research team’s main purpose is a collaboration between the academic world and the industry. This collaboration relates to many topics such as artificial intelligence, data, computer science, machine learning, economics, sociology, etc. In most cases, this team offers the jobs of a researcher and data & applied scientists. These jobs generally involve: • Collaborate with (other) experts to create data-based and machine learning innovations. • Use machine learning to build customer-oriented solutions. • Create and optimize the algorithms to enhance the customer’s business performance. • Training models. • Analyze and visualize data. • Create patents and academic papers. ###Sales As in any company, the Sales team targets new customers, establishing the connection with them and selling the products to them. Their tasks, of course, include keeping the current customers and establishing a long and fruitful collaboration that will see the increase in the Microsoft products’ sales and income. You could use your knowledge here too. You’ll have the opportunity to: • Aggregate and analyze data on various levels. • Combine data and business knowledge to identify sales trends, processes, and opportunities. • Suggest improvement in the current and future sales strategies by means of regression and forecasting techniques. • Use technical knowledge of cloud, ML/AI, and analytics to increase the sales performance of the specific Microsoft products. ###Services This team is dedicated mainly to support the customers from the technical perspective in using different Microsoft products. Depending on the products, your role as a data expert can vary, but here’s what you could expect if you get the job here: • Provide technical support in problem escalation. • Database administration problem-solving • Database backup and maintenance. • Database optimization. • Database and code migration. • Use SQL, database, BI, and machine learning knowledge to support the customers and solve their issues. ###Supply Chain & Operations Management It’s a team that ensures the smooth delivery of the products to the customers. This involves maintaining the supply chain of the Microsoft products and the supply chain of the materials used in their production. All that has to include efficiency from the quality, price, and time perspective. This team offers opportunities to show your data knowledge. For example, you could be: • Support the supply strategies by analyzing costs. • Analyze and monitor product performance. • Support inventory planning. • Develop metrics and reporting according to the team’s needs. • Develop strategies that will overall lead to supply chain optimization. ###Technical Sales The members of this team work on increasing revenue and market share with the strategic enterprise clients. They provide and support customers with the architectural solutions and concepts that will benefit the user’s experience with Microsoft’s intelligent cloud. Here’s how you could use your data expertise: • Participate in designing and creating cloud-based and customer-oriented solutions. • Create a data architecture that will meet the customers’ demands. • Work cross-disciplinary within the customer’s department to smoothly transition to the cloud. • Perform analysis of the new customers acquisition potential and the business growth within the current customer portfolio. • Participate in the technical workshops, educations, and demonstrations of the product capabilities. ###Technology Sales This team also works on the client’s digital transformation by recognizing their needs and providing suggestions and technical support in that mission. Here you’ll also have the opportunity to showcase your technical and data knowledge. What you’ll work on is generally very similar to descriptions of the Technical Sales team. You’ll have to know the Microsoft products and the concepts these products are based on, such as relational databases, cloud computing, machine learning, reporting & analytics. You will then use that knowledge to support the customers and/or analyze the opportunities for sales increase. ##Outlining the Microsoft Data Scientist Interview Process Microsoft’s interview process consists of several rounds and, as with all the famous technology companies, is rigorous. To increase your performance in this interview process, we’ve prepared a general overview how the process will look like. That way, you will know what to expect and be prepared. The Microsoft interview process used to consist of both virtual and on-site interviews. However, due to the COVID-19 pandemic, the official statement by Microsoft confirms all the in-person interviews will be held virtually. This doesn’t change significantly the outline of the process overall and what you should expect. When you enter the interview process, you should expect the following: one phone screen and assessment, then 4-5 on-site interviews (or, better, face-to-face interviews, since the pandemic changed the approach). Here’s an overview of this process: ![Outlining the Microsoft Data Scientist Interview Process](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/8gy7ijwv2kiuz0fq7wie.png) ###Phone Screen and/or the Online Assessment After you’ve got a call from an HR recruiter or send a job application, the first step of the interview process in Microsoft is phone screening. This first step in the process usually lasts up to 60 minutes and will involve talking to a team member or your future boss. The screening will involve your CV review. Then some questions will follow. Usually, several behavioral and one easy-to-medium coding, data structure, algorithm, or some other technical question, depending on the position you applied for. The technical question will be assessed via an online code editor, and you’ll be given 30 minutes to solve it. It’s also possible that you’ll only have an online assessment of your technical skills. Usually, this lasts up to 90 minutes and involves three questions. ###Face-to-Face Interviews This phase involved spending the whole day at Microsoft premises and having 4 or 5 interviews. Now, the pandemic changed this to completely virtually-held interviews. This is the most important change. As before, these interviews will all be hour-long and will be conducted one-on-one. Here you can expect some more behavioral and technical questions. There will be more of them, and they will be more difficult than in the previous round. The interviews will involve talking to various members of your future team with different levels of technical knowledge and fields of expertise. The last face-to-face interview will be with a senior executive who has the power to veto or approve your hiring. Again, the purpose of this interview is to ask you some questions (be it behavioral or technical) to make sure all that was maybe missed in the previous interviews is covered. As a senior executive, the interviewer will also try to talk you into accepting the employment offer if they’re to make it. ###HR Interview The final step of the interviewing process will be the HR interview. This is an interview with the Human Resources employer and is more or less a formality. Here you’ll also be asked some behavioral and technical questions, but more with the purpose to make sure once again you’re the right candidate. In this interview, you’ll also discuss your salary, benefits, and other topics regarding your employment. ##Types of Questions Asked during the Microsoft Data Scientist Interview Microsoft’s data scientist interview questions can fit in the following four categories: • Behavioral Questions • Product Sense & Business Cases • Data Analysis & Coding • Modeling Techniques We’ll give you some examples of each category, along with the links to the answers and discussion pages. ###Behavioral Questions These are the questions asked to screen your behavior at work. How you react in certain situations, build interpersonal relationships, and perform in different situations. To be more specific, here are some examples: • Why are you leaving your current job? • Why do you want to work at Microsoft? • Describe a time when you had to learn a new technical skill on the job. • Tell us about some of the biggest lessons you've learned in life. Here you’ll need to express yourself, present yourself as a person and a professional. The most important thing is what you want to say, but it’s also important to know how to say it. You could [use our article for more guidance](https://www.stratascratch.com/blog/how-to-tell-your-story-in-an-interview/?utm_source=blog&utm_medium=click&utm_campaign=dev.to). ###Product Sense & Business Cases Here you’ll have to show how well you know Microsoft and its products. You’ll also have to answer the questions that require thinking and showing the ‘feeling’ for numbers, data, and estimates. • Explain a recursion to me like I’m 5 years old. • How would you design an alarm clock for deaf people? • What is your favorite Microsoft product and why? ###Data Analysis & Coding These are technical questions designed to screen your theoretical and practical knowledge in data analysis, data handling, and code writing. Here are some questions that you might be asked at Microsoft: • [Find the total number of downloads for paying and non-paying users by date](https://platform.stratascratch.com/coding/10300-premium-vs-freemium?python=&utm_source=blog&utm_medium=click&utm_campaign=dev.to).​ • [We have a table with employees and their salaries, however, some of the records are old and contain outdated salary information. Find the current salary of each employee assuming that salaries increase each year](https://platform.stratascratch.com/coding/10299-finding-updated-records?python=&utm_source=blog&utm_medium=click&utm_campaign=dev.to).​ • [Given a list of projects and employees mapped to each project, calculate by the amount of project budget allocated to each employee](https://platform.stratascratch.com/coding/10301-expensive-projects?python=&utm_source=blog&utm_medium=click&utm_campaign=dev.to).​ ###Modeling Techniques These questions intend to test your statistical, mathematical, and model-building knowledge. Here are the example questions you could expect when being interviewed: • [How to compute an inverse matrix faster by playing around with some computational tricks?​](https://platform.stratascratch.com/technical/2047-computational-tricks?utm_source=blog&utm_medium=click&utm_campaign=dev.to) • [How do you detect if a new observation is outlier?​](https://platform.stratascratch.com/technical/2231-new-observation-is-outlier?utm_source=blog&utm_medium=click&utm_campaign=dev.to) • [What is the definition of the variance?](https://platform.stratascratch.com/technical/2243-definition-of-variance?utm_source=blog&utm_medium=click&utm_campaign=dev.to) ##Quick Tips • Do your research on Microsoft, its industry, and how your role contributes to the company. • Be informed about the interview process and Microsoft products, especially if this is a product-oriented position. • Don’t think only about the current position, but think about where this position could lead you within the organization. • Be in touch with the latest ideas and developments in the tech industry. • Since all the interviews are currently held virtually, make your environment as comfortable as possible and check your equipment to avoid any technical difficulties. • Work on your technical and non-technical knowledge; assess the holes in your knowledge and/or experience, and try to patch them. • Don’t lose hope; even if you don’t get the job, you will gain interview experience which can help you to get your next job. ###Additional Resources We have articles about [Microsoft data scientist interview questions](https://www.stratascratch.com/blog/microsoft-data-scientist-interview-questions/?utm_source=blog&utm_medium=click&utm_campaign=dev.to) and an article dedicated only to the [SQL interview questions for data science positions at Microsoft](https://www.stratascratch.com/blog/microsoft-sql-interview-questions-for-data-science-position/?utm_source=blog&utm_medium=click&utm_campaign=dev.to). If you’re applying for a data analyst position, there’s an interview guide for that too. Feel free to use some other articles on our blog when preparing for the interview. You should also check Microsoft’s site too. It provides information about the [professions and teams](https://careers.microsoft.com/professionals/us/en/professions); it gives you some [interview tips](https://careers.microsoft.com/us/en/interviewtips) and [how to get hired](https://careers.microsoft.com/u/us/en/interviewtips). You can also use it to [search all the available openings](https://careers.microsoft.com/us/en). You can do that on [Glassdoor](https://www.glassdoor.com/member/home/index.htm), too, along with the salary for a certain position. [Levels.fyi](https://www.levels.fyi/company/Microsoft/salaries/) also has all the up-to-date information on [data science salaries and benefits](https://www.stratascratch.com/blog/how-much-do-data-scientists-make/?utm_source=blog&utm_medium=click&utm_campaign=dev.to).
nate_at_stratascratch
824,828
One year of technical writing: Where am I now?
Hey there developers! I know, I'm sorry! I have been very inconsistent recently, didn't post for...
0
2021-09-15T11:17:11
https://dev.to/geobrodas/one-year-of-technical-writing-where-am-i-now-2cb8
writing, technicalwriting, freelance
Hey there developers! I know, I'm sorry! I have been very inconsistent recently, didn't post for three months straight. But duty calls, college went fast these three months. Anyways you must be wondering how come I came all of a sudden! Thanks to the [Hashnode Bootcamp](https://hashnode.com/bootcamp)! I was able to relieve those old days, where I used to struggle with writing, and today I'm earning from the very thing! Come hear my story of how it all started. #### - *6th July 2020* : **The beginning** I bought a Udemy course on Web development after researching for hours on what I should do this Lockdown ( after wasting two months of binge watching series ). At first I wasn't sure of how I would go about but the instructor was really good at explaining stuff and soon I grew in love with coding. It gave me hopes of a career change. I knew there was more to it rather than just coding, and actually showcase my work out in the public. After that I got my ears on Open Source contribution. #### - *1st October 2020* : **Open Source World!** Hacktober Fest begins! I was really excited on how I would perform. I made some friends on the discord server, and soon enough, got a hang around what actually to do. Initially, I was nervous to send that pull request. Well, what's there to lose! It was a successful merge! The reply back from the maintainer just gave me enough motivation to complete the challenge. I used to watch a lot of youtubers during this time, when I came across a video titled *"Top skills you need to possess as a developer"*, and yeah you might have guessed it right by now, Blogging was one of them! Guess that video changed my life. #### - *12th October 2021* : **My first article!** Yeah and finally I did the impossible. I wrote my first article on [Dev](https://dev.to/geobrodas/hacktoberfest-2020-1amn) . I was always bad at writing essays back in my school days. I wouldn't even get half the allotted score. I knew my first article won't go viral, but I was off to a good start. ![image.png](https://cdn.hashnode.com/res/hashnode/image/upload/v1631624770239/gUQIS1Lg5.png) I started to read articles written by other developers, and later developed a taste in writing articles. Well it didn't just come by reading, I had to write more articles. #### - *9th April 2021* : **A boost much needed**! I got introduced to Hashnode around January through the hackathons. Soon enough, I even got a offer to work with a startup, thanks to my hackathon submission! What provoked me to write on Hashnode was the constant support I was receiving from the Hashnode staff. Later one fine day, I learnt [how to make a VSCode theme from scratch](https://geobrodas.hashnode.dev/make-your-very-own-vscode-theme-and-publish) , and wrote a brief article on it describing some tricks and errors one might face otherwise. Guess what! It got featured! The feeling, I was just proud of myself! That was the confirmation I was waiting for! #### - *11th May 2021* : **A dream come true** I wanted to take a step forward. I started to see a plenty of articles on freeCodeCamp. In my mind right now, I wanted to build a audience on Twitter. I reached out to the editorial team, and they were happy enough to bring me on their team. What a pleasure, to work with the team that strive to provide free tutorials and content on coding. Truly a honor. In no time I released my first article on [freeCodeCamp](https://www.freecodecamp.org/news/why-should-you-start-using-chakraui/) and the response was just mind-blowing. It was the first time I saw such an immense response. This was the time I realized that people were actually getting benefitted from what I write. The realization that I was helping other people, was truly a pleasure to experience. #### - *23rd July 2021* : **Leap of faith** I wanted to take one last jump. Something to make my parents feel proud, and make them realize that, what I'm doing is something serious and passionate about. I started to reach out multiple guest author programs. Thanks to [Edidiong Asikpo](https://twitter.com/didicodes) who came in clutch to post an article on [ways to earn money from blogging](https://edidiongasikpo.com/5-ways-developers-can-make-money-through-blogging). A week after I got back a reply! Swish it was game time. I made my mind clear, and wanted to focus on the article I was about to write for the company blog. A week after, I got paid for the work I did. The feeling? Unreal. The journey was filled with obstacles. I had friends that said it was going to be tough. The reality? Everything's tough, nothing comes for free. You have to work until you sweat. If you love what you're doing, go for it. Listen to your heart. ### My advice to upcoming writers - **Every writer has their own style of writing**. You may have to change it when you're representing a company blog like I did. But you can always write freely on platforms like Hashnode and Dev. - **Start writing one today**. It's tough to start, I have been there. But what's there to lose. If you feel your content can help even one developer, your in for the job. - **Read articles from other developers**. Illustration is something I learnt from reading articles written by other developers. I wasn't good at graphic design first, but there are free tools that can help you get started. - **Keep your content G-Rated**. There are many young developers who are going to read your articles. It might be misleading for them. - **Choose unique topics**. I personally don't advice to repeat the same articles again and again. Let's say TypeScript. I wouldn't advice to write about how to use it, as there are plenty of resources online, but you can write about how TypeScript helped your development process, or how important is it to add it in your job resume? > Like what I write? Support me [here](https://www.buymeacoffee.com/geobrodas)!
geobrodas
824,843
Entering Invalid Dates Is Not Possible Anymore in Angular Apps
How many times have you seen people making mistakes while entering dates? It is mostly due to the...
0
2021-09-15T11:57:33
https://www.syncfusion.com/blogs/post/entering-invalid-dates-is-not-possible-anymore-in-angular-apps.aspx
angular, webdev
--- title: Entering Invalid Dates Is Not Possible Anymore in Angular Apps published: true date: 2021-09-15 10:30:09 UTC tags: angular, webdev canonical_url: https://www.syncfusion.com/blogs/post/entering-invalid-dates-is-not-possible-anymore-in-angular-apps.aspx cover_image: https://dev-to-uploads.s3.amazonaws.com/uploads/articles/tfv51l5eo05ziwmrnrgm.png --- How many times have you seen people making mistakes while entering dates? It is mostly due to the lack of clarity in the UI as to format. The Syncfusion [Angular DatePicker](https://www.syncfusion.com/angular-ui-components/angular-datepicker "Link to Angular DatePicker") provides mask support to improve the user experience while entering dates by providing month, day, and year fields. These help users enter valid dates in the correct format and also keep them from entering invalid input dates. For example, if you enter 6 (June) in the month field, then you can enter only dates from 1 to 30 in the day field. The component won’t allow you to enter values above 30. In this blog post, we will see how to get started with the Angular DatePicker and enable mask support to easily handle dates in it. ## Setup Angular environment Follow these steps to set the angular CLI projects using the [Angular CLI](https://github.com/angular/angular-cli "Link to CLI tool for Angular on GitHub") tool. 1. First, install the latest version of Angular CLI locally in your application using the following command. | `npm install -g @angular/cli@latest` | **Note: ** If you would like to follow and run the application in **Angular 8 to 11,** you need to replace the CLI command version number with the corresponding Angular version number. | `npm install -g @angular/cli@<CLI VERSION>` | 1. Now, create a new Angular project by using the **ng new** command and navigate to the created project folder. Here, I am naming this Angular project **angular-datepicker-mask**. | `ng new < angular-datepicker-mask> cd < angular-datepicker-mask> ` | 1. Then, use the following command to install the [ej2-angular-calendars](https://www.npmjs.com/package/@syncfusion/ej2-angular-calendars "Link to ej2-angular-calendars npm package") npm package locally in the application. | `npm install @syncfusion/ej2-angular-calendars --save` | ## Adding Angular DatePicker Follow these steps to include the Angular DatePicker component in your application. 1. The following CSS files are available in the **../node\_modules/@syncfusion** package folder. This can be referenced in the [src/styles.css] file using the following code. **[styles.scss]** ```js @import '../node_modules/@syncfusion/ej2-base/styles/material.css'; @import '../node_modules/@syncfusion/ej2-buttons/styles/material.css'; @import '../node_modules/@syncfusion/ej2-inputs/styles/material.css'; @import '../node_modules/@syncfusion/ej2-popups/styles/material.css'; @import '../node_modules/@syncfusion/ej2-lists/styles/material.css'; @import '../node_modules/@syncfusion/ej2-splitbuttons/styles/material.css'; @import '../node_modules/@syncfusion/ej2-calendars/styles/material.css'; @import '../node_modules/@syncfusion/ej2-angular-calendars/styles/material.css'; ``` 1. Then, import the **DatePicker** module into the Angular application ( **app.module.ts** ) from the **ej2-angular-calendars** package. Refer to the following code example. **[app.module.ts]** ```js import { NgModule } from '@angular/core'; import { BrowserModule } from '@angular/platform-browser'; import { DatePickerModule } from '@syncfusion/ej2-angular-calendars'; import { AppComponent } from './app.component'; @NgModule({ declarations: [ AppComponent ], imports: [ BrowserModule,DatePickerModule ], providers: [], bootstrap: [AppComponent] }) export class AppModule { } ``` 1. Next, define the Angular DatePicker within the **component.html** file mapped against the **templateUrl** option in the **app.component.ts** file. **[app.component.html]** ```html <ejs-datepicker></ejs-datepicker> ``` 1. Now, run the application with the **ng serve** command and it will display a DatePicker on the browser like in the following screenshot. ![Angular DatePicker](https://www.syncfusion.com/blogs/wp-content/uploads/2021/09/Angular-DatePicker.png)<figcaption>Angular DatePicker</figcaption> Thus, we have included the DatePicker component in our Angular application. Let’s see how to enable the mask support to easily handle dates in the Angular DatePicker. ## Enable mask input You can use the **enableMask** property to enable the built-in date format masking. By default, the mask pattern is formatted based on the current culture. To use mask support, inject the **MaskedDateTimeService** module into the Angular DatePicker. Refer to the following code example. [**app.component.ts**] ```js import { Component } from '@angular/core'; import { MaskedDateTimeService } from '@syncfusion/ej2-angular-calendars'; @Component({ selector: 'app-root', styleUrls: ['./app.component.scss'], templateUrl: './app.component.html', providers: [MaskedDateTimeService], }) export class AppComponent { title = 'angular-datepicker-mask'; public enableMaskSupport: boolean = true; } ``` [**app.component.html]** ```html <div style="width: 300px; margin: auto;"> <ejs-datepicker [enableMask]="enableMaskSupport"> </ejs-datepicker> </div> ``` ![Enabling Mask Input in Angular DatePicker](https://www.syncfusion.com/blogs/wp-content/uploads/2021/09/Enabling-Mask-Input-in-Angular-DatePicker.png)<figcaption>Enabling Mask Input in Angular DatePicker</figcaption> ## Configure mask placeholder You can change the mask placeholder value through the **maskPlaceholder** property. By default, it takes the full name of date and time coordinates such as **day**** , month, year, **and** hour**. **Note:** While changing to a culture other than **English** , ensure that the locale text for the concerned culture is loaded through the load method of the [L10n](https://ej2.syncfusion.com/angular/documentation/datepicker/date-masking/#configure-mask-placeholder "Link to Configure Mask Placeholder documentation") class for mask placeholder values. Refer to the following code example in which we have customized the default **month/day/year** format to **MM/dd/yyyy**. [**app.component.ts**] ```js public maskPlaceholderValue: Object = {day: 'dd', month: 'MM', year: 'yyyy'} ``` [**app.component.html]** ```html <div style="width: 300px; margin: auto;"> <ejs-datepicker [enableMask]="enableMaskSupport" [maskPlaceholder]="maskPlaceholderValue"> </ejs-datepicker> </div> ``` ![Configuring Mask Placeholder in Angular DatePicker](https://www.syncfusion.com/blogs/wp-content/uploads/2021/09/Configuring-Mask-Placeholder-in-Angular-DatePicker.png)<figcaption>Configuring Mask Placeholder in Angular DatePicker</figcaption> ## Keyboard accessibility Also, the mask support in Angular DatePicker provides keyboard interaction to easily handle dates. With this, you can change the values, increments, and decrements of the selected portions of date and time coordinates using the **Up** and **Down** arrow keys. You can also use the **Right** and **Left** arrow keys to navigate from one segment to another. ![Keyboard Accessibility in Angular DatePicker](https://www.syncfusion.com/blogs/wp-content/uploads/2021/09/Keyboard-Accessibility-in-Angular-DatePicker.png)<figcaption>Keyboard Accessibility in Angular DatePicker</figcaption> ## Reference For more information, refer to the [Mask support in Angular DatePicker demos on the web](https://ej2.syncfusion.com/angular/demos/#/material/datepicker/input-mask "Link to Mask Support in Angular DatePicker demo on web") and the [GitHub](https://github.com/syncfusion/ej2-angular-ui-components/tree/master/components/calendars "Link to Mask Support in Angular DatePicker demo on GitHub") repository. ## Conclusion Thanks for reading! In this blog post, we have seen how to enable the masking feature to easily handle dates in our [Angular DatePicker](https://www.syncfusion.com/angular-ui-components/angular-datepicker "Link to Angular DatePicker") component. This feature helps users enter valid dates in the correct format and avoid data input errors. Also, try our Angular DatePicker component by downloading a [free 30-day trial](https://www.syncfusion.com/account/manage-trials/downloads "Link to the free evaluation of the Syncfusion Essential Studio"). Feel free to have a look at the [documentation](https://ej2.syncfusion.com/angular/documentation/datepicker/date-masking/ "Link to Mask Support in Angular DatePicker component documentation") to explore other available features. If you have any questions, please let us know in the comments section below. You can also contact us through our [support forum](https://www.syncfusion.com/forums/blazor-components "Link to the Syncfusion support forum") or [Direct-Trac](https://www.syncfusion.com/support/directtrac/incidents/newincident "Link to the Syncfusion support system Direct Trac"). We are always happy to assist you! ## Related blogs - [Update Data Without Re-rendering an Entire Grid in Angular](https://dev.to/karthickramasamy08/how-to-update-data-without-rerendering-an-entire-grid-in-angular-3o7p-temp-slug-8959103 "Link to How to Update Data Without Rerendering an Entire Grid in Angular blog") - [Load and View PDF Files in an Angular App](https://dev.to/syncfusion/how-to-load-and-view-pdf-files-in-an-angular-app-bjb "Link to How to Load and View PDF Files in an Angular App blog") - [A Complete Guide to Running a Full-Stack Angular Application in a Monorepo](https://dev.to/syncfusion/a-complete-guide-to-running-a-full-stack-angular-application-in-a-monorepo-kbg "Link to A Complete Guide to Running a Full-Stack Angular Application in a Monorepo blog") - [Binding a Firebase Data Source to Grid Using AngularFire2](https://dev.to/syncfusion/binding-a-firebase-data-source-to-grid-using-angularfire2-oki "Link to Binding a Firebase Data Source to Grid Using AngularFire2 blog")
sureshmohan
825,159
Slow Query Basics: Why Are Queries Slow?
Introduction ​ If you've ever worked with databases, you have probably encountered some...
0
2021-09-15T17:47:55
https://arctype.com/blog/mysql-slow-query-log
mysql, schema, guide
## Introduction ​ If you've ever worked with databases, you have probably encountered some queries that seem to take longer to execute than they should. Queries can become slow for various reasons ranging from improper index usage to bugs in the storage engine itself. However, in most cases, **queries become slow because developers or MySQL database administrators neglect to monitor them and keep an eye on their performance.** In this blog, we will figure out how to avoid that. ​ ## What is a Query? ​ To understand what makes queries slow and improve their performance, we have to start from the very bottom. First, we have to understand what a query fundamentally is–a simple question, huh? However, many developers and even very experienced database administrators could fail to answer. ​ ### MySQL Query Execution Sequence ​ Queries are tasks that are composed of smaller tasks. If we want to improve their performance, **we make those smaller tasks shorter or eliminate them**. Here’s how MySQL executes its queries: ​ 1. First and foremost, MySQL sends the SQL statement to the server for execution. 2. MySQL checks the query cache. If the results exist there, they are returned. If not, MySQL proceeds to the next step. 3. The server parses a given SQL query, and a query optimization plan is made. 4. The plan is executed, calls to storage engines are made. 5. Storage engines return rows – we see results! ​ However, to observe how MySQL executes its queries on a deeper level, we should probably profile them instead of simply looking at the shiny outside of them. That’s where the real fun begins. ​ ## Profiling Queries ​ By now, we have touched the outside of what makes queries run. Still, to optimize our slow queries, we must first understand what they do and what stages of execution they go through before trying to optimize anything – in other words, profile them. ​ Thankfully, if we want to make use of the power offered by profiling in MySQL, we won’t have a hassle – it’s really, really easy to do. ​​ ### Using SHOW PROFILES in MySQL ​ Enable profiling by running `SET profiling = 1;`, run your query, then issue a `SHOW PROFILES;` on MySQL. You should now be able to see through what stages your MySQL query went through and how long each of those stages took to execute (the table below represents states and durations returned when a `SELECT` query was profiled – the entire table is actually quite a bit larger, but since we are only interested in the states and durations, we are going to be observing that): |State | Duration | |------|----------| |Starting | 0.000017 | |Waiting for query cache lock | 0.000004 | |Waiting on query cache mutex | 0.000006 | |Checking query cache for query | 0.000027 | |Checking permissions | 0.000005 | |Opening tables | 0.000276 | |System lock | 0.000010 | |Waiting for query cache lock | 0.000022 | |Waiting on query cache mutex | 0.000021| |Init | 0.000007 | |Optimizing | 0.000005 | |Statistics | 0.000004 | |Preparing | 0.000055 | |Executing | 0.000042 | |Sending data | 0.000004 | |End | 0.000002 | |Query end | 0.000067 | |Closing tables | 0.000005 | |Freeing items | 0.000056 | |Logging slow query | 0.000001 | |Cleaning up | 0.000002| See what we meant by saying that “queries are tasks that are composed of smaller tasks”? These smaller tasks are listed above. Now that we know what tasks our query goes through before the results reach our screens, it should be easier to optimize. ​ ### Optimizing Your Queries ​ To optimize your query performance, make the execution time of those tasks shorter or make MySQL not execute them at all. “How do I do that?” – you ask? There are a couple of ways to navigate around this complex jungle: ​ |Action | Explanation | |-------|-------------| |Make sure to use appropriate permissions | Checking permissions is one of the first things that happen when a query is executed. By ensuring that the user you run queries with has proper permissions, you can shorten the task. | |Keep the query cache big enough | Make use of the `query_cache_size` variable if you are running MySQL <= 5.7.20. Though note that this variable was removed in MySQL 8. | |Properly use indexes and partitions | While both of them would slow down the performance of `INSERT`s, `UPDATE`s, and `DELETE`s, they would speed up read (`SELECT`) queries, sometimes by an order of magnitude. With indexes, MySQL will be able to execute `SELECT` queries faster because it will scan through less data – as a result, your queries will be faster. If you want to, you can also log all of the queries not using indexes by using the `log_queries_not_using_indexes` parameter, but for that, you would need to enable the `slow_query_log` parameter (set it to a value of `ON`). | |Don’t ask MySQL for data you don’t need | Instead of using `SELECT *`, select only the columns that are necessary for your query to execute successfully. In other words, don’t make MySQL examine data that is not necessary. | |If you want to, enable the slow query log. | As you can see, if a query is slow, it’s logged in the slow query log (it’s one of the last tasks that gets executed) – keep your `slow_query_log` variable `ON` and perhaps adjust how MySQL understands what a “slow query” is: by default, MySQL logs any query that runs for longer than 10 seconds, but this value can be adjusted by adjusting the `long_query_time parameter`. | ## What to Do After Profiling ​ Once you have profiled your queries, you should be set on a good path. You should be set on a good path because profiling helps you look at the past of your queries to make them performant in the future. However, there are a couple of additional things you would need to keep a watchful eye on: |What to Keep an Eye On? | Why? | |------------------------------|----------------------------------| |Schema and Data Types | Properly optimizing your schema and data types is crucial for high performance; do not ever neglect them – you will make your own life as a DBA harder. If you neglect to keep an eye on those things, chances are you will waste hard drive space and potentially degrade the performance of your database instances in the future.| | Character Sets and Collations | MySQL supports many different character sets and collations. Each of them must be used carefully both to save space and to avoid negatively impacting performance. In this case, avoid using character sets and collations of unknown descent to you; consult the MySQL manual or blogs like this one, learn and then apply your knowledge.| | Indexes | MySQL supports many kinds of indexes that could be twisted in such a way that helps accomplish a variety of goals: of course, they have their own upsides and downsides. However, in most of the use cases, they can dramatically improve performance–[we have dug into indexing in an older blog post](https://arctype.com/blog/mysql-index-performance/), so for further explanation, have a read.| | Partitions | Partitions, of course, are good friends of indexes, and they can also help improve query performance–however, only when used properly. For example, they can allow MySQL to back up or recover data relevant to one partition and not all data at once. [We have dug into partitions earlier on](https://arctype.com/blog/mysql-partitions/), so have a read if you want to figure out how it works on a deeper level.| | Server Settings | Server settings are a cornerstone of your MySQL instance–always keep an eye out for them. We will have a blog post focused on this specific topic, but for now, learning how to optimize InnoDB for big data sets should do the trick.| | Hardware | Hardware sits underneath everything you do in MySQL–by having proper hardware, you can properly optimize your server settings for high performance. Therefore, always use as much hardware as necessary and allocate enough resources to MySQL to make it run at the very best of its ability.| | Blogs and Documentation | Of course, blogs like the Arctype blog are also a perfect place to expand your knowledge. They can tell you how you should work with your database instances to improve your database performance on the go. Always keep an eye on documentation, too– it’s vital for your database both now and in the future.| Take care of all of the aforementioned things, and once you have, make sure to use a proper SQL client! Lukas is an ethical hacker, a MySQL database administrator, and a frequent conference speaker. Since 2014 Lukas has found and responsibly disclosed security flaws in some of the most visited websites in Lithuania and abroad including advertising, gift-buying, gaming, hosting websites as well as some websites of government institutions. Lukas runs one of the biggest & fastest data breach search engines in the world - BreachDirectory.com and frequently blogs in multiple places educating people about information security and other topics. He also runs his own blog over at lukasvileikis.com
rettx
825,433
CfP for AsyncAPI Conference is open! 😀 🎉
The Call for Papers (CfP) for our upcoming AsyncAPI Conference is open! 😀 It ends on October 17th,...
0
2021-09-15T22:33:07
https://dev.to/alejandra_quetzalli/cfp-for-asyncapi-conference-is-open-mm7
eventdriven, opensource, contributorswanted, speaking
The **Call for Papers (CfP)** for our upcoming [AsyncAPI Conference](https://conference.asyncapi.com/) is open! 😀 It <mark>ends on October 17th</mark>, which means **you have one month to apply**! 😱 ## Set aside November 16-18! 🦄 [AsyncAPI Conference](https://conference.asyncapi.com/) is for everyone in the community! 🦄 The main goal is to share and exchange the experiences between existing users and new community members. And have lots of fun. 😁 The community always needs more real examples/use cases of both the **[AsyncAPI spec](https://github.com/asyncapi/spec)** and **[tools](https://www.asyncapi.com/generator)**. That said, we don't want to place any limitations on the community and encourage submitters to share any and all ideas, in any way, shape, or form. The most important is to have some time for community members to share their experiences with each other. ## Dates to Remember: - **CFP Closes:** <mark>Sunday, October 17 at 11:59 PM PDT</mark> - **CFP Notifications:** Friday, October 22 - **Schedule Announcement:** Friday, October 29 - **Pre-recorded Video & Slide Due Date:** Friday, November 5 at 11:59 PM PDT - **Event Dates:** Tuesday, November 16 - Thursday, November 18 ## CfP Topic Suggestions Remember to ✨ have fun ✨ as you select your topic! 😀 Some ideas could be... - Real examples - Real use cases - AsyncAPI spec - AsyncAPI tools - etc. 👉🏽 <mark>Don't forget to apply</mark> and **submit your CfPs over [here](https://linuxfoundation.smapply.io/prog/asyncapi_conference_2021/).** ![Alt Text](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/ylk8ybogtjpzcq7vswhp.png) ## What if I want to sponsor AsyncAPI conference? If you would like to take a look at our sponsorship levels and learn more about where you can see your logo placements within the AsyncAPI Conference website, go **[here](https://opencollective.com/asyncapi/events/asyncapi-hackathon-and-conference-2021-3156d7af).** 😀 ![Alt Text](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/mib816as78zbfqrtehq6.png) ## Want to help with proposals selection? If you would like to help with the AsyncAPI proposals selection, simply contact us directly on [slack](https://asyncapi.slack.com/join/shared_invite/enQtNDY3MzI0NjU5OTQyLTM5NTlkYzFmZDQyMGVkNzVkOTRhMGU2N2VmMWRlOTdkNWE0YzdjMGQ2NzRlOWU1NGJkYjUyZDEzMzM3ZGYzYzM#/shared-invite/email) or feel free to raise your hand in [our public community GitHub Discussion thread](https://github.com/asyncapi/community/discussions/71) 🧵. ## We can't wait to read your proposals! 🦄 Let us know if there are any questions we can help with!
alejandra_quetzalli
825,581
Hiring Python Developers
Please send your resume to nakul.a@experionglobal.com Thankyou
0
2021-09-16T04:29:39
https://dev.to/nakullukan/hiring-1ib8
hiring
Please send your resume to **nakul.a@experionglobal.com** ![1631695643237](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/n5qgymu8d408thal72hc.jpg) Thankyou
nakullukan
825,759
Use Prometheus and Grafana to Visualize ISP Packet Loss
Background Since people started working from home, poor video/voice call connections have...
0
2021-09-16T07:28:06
https://dev.to/ericyi/use-prometheus-and-grafana-to-visualize-isp-packet-loss-2eh
opensource
## Background Since people started working from home, poor video/voice call connections have become a very annoying problem. However, it's hard for people to diagnose what is the root cause. People start blaming their ISPs, and I feel bad for them. In fact, there are a number of reasons that can cause poor video call connections, but if you can tell us with great confidence that my problem is not from your end. You should probably start monitoring your ISP packet loss. ## Prerequisites - Grafana(You can register a free [Grafana Cloud account](https://grafana.com/auth/sign-in?plcmt=top-nav&cta=myaccount)) - Prometheus (You can [install it](https://prometheus.io/docs/prometheus/latest/installation/) on your Raspberry Pi or NAS) - Open Source Router OS (OpenWRT, ClearOS, Asuswrt-Merlin etc) ## Process ### Set Up ping_exporter SSH in to your router > Download ping_exporter You can check which version you need [here.](https://github.com/czerwonk/ping_exporter/releases) For example: ```bash wget https://github.com/czerwonk/ping_exporter/releases#:~:text=ping_exporter_0.4.7_linux_arm64.tar.gz ``` Extract the file: ```bash tar -xf ping_exporter_*.tar.gz ping_exporter ``` Move to `/usr/local/bin`: ```bash mv ping_exporter /usr/local/bin ``` Choose the way you like to get the ISP's DNS servers on your router. For example: ```bash cat /etc/resolv.conf ``` Create a `ping_exporter.yaml` file under `/etc/ping_exporter/`: ```bash targets: - <Your ISP's DNS servers> ping: interval: 2s timeout: 3s history-size: 42 payload-size: 120 ``` Create a `ping_exporter.service` file under `/etc/systemd/system/`: ```bash [Unit] Description=ping_exporter [Service] User=root ExecStart=/usr/local/bin/ping_exporter --config.path /etc/ping_exporter/ping_exporter.yaml Restart=always [Install] WantedBy=multi-user.target ``` Reload the service files: ```bash sudo systemctl daemon-reload ``` Start your `ping_exporter.service`: ```bash sudo systemctl start ping_exporter.service ``` Check the status of your `ping_exporter.service`: ```bash sudo systemctl status ping_exporter.service ``` To enable your `ping_exporter.service` on every reboot: ```bash sudo systemctl enable ping_exporter.service ``` Get the results for testing via cURL: ```bash curl http://localhost:9427/metrics ``` ### Add a target to Prometheus In your Prometheus configuration file, add the target in the `static_config` section : ```bash - targets: ["<Your router's ip/dns address>:9427"] ``` The reload your Prometheus’ configuration. ### Create a Grafana Panel Add a new Panel in your home network's dashboard, we are going to use the `ping_loss_percent` metric. ```bash ping_loss_percent{instance="<Your router's ip/dns address>:9427",target="<Your ISP's DNS servers>"} ``` ![Packet Loss Pannel](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/2y7h6c4o2lgt3mjmkzwd.png) ⚠️ Please note for voice and video calls, any packet loss below 0.05 could be considered acceptable.
ericyi
825,791
My new book about Typescript 4 is published. AMA
My latest book TypeScript 4 Design Patterns and Best Practices is out for grabs.
0
2021-09-16T08:48:38
https://dev.to/theodesp/my-new-book-about-typescript-4-is-published-ama-5953
typescript, programming, learning
--- title: My new book about Typescript 4 is published. AMA published: true description: My latest book TypeScript 4 Design Patterns and Best Practices is out for grabs. tags: typescript, programming, learning cover_image: https://dev-to-uploads.s3.amazonaws.com/uploads/articles/p04oa6kyx3z7c4s4qf3t.png --- I'm happy to announce that my book, "TypeScript: 4 Design Patterns and Best Practices" is now available on Amazon: ![img](https://static.packt-cdn.com/products/9781800563421/cover/smaller) Amazon.com: [link](https://packt.link/3qwmL) Amazon.co.uk: [link](https://www.amazon.co.uk/TypeScript-Design-Patterns-Best-Practices/dp/1800563426/ref=sr_1_3?dchild=1&keywords=typescript+4&qid=1631781999&qsid=258-2412969-5194553&sr=8-3&sres=1800564732%2C148427010X%2C1800563426%2C0997303727%2CB0948BCH24%2CB08DXSC18H%2C180020616X%2CB08D6T6BKS%2C1379268907%2CB019TLHKVW%2CB096W2JWS3%2CB076ZXN6B9%2CB01MA5JA74%2C1617295345%2CB07WZXYTRH%2C1617295949&srpt=ABIS_BOOK) Take a hands-on approach and get up and running with the implementation of design patterns in TypeScript learning best practices for writing good testable code. If you want to ask few questions about the book, or how to write a technical book, then you Ask Me Anything. Thank you.
theodesp
825,803
Enjoy Embedded Video Calls in your Website
Arvia can be added to your website with just a single line of code! This is the new way of connecting...
0
2021-09-16T09:03:43
https://dev.to/arviatech/enjoy-embedded-video-calls-in-your-website-1jhn
javascript, webdev, webrtc, angular
Arvia can be added to your website with just a single line of code! This is the new way of connecting with your customers. If someone is interested in your products or services, comes to your website and search for details, right? But you can grow this relation bigger, faster, and more importantly way more human. We are taking it to the next level @ Arvia ! With Arvia, you can position a company representative on your website, live and visual. It is a privilege to see and understand customer’s current conditions and moods via their live gestures. This helps you do suggestions, cross-sell your services — products or give more details and showcase the products live. Would you like to boost up your sales? Would you like to multiply your customer satisfaction rates and grow exponentially? Arvia makes it happen. Customers can join your store live — anytime, from anywhere in seconds. Customers can go through the products, evaluate new suggestions, ask questions, and shop live, together with your representative. This is a new era of communication. You need to catch up with your rivals and even pass them to set the bar. Arvia is fast, easy to use, reliable, and giving you an exclusive opportunity to get more insights from your customers. Detailed admin panel helps you create, design, and inspect all actions in video call experiences. And you can position yourself (Company) — product, staff, services based on this insightful important data. You can check out all the features @ arvia.tech WE ARE ARVIA — Fast, Easy, Cloud, Global!
arviatech
825,810
How to Create a Random Hex Colour Generator in React
If you’re looking for the source code, then it’s available in the video. In this, we’re going to...
0
2021-09-16T09:19:23
https://dev.to/germavinsmoke/how-to-create-a-random-hex-colour-generator-in-react-2fp6
react, html, css, javascript
If you’re looking for the source code, then it’s available in the video. {% youtube PPZQ4-oPnAw %} In this, we’re going to see how to create a full-screen hex colour generator that generates colours randomly. We’ll create a separate component for generating this colour, and name it **RandomColor**. ![image](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/k9l0mizxqikcyxvfr1c1.png) ###useState It is used to store the generated colour and also to update the colour on a button click. It’ll help us in updating the colour of the page reactively. 😏 ###getRgb - This function is used to get a random value. The range of this function is 0 to 255 (because RGB ranges from 0 to 255 🧐). - `Math.random` generates a floating-point value between 0 and 1. On multiplying with **n**, we will get the value in the range of **0 and n — 1**. - But it’ll still be in decimal, so we can use Math.floorto get the floor round-off value. ###rgbToHex - This function is used to generate the hex code of the colour based on the three values of **red**, **blue**, and **green**. - We are mapping over these 3 values and applying `toString()` function over the value. We can provide a **radix** argument to this function which converts the number as per the base value provided. - Here, we are using **16** which is for **hexadecimal numbers** because hex code colour is made up of **hexadecimal numbers** 🧐. Then we are checking whether the length of the result is 1 or more, if it’s 1 then we’re adding **0** in front of it to normalize it. - At last, we’re joining the array and adding a `#` in front of the generated string. ###handleGenerate This function is called whenever we click on the button. It creates a colour object and then passes those red, blue, and green values to **rgbToHex** function. The returned value is used to update the colour. At last, we are setting the colour to the `backgroundColor` of the **container** and text `color` of the **button**. ![image](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/m57paawm3bmwajnnlw56.png) The styling part of the application is done like this. The **container** class is just to make sure the whole screen area is used and the button is placed in the centre. transition is just to provide a smooth **transition** of colour whenever a new colour is generated. **Button** styling in order to make it look good. **transform** and **box-shadow** are used to provide a 3D effect to the button whenever we hover on the button. And by doing all this we’ll finally have our random full-screen colour generator complete. It’ll look something like this 🤩👇🏻 ![image](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/lhb4fw7v0fayqnxbo1nd.png) That’s it, this is where our journey ends. I hope you were able to reach this point. 😃 Thanks!
germavinsmoke