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
358,325
Turn your server into a Centralize-Git-Repository.
GitHub is Great for Open Source projects, But i don't like GitHub and many other third-party code sto...
0
2020-06-18T21:02:08
https://dev.to/jswalker_in/turn-your-server-into-a-centralize-git-repository-1p
git, webdev, linux
GitHub is Great for Open Source projects, But i don't like GitHub and many other third-party code storage systems when it comes to building a Private-Product which is a highly closed-end system. I believe in "Your-Code-Your-Responsibility". Don't Transfer Your Responsibility to others or there will be greater consequences. If your organization is not involved in open-source development.GitHub is not for you, Private organization must follow own approach to build a product. Do it hard way to achieve best results,Setting own git server is piece of cake and secure too(If you want your product secure). ###Generate key ``` ssh-keygen -t rsa -b 4096 -C "your_email@example.com" ``` ### Obtain key from user and push into server ``` Copy local id_rsa for windows (C:/USER/YOUR-USERNAME/.ssh/id_rsa.pub) For linux(/root/.ssh/id_ras.pub) INTO Remote server /root/.ssh/authorized_keys ``` ### Create Directory to store your centralize git server ``` mkdir git-server cd git-server git init --bare ``` ### Access this Repo at local client ``` git clone root@ip-address:/git-server ``` ### Additional Note: If you like to make git more secure keep development and production copy where development copy is accessible to everyone in your organization and production copy allow only via special-mechanism such as Custom platform build in browser where user sync development code into production after checks-and-balance. For my scenario (Single engineer) I do not use git at the local/server.Simply use own platform where development code pushes into production mode after stable development channel. ![Alt Text](https://dev-to-uploads.s3.amazonaws.com/i/audd6xaybqk0ddz71r32.jpg) ###Moral Of the story IF I can do it as a single engineer, It's a teeny-tiny challenge for the Minimal Team of any organization. In Case you care about your product. EOF
jswalker_in
359,175
Analyzing a DataSet with Unsupervised Learning
Introduction The goal of this article is to show how Unsupervised Learning can be used in...
0
2020-06-20T18:21:59
https://dev.to/travelleroncode/analyzing-a-dataset-with-unsupervised-learning-31ld
machinelearning, datascience, azure
# Introduction The goal of this article is to show how Unsupervised Learning can be used in analyzing datasets. This article is a part of the *MSP Developer Stories* initiative by the Microsoft Student Partners (India) program. # What is Unsupervised Learning ? Generally, when we talk about Machine Learning, we say a model trained on some X and corresponding Y values to predict Y on unknown X's. This form of ML Algorithms is called Supervised Learning. Now, what if you are given with only X. Confused right? This kind of data is called unlabelled data and working with this kind of data is called *"Unsupervised Learning"*. ## Importance of Unsupervised Learning In the real world, most of the data is available in an unstructured format. Hence, it becomes extremely difficult to draw insights from them. Unsupervised Learning helps to draw similarities between the data and separate them into groups having unique labels. In this way, the unstructured data can be converted into a structured format. Due to this cognitive power to draw insights, deduce patterns from the data, and learn from those, unsupervised learning is often compared to human intelligence. # Types of Unsupervised Learning Applications This area of Machine Learning has got wider applications and is often considered as the real use of Artificial Intelligence. Some of these use cases are: * Clustering * Reinforcement Learning * Recommender Systems In this article, we will consider the first use case i.e. Clustering. # Clustering - Divide and Rule Clustering as the name suggests is grouping up of similar objects in groups. All elements in a group have similar properties. In the case of data, these objects are data points plotted in multi-dimensional space. Here we will take a famous dataset the *"California House Pricing Dataset"*. Our task will be to break the region into various clusters to gain some insights. So, let's get coding. # KMeans KMeans is a popular clustering algorithm. K-Means as the name suggests determines best k-center points (or centroids). After iteratively determining the k points, it assigns each example to the closest centroid thus forming k-clusters. Those examples nearest the same centroid belong to the same group. Let us say we have a dataset when plotted looks like this: ![Alt Text](https://dev-to-uploads.s3.amazonaws.com/i/dnzvrzn4g2fz8v671gtx.png) The k-means algorithm picks centroid locations to minimize the cumulative square of the distances from each example to its closest centroid. The dataset will be separated in the following manner using KMeans: ![Alt Text](https://dev-to-uploads.s3.amazonaws.com/i/29ct9eidwu91qxtk4j8l.png) In this article, we will take a look on how KMeans can be used to analyze the housing dataset. The dataset will be clustered in two formats: * With respect to Regions. * Finding out locations that have high housing prices. The entire project will be done on the Microsoft Azure Notebooks. # Setup Azure Notebooks The first and foremost thing is to get the environment ready for work. For this Microsoft Azure Notebooks is the right place to perform all Data Science projects. * Open [Microsoft Azure Notebooks](https://notebooks.azure.com/). * Create a new project ![Alt Text](https://dev-to-uploads.s3.amazonaws.com/i/35m2jebz4n9lebx4d3tv.png) Click on the project name and a project window will appear. * To upload any kind of additional file, get to this section. ![Alt Text](https://dev-to-uploads.s3.amazonaws.com/i/zi89d7pui8h653v4ywtl.png) Upload the dataset (.csv file) here * To create a notebook, folder, etc check this section. ![Alt Text](https://dev-to-uploads.s3.amazonaws.com/i/q5u8ve39pryeg1c6qnyp.png) Create a Jupyter notebook here with the following specifications. ![Alt Text](https://dev-to-uploads.s3.amazonaws.com/i/uxketqfs1k3zvkgeqhwc.png) * Click on "Run on Free Compute". Here, if you need more computation. ![Alt Text](https://dev-to-uploads.s3.amazonaws.com/i/p3tir6dgu4vxhi3c2lbq.png) * A Jupyter Notebook console will appear showing all the files. ![Alt Text](https://dev-to-uploads.s3.amazonaws.com/i/c49vbatcm89z193ckqzz.png) All set Let's get started. # Implementation The clustering will be done in two parts: * Divide all the geolocation points of California into two regions * In each region cluster points that have housing prices higher than the rest. At first, we start by exploring the dataset. ![Alt Text](https://dev-to-uploads.s3.amazonaws.com/i/2to3l6ruwvugxg8jlmf3.png) The dataset contains (latitudes, longitudes) and some feature columns that affect a house price. Next, we scatter plot all the points from the datasets. ![Alt Text](https://dev-to-uploads.s3.amazonaws.com/i/nzfuxdab81zl9v31u1jd.png) Wohoo! As one can see the plot clearly resembles the map of California. ### Load Fit & Predict The K-Means is loaded from sklearn package. The number of clusters (value of k) is set to two since we are trying to divide the location points into two regions. Next, fit the data and call .predict(). ![Alt Text](https://dev-to-uploads.s3.amazonaws.com/i/zylqywekqw0y52jyzqjq.png) Let's examine the result now: Since the k value was set to 2, we will have two centroids which can be viewed using the .centroid() attribute. ![Alt Text](https://dev-to-uploads.s3.amazonaws.com/i/088b95e6ywjqtkft7db3.png) The cluster labels can be viewed using .labels_() attribute, in this case, we will have two labels starting from 0. The labels are then stored in a column in the DataFrame and on doing value_count, the output turns out to be this. ![Alt Text](https://dev-to-uploads.s3.amazonaws.com/i/f99isykm6oj6mmcr0qqa.png) This shows that 6620 data points have been grouped as 0 and remaining as 1. Let's plot the points and label each cluster point with their cluster color. ![Alt Text](https://dev-to-uploads.s3.amazonaws.com/i/ttwrsi5ziw55ktpzbarq.png) *It is to be noted that RED indicates Cluster 0 (Region B) and GREEN indicated Cluster 1 (Region A).* All the geolocation data points have been successfully divided into two clusters and the original dataset has also been split into two and stored in two data frames. ![Alt Text](https://dev-to-uploads.s3.amazonaws.com/i/fv0ipkwg20mr5wk5lli9.png) With this, the first part of the Clustering process is done. Now let us consider the points cluster by cluster. # Cluster by house prices Rather than clustering the house prices of the entire dataset, one can take a small demographic area. As there was no way in figuring out the demographic, the previous cluster helped in dividing the entire dataset into two. The region that we are now considering is the GREEN Region or CLuster 1: ![Alt Text](https://dev-to-uploads.s3.amazonaws.com/i/7kqraghtmo46nuvje2kn.png) Similarly, region B can also be plotted like this: ![Alt Text](https://dev-to-uploads.s3.amazonaws.com/i/p1mj6s8og2q4fid3pj71.png) The target is to mark regions where house prices are higher than the rest. The *median_house_value* column will serve as the data points that need to be clustered. Before fitting this data to the model, we need to normalize the values so that the model doesn't get biased to values having a higher variance. This can be done using StandardScaler() from sklearn. *StandardScalar() scales the values in such a way that the mean value is 0 and the standard deviation is 1.* ![Alt Text](https://dev-to-uploads.s3.amazonaws.com/i/g8t1wy6xfi0vlt77xpsj.png) This scaled data is now fitted into the model and the prediction function is called. The number of clusters (k value) is set to two as the intention to divide into low and high prices. The results thus obtained is here. ![Alt Text](https://dev-to-uploads.s3.amazonaws.com/i/zf3n7hskhksev2ifyhfy.png) This shows the number of values in each cluster but this does not give any insight into which one signifies the cluster with high prices and which one low price. To make sense of this data the median value of the house prices in each cluster is calculated. This will show the central point of the range of values irrespective of the outliers. ![Alt Text](https://dev-to-uploads.s3.amazonaws.com/i/4n67r9jrkl5iwei1rdr9.png) Thus, it is clear that the data points in cluster 0 are at higher house prices as compared to cluster 1. A Scatter plot of the result will look like this: ![Alt Text](https://dev-to-uploads.s3.amazonaws.com/i/ucjv5ldgb78v141fprx7.png) A direct inference from this would be that the coastal areas are way more costly than the inner areas. This entire process is repeated for the other region and the results obtained are quite similar. ![Alt Text](https://dev-to-uploads.s3.amazonaws.com/i/oh65s2mq18h7bscqn03s.png) In this way, clustering helps in analyzing a dataset. Various other interpretations can be drawn using the other columns. Hence it's open for experimentation. # Creating an interactive plot Plots are extremely important when doing data analysis. Folium is an excellent library in python which allows us to plot geolocation points that are manipulated in python and plotted on an interactive leaflet map. ![Alt Text](https://dev-to-uploads.s3.amazonaws.com/i/ikj4ysdzn23wxgtn0vuv.jpg) The Microsoft Azure Notebook does not have Folium pre-installed so install it using the pip command. To get started first create the base map, the base map defines the region you will be working with. Here, let us take the mean of latitude and longitude respectively as the starting coordinates and plot the base map. ![Alt Text](https://dev-to-uploads.s3.amazonaws.com/i/1vehqs6qm3o0b3tks74w.png) Folium allows us to save any html generated using .save function. ![Alt Text](https://dev-to-uploads.s3.amazonaws.com/i/y4sawwc31o30oz8ss0o6.png) On the Map above, the location points will be marked using the function below: ![Alt Text](https://dev-to-uploads.s3.amazonaws.com/i/78g93o2c17td6f4nvxx4.png) The resultant map will look like this: ![Alt Text](https://dev-to-uploads.s3.amazonaws.com/i/heal4i1eujopaxupobdl.png) Finally, we need to highlight the locations that have higher prices. ![Alt Text](https://dev-to-uploads.s3.amazonaws.com/i/t2cwaqx88sb9xu35psnu.png) In this way, a dataset can be analyzed using unsupervised learning. # Conclusion Unsupervised Learning is a great way of dealing with datasets that are not structured, clustering thus helps in segregating the dataset based on common features. This dataset can further be used as a labeled dataset for Supervised Learning. In this article, the k-value has been fixed to 2 since the problem statement demands so but there are ways to determine the optimal value of k. Two such ways are the *Elbow method* and the *Silhouette Score* method. An example has been shown in the notebook. To work around with the code access it from here. [Project Link](https://notebooks.azure.com/avijit-chakraborty/projects/unsupervised-learning) Happy Learning!
travelleroncode
358,337
Having inclusive names in docs examples
We want to make the names we use in our docs examples more inclusive from both a gender and a cultura...
0
2020-06-18T21:33:24
https://dev.to/bravegrape/having-inclusive-names-in-docs-examples-2jo
discuss, inclusion, docs
We want to make the names we use in our docs examples more inclusive from both a gender and a cultural perspective. We use a [docs-as-code](https://www.writethedocs.org/guide/docs-as-code/) approach to docs so we're interested in automation and scalable approaches. Is this something you or your team have worked on? Could you recommend any best practices in approaching this? Thank you!
bravegrape
358,557
Answer: set expandtab in .vimrc not taking effect
answer re: set expandtab in .vimrc no...
0
2020-06-19T01:53:43
https://dev.to/icy1900/answer-set-expandtab-in-vimrc-not-taking-effect-2pn5
vim
{% stackoverflow 37962622 %}
icy1900
358,632
React Course Pre-Launch Giveaway
In celebration of our new React course launch (coming soon). Here’s our giveaway challenge to win a...
0
2020-06-19T06:38:49
https://alterclass.io/blog/react-course-pre-launch-giveaway
react, javascript, alterclass, webdev
In celebration of our new React course launch (coming soon). Here’s our giveaway challenge to **win a PRO access to the course**. To enter: 1. Follow us on Twitter [@AlterClassIO](https://twitter.com/AlterClassIO) 2. Retweet the [giveaway post](https://twitter.com/AlterClassIO/status/1273648921181642755?s=20) & tag 2 friends 3. Add a comment in the Twitter post to explain why you want to learn React The giveaway will run until the launch date. **Every Friday at 12pm (CET) 5 winners will be selected**.
gdangelo
358,852
Solving buffer.readUIntBE is not a function reading a JWKS key with NodeRSA
Recently while trying to read a public key in from a JWKS endpoint I was stumped by an error when imp...
0
2020-06-19T09:10:13
https://blog.kleeut.com/2020/06/solving-bufferreaduintbe-is-not.html
Recently while trying to read a public key in from a JWKS endpoint I was stumped by an error when importing the public key using [NodeRSA](https://github.com/rzcoder/node-rsa). My code looked like this: ```Typescript return rsa.importKey( { n: Buffer.from(jwksKey.n), e: jwksKey.e, }, "components-public" ); ``` The error was: ```bash TypeError: buffer.readUIntBE is not a function at Object.module.exports.get32IntFromBuffer (C:\dev\jwttest\node_modules\node-rsa\src\utils.js:43:27) at RSAKey.module.exports.Key.RSAKey.setPublic (C:\dev\jwttest\node_modules\node-rsa\src\libs\rsa.js:172:48) at Object.publicImport (C:\dev\jwttest\node_modules\node-rsa\src\formats\components.js:44:17) at Object.detectAndImport (C:\dev\jwttest\node_modules\node-rsa\src\formats\formats.js:65:48) at NodeRSA.module.exports.NodeRSA.importKey (C:\dev\jwttest\node_modules\node-rsa\src\NodeRSA.js:183:22) at C:\dev\jwttest\dist\jwks.js:53:20 at Generator.next (<anonymous>) at fulfilled (C:\dev\jwttest\dist\jwks.js:5:58) at processTicksAndRejections (internal/process/task_queues.js:93:5) ``` I couldn't see any issue with the way I was setting up the buffer. I was able to log the contents out. Everything looked correct. When I searched for `buffer.readUIntBE is not a function` I found nothing useful. It left my scratching my head and saying "What the damn hell!?". ![What the damn hell](https://dev-to-uploads.s3.amazonaws.com/i/sqlslw3u7n8a9o0ocusd.gif) Eventually I worked it out. The issue wasn't with th buffer I had so much as the one I didn't. I had been let down by own poor use of the Typescript type system. I had assumed that since the code was compiling that I was passing correct values and skipping reading the documentation. The mistake I had made was that the JWKS spec sets up the [`e` (Exponent) parameter](https://tools.ietf.org/html/rfc7518#section-6.3.1.2) as a Base64urlUInt-encoded string value and the `new NodeRSA().importKey({n,e}, "public-components")` api takes a `number`or a `Buffer` as the `n` parameter. In this case the error I was saying that `buffer.readUIntBE is not a function` where `buffer` is a `string` not a `Buffer`
kleeut
358,886
Entry Components Vs Declarations in Angular
Breaking down the differences when you are dealing with Angular components Hi! I am a full...
0
2020-06-19T10:24:08
https://dev.to/arpan_banerjee7/entry-components-vs-declarations-in-angular-5d
angular, entrycomponents, declarations
###Breaking down the differences when you are dealing with Angular components Hi! I am a full stack developer based out of West Bengal, India. I love digging deep into the trickier parts of the technologies. Here is one from my vault. Hope this helps you. Without further ado, let us dive straight into it. **For this you need to understand how angular actually works behind the scenes when it comes to creating components.** Any component as well as directives and pipes you plan on working with, you need to add them to your `declarations array` in `@NgModule` of `app.module.ts`(while working with multiple modules, we import the feature module in our `app.module.ts` imports array, and that feature module has all the components in its `declarations array`). The above mentioned step is important for angular to understand what's a component or which components and directives you have in your app because, **it does not automatically scan all your files**. You'd need to tell it which components exist, after creating a new component. *Still this alone only makes angular aware of it so that it is able to create such a component when it finds it in one of two places--* 1. The first place would be in your templates if in your templates angular finds a `selector of a component`--> then it basically looks into the `declarations array for that particular component-->finds that there and then is able to create that component. 2. The other place where angular will look for this component is in your `routes in your rout config`--> when you point at a component there angular will also `check that in the declarations array` and--> if it finds that there it is able to create such a component and load it. Now one place that **does not** work by default is when you want to create a component manually in code. Like when you want to create a `dynamic component` with `component factory` like an alert component maybe which only shows up when there is any error and **you neither mention the selector of it in any template nor in the rout configuration**. And now, here angular does not automatically reach out to the declarations array. It simply doesn't do that. You can complain about that. Still it's the case. You instead deliberately need to inform angular that in this case the alert component will need to be created at some place and that angular basically should be prepared for this. Generally angular will prepare itself for this creation when it finds a component in the `template` or in a `rout configuration`. But in our case as we haven't done either of the two things as mentioned above, angular won't prepare itself. Now to tell angular to be prepared for the creation of that component you need to add a special property to the object you pass to `@ngModule` besides `declarations` `import` and so on. That property is `entry components`, it is an array of component types, but only those components that will eventually be created without `routs` or `selectors`. **But with the launch of Angular 9, there were changes made behind the scenes, and it does all these work for you, you do not need to mention the entry components manually anymore.** I hope this clears some doubt regarding the entry components and declarations and how angular application works when it comes to deal with your components. [Here is the link to my stackoverflow answer.] (https://stackoverflow.com/questions/43815995/what-is-the-difference-between-declarations-and-entrycomponents/61896107#61896107) Credits--Learned these concepts from the Udemy course "Angular the Complete Guide" -by Maximilian Schwarzmüller . Thank you, for reading!
arpan_banerjee7
358,922
Should programming be taught in schools?
Should programming, logic &amp; algorithms be taught in schools? If so, from what age? What do you t...
0
2020-06-19T11:36:22
https://dev.to/reece_coombes/should-programming-be-taught-in-schools-19i4
discuss, education
Should programming, logic & algorithms be taught in schools? If so, from what age? What do you think? Would this be an unnecessary move or would it help train the next generation of programmers? Share your thoughts in the comments!
reece_coombes
358,976
Progressive Web Apps (PWAs): The future of mobile apps
Progressive web apps are continuously gaining momentum in the digital space. PWAs provide the best &a...
0
2020-06-19T13:16:25
https://dev.to/shanalaggarwal/progressive-web-apps-pwas-the-future-of-mobile-apps-g5i
[Progressive web apps](https://www.techaheadcorp.com/blog/progressive-web-apps/) are continuously gaining momentum in the digital space. PWAs provide the best & combined experience of web and mobile apps to the user. Businesses need it to stay ahead in the competition. If we talk in non-IT language, then it would be wrong to say that these are the websites built using wen technologies but with the features of an app. Modern technologies and development in browser and services have added enabled web developers to let users install web apps to their home page, receive push notifications and operate it even without internet connectivity. PWAs solve generic native apps issues like high data consumption, storage space, need for internet connectivity, development cost, etcetera. Cross-platform accessibility and offline accessibility to data are two of the major advantages of PWAs.
shanalaggarwal
359,067
PlaywrightSharp v0.10 for Firefox is here!
Firefox joined to the PlaywrightSharp family! What can I do with PlaywrightSharp.Firefox?...
0
2020-06-19T17:11:59
https://www.hardkoded.com/blog/playwright-sharp-firefox-010
playwright, csharp
--- title: PlaywrightSharp v0.10 for Firefox is here! published: true date: 2020-06-19 00:00:00 UTC tags: playwright,csharp canonical_url: https://www.hardkoded.com/blog/playwright-sharp-firefox-010 --- ![firefox](https://media.giphy.com/media/xsE65jaPsUKUo/giphy.gif) Firefox joined to the PlaywrightSharp family! ## What can I do with PlaywrightSharp.Firefox? You can do lots of things. ![a lot](https://media.giphy.com/media/qkdTy6tTmF7Xy/giphy.gif) Seriously! ![seriously](https://media.giphy.com/media/Ful8UzCFYAjlu/giphy.gif) You should be able to do almost everything you would do with his older brother PuppeteerSharp or his younger brother PlaywrightSharp.Chromium. This is how you can take a screenshot in PlaywrightSharp **NOW**! ```cs var options = new LaunchOptions { Headless = true }; Console.WriteLine("Downloading Firefox"); var firefox = new FirefoxBrowserType(); await firefox.CreateBrowserFetcher().DownloadAsync(); Console.WriteLine("Navigating google"); await using var browser = await firefox.LaunchAsync(options); var page = await browser.DefaultContext.NewPageAsync(); await page.GoToAsync("http://www.microsoft.com"); Console.WriteLine("Taking Screenshot"); File.WriteAllBytes(Path.Combine(Directory.GetCurrentDirectory(), "microsoft.png"), await page.ScreenshotAsync()); Console.WriteLine("Export completed"); ``` ## Is there anything I can't do? There are only two features not implemented on PlaywrightSharp.Firefox: PDF generator and Tracing. ## Can I use this package in Production? As [I mentioned when we launched Playwrightsharp.Chromium](https://www.hardkoded.com/blog/playwright-sharp-monthly-jun-2020), If you start using PlaywrightSharp now, the API is going to change, guaranteed, but you will jump into a project that will have way more support and new features. PuppeteerSharp doesn't support Firefox yet. So I believe PlaywrightSharp.Firefox, even in its 0.10 version, is the best library to automate Firefox in .NET. # Final words Now that we shipped our first version, I'm looking forward to getting more feedback. The issues tab in GitHub is open for all of you to share your ideas and thoughts. Don't forget to follow me on Twitter [@hardkoded](https://twitter.com/hardkoded) to get more updates. Don't stop coding!
hardkoded
359,126
Java/Spring Twitter Bot
Ah, ye ol' twitter bot... Gotta love them. I've been sat at home for the past couple of months self...
0
2020-06-19T17:35:45
https://dev.to/goldennoodles/java-spring-twitter-bot-2ceo
java, twitter, spring, bot
Ah, ye ol' twitter bot... Gotta love them. I've been sat at home for the past couple of months self-isolating and have become dreadfully bored.. So why not work on a cool little project? I definitely didn't get super excited and giggled like I was witing my first hello world when the @ItsMelonBot actually posted a tweet. Believe me, I know its nothing fancy, I essentially do this every day at work but it was still pretty cool non the less... It the little things in life! The journey began with me going through medium until I came across a post 'cool programming projects' and saw the twitter bot and thought... why not. I needed an idea, a retweet bot? Boring. A trend bot. Booooring. How about a melon bot?... A what? ![Alt Text](https://dev-to-uploads.s3.amazonaws.com/i/zmm7m2mt4aa6gqorb9r3.PNG) I kicked started Intellij and started the process, had it finished in 15 minutes or so. The thing that did take me ages to get my head around was deploying it into Azure. Now that... that was a b****. I tried to sign up to AWS but for whatever reason AWS didn't like me very much so off to Azure I went. Azure is seriously complicated... It took a while to get my head around how it all works but we got there in the end and it made deploying my bot to the cloud much faster and easier. For anyone interested, I've created a public GitHub repo with detailed documentation and comments on how to get it up and running, thought some of you would like to play around with it or add some functionality. https://github.com/goldennoodles/Spring-Twitter-Bot ![Alt Text](https://dev-to-uploads.s3.amazonaws.com/i/q7mrxjrq5k7rwa0z61r7.PNG) Just wanted to get my thoughts on paper. If you would like to see a full tutorial on deploying it, etc. Let me know! Oh and follow the bot, he's pretty funny. https://twitter.com/ItsMelonBot Rus - ItsMelonBot's papa.
goldennoodles
359,159
Does Java pass only by value?
When it comes to Java in calling a method and passing arguments as primitives, there’s no doubt that...
0
2020-06-19T18:59:14
https://dev.to/vivekworks/does-java-pass-only-by-value-3l7l
java, c, cpp
When it comes to Java in calling a method and passing arguments as primitives, there’s no doubt that it follows the pass by value model. Trouble in understanding comes when dealing with Objects. Since reference types store the address of the object, when reference types are passed as arguments, it’s the memory address of the object that is passed and any change to the object’s nature (instance variables) inside the called method reflects in the caller. This raises the question, _Does Java pass by reference when it comes to reference types?_ __Variables__ Before getting into the discussion of pass by value/reference, let’s understand about the kind of variables apart from the standard variable that were available to programmers in the languages that predate Java. *__Pointers__* — In C/C++, there are special type of variables that stored the address of any type of variable called Pointers. Pointers are usually assigned with address of another variable or they're made to point to nothing (NULL pointer). Pointers are the reference types in Java. *__Reference Variables__* — In C++, another special type of variable that acts as an alias/alternative name to the original variable exists called Reference Variable. So, any change to the original variable or it’s aliases affects everywhere. Reference variables are declared using & operator and must be initialized during creation as it doesn’t accept NULL. Look at below code example in C++. Note that * and & operators have different functionality in a declaration and an expression. ```cpp #include <iostream> using namespace std; int main(){ int var = 45; //Simple variable , stores 45 as its value int* varPtr = &var; //Pointer variable , stores the address of var as its value int** varPtrPtr = &varPtr; //Pointer variable , double pointer, stores the address of varPtr as its value int& varRef = var; //Reference variable, acts as a reference to var int* varRefPtr = &varRef; //Pointer variable , stores the address of varRef as its value cout << "\nvar : " << var; cout << "\nvarPtr : " << varPtr; cout << "\nvarPtrPtr : " << varPtrPtr; cout << "\nvarRef : " << varRef; cout << "\nvarRefPtr : " << varRefPtr; } /* * * Sample Output * -------------------- * var : 45 * varPtr : 0x61fdb4 * varPtrPtr : 0x61fda8 * varRef : 45 * varRefPtr : 0x61fdb4 * * */ ``` From the above output, we can see that __varPtr__ stored the address of __var__ whereas __varRef__ stored the value of var. Similarly, the address of __varRef__ i.e., __varRefPtr__ is identical to the address of __var__ i.e., __varPtr__. This proves that the pointers and reference variables are different conceptually. __Pass by value vs Pass by reference in C++__ Now that we understood different types of variables available, let’s see a sample swap program in C++ employing these different variables. Here is summary of various functions in the program. - _swapByValue_ — This function takes in two simple variables and swaps using a temp variable. - _swapByPointer_ — This function takes in two pointer variables and attempts swapping. Note that here pointer dereferencing isn’t used to show the difference between pointer and reference variables. - _swapByReference_ — This function takes in two reference variables and swaps them. - _swapByPointerDereference_ — This function takes in two pointer variables and dereferences it using the address. ```cpp #include <iostream> using namespace std; void swapByPointerDereference(int* a4, int* b4){ cout << "\nEnters : a4 value is " <<a4 <<", b4 value is " << b4; cout << "\nEnters : a4 address is " << &a4 <<", b3 address is " << &b4; int temp = *a4; *a4 = *b4; *b4 = temp; cout << "\nExits : a4 value is " <<a4 <<", b4 value is " << b4; cout << "\nExits : a4 address is " << &a4 <<", b4 address is " << &b4 << "\n"; } void swapByReference(int& a3, int& b3){ cout << "\nEnters : a3 value is " <<a3 <<", b3 value is " << b3; cout << "\nEnters : a3 address is " << &a3 <<", b3 address is " << &b3; int temp = a3; a3 = b3; b3 = temp; cout << "\nExits : a3 value is " <<a3 <<", b3 value is " << b3; cout << "\nExits : a3 address is " << &a3 <<", b3 address is " << &b3 << "\n"; } void swapByValue(int a1, int b1){ cout << "\nEnters : a1 value is " <<a1 <<", b1 value is " << b1; cout << "\nEnters : a1 address is " << &a1 <<", b1 address is " << &b1; int temp = a1; a1 = b1; b1 = temp; cout << "\nExits : a1 value is " <<a1 <<", b1 value is " << b1; cout << "\nExits : a1 address is " << &a1 <<", b1 address is " << &b1 << "\n"; } void swapByPointer(int* a2, int* b2){ cout << "\nEnters : a2 value is " <<a2 <<", b2 value is " << b2; cout << "\nEnters : a2 address is " << &a2 <<", b2 address is " << &b2; int* temp = a2; a2 = b2; b2 = temp; cout << "\nExits : a2 value is " <<a2 <<", b2 value is " << b2; cout << "\nExits : a2 address is " << &a2 <<", b2 address is " << &b2 << "\n"; } int main(){ int a1 = 45; int b1 = 65; int a2 = 15; int b2 = 35; int a3 = 25; int b3 = 55; int a4 = 75; int b4 = 95; cout << "\n*-----Swap By Value-----*"; cout << "\nBefore : a1 value is " << a1 << ", b1 value is " << b1; cout << "\nBefore : a1 address is " << &a1 << ", b1 address is " << &b1; swapByValue(a1, b1); cout << "After : a1 value is " << a1 << ", b1 value is " << b1 << "\n"; cout << "After : a1 address is " << &a1 << ", b1 address is " << &b1 << "\n"; cout << "\n*-----Swap By Pointer-----*"; cout << "\nBefore : a2 value is " << a2 << ", b2 value is " << b2; cout << "\nBefore : a2 address is " << &a2 << ", b2 address is " << &b2; swapByPointer(&a2, &b2); cout << "After : a2 value is " << a2 << ", b2 value is " << b2 << "\n"; cout << "After : a2 address is " << &a2 << ", b2 address is " << &b2 << "\n"; cout << "\n*-----Swap By Reference-----*"; cout << "\nBefore : a3 value is " << a3 << ", b3 value is " << b3; cout << "\nBefore : a3 address is " << &a3 << ", b3 address is " << &b3; swapByReference(a3, b3); cout << "After : a3 value is " << a3 << ", b3 value is " << b3 << "\n"; cout << "After : a3 address is " << &a3 << ", b3 address is " << &b3 << "\n"; cout << "\n*-----Swap By Pointer Dereference-----*"; cout << "\nBefore : a4 value is " << a4 << ", b4 value is " << b4; cout << "\nBefore : a4 address is " << &a4 << ", b4 address is " << &b4; swapByPointerDereference(&a4, &b4); cout << "After : a4 value is " << a4 << ", b4 value is " << b4 << "\n"; cout << "After : a4 address is " << &a4 << ", b4 address is " << &b4 << "\n"; } /* * * Sample Output * --------------- * * *-----Swap By Value-----* * Before : a1 value is 45, b1 value is 65 * Before : a1 address is 0x61fe1c, b1 address is 0x61fe18 * Enters : a1 value is 45, b1 value is 65 * Enters : a1 address is 0x61fde0, b1 address is 0x61fde8 * Exits : a1 value is 65, b1 value is 45 * Exits : a1 address is 0x61fde0, b1 address is 0x61fde8 * After : a1 value is 45, b1 value is 65 * After : a1 address is 0x61fe1c, b1 address is 0x61fe18 * * *-----Swap By Pointer-----* * Before : a2 value is 15, b2 value is 35 * Before : a2 address is 0x61fe14, b2 address is 0x61fe10 * Enters : a2 value is 0x61fe14, b2 value is 0x61fe10 * Enters : a2 address is 0x61fde0, b2 address is 0x61fde8 * Exits : a2 value is 0x61fe10, b2 value is 0x61fe14 * Exits : a2 address is 0x61fde0, b2 address is 0x61fde8 * After : a2 value is 15, b2 value is 35 * After : a2 address is 0x61fe14, b2 address is 0x61fe10 * * *-----Swap By Reference-----* * Before : a3 value is 25, b3 value is 55 * Before : a3 address is 0x61fe0c, b3 address is 0x61fe08 * Enters : a3 value is 25, b3 value is 55 * Enters : a3 address is 0x61fe0c, b3 address is 0x61fe08 * Exits : a3 value is 55, b3 value is 25 * Exits : a3 address is 0x61fe0c, b3 address is 0x61fe08 * After : a3 value is 55, b3 value is 25 * After : a3 address is 0x61fe0c, b3 address is 0x61fe08 * * *-----Swap By Pointer Dereference-----* * Before : a4 value is 75, b4 value is 95 * Before : a4 address is 0x61fe04, b4 address is 0x61fe00 * Enters : a4 value is 0x61fe04, b4 value is 0x61fe00 * Enters : a4 address is 0x61fde0, b3 address is 0x61fde8 * Exits : a4 value is 0x61fe04, b4 value is 0x61fe00 * Exits : a4 address is 0x61fde0, b4 address is 0x61fde8 * After : a4 value is 95, b4 value is 75 * After : a4 address is 0x61fe04, b4 address is 0x61fe00 * */ ``` The output clearly shows that only during the execution of _swapByReference_ routine, the value & address of variables remained the same. Though _swapByPointerDereference_ function swapped the values, they just employed pass by value with address and performed dereferencing. It is evident from the difference in the addresses of variables between the caller and called function. Thus it proves that only through reference variables, pass by reference can be employed. __Pass by value vs Pass by reference in Java__ In Java, there are no such variables as reference variables. The reference type that store the address of an object is just a pointer to the object. Lets see a similar swap program to the one seen above in Java language. The program can be contains three methods and they do the following, - _swapByValue_ — Method that swaps two primitives - _swapByReferenceType_ — Method that swap two reference types - _swapByObjectManipulation_ — Method that swaps objects by doing something similar to pointer dereferencing using Java dot operator ```java class Person { int id; String name; Person(int id, String name){ this.id = id; this.name = name; } } public class PassByModel { public static void main(String... args) { Person p1 = new Person(1, "Person1.0"); Person p2 = new Person(2, "Person2.0"); Person p3 = new Person(3, "Person3.0"); Person p4 = new Person(4, "Person4.0"); int a = 1, b = 2; System.out.println(); System.out.println("*-----Swap By Value-----*"); System.out.println("Before : a is "+a+", b is "+b); swapByValue(a, b); System.out.println("After : a is "+a+", b is "+b); System.out.println(); System.out.println("*-----Swap By Reference Type-----*"); System.out.println("Before : p1 is "+p1+", p2 is "+p2); System.out.println("Before : p1 id is "+p1.id+", p1 name is "+p1.name+"; p2 id is "+p2.id+", p2 name is "+p2.name); swapByReferenceType(p1, p2); System.out.println("After : p1 is "+p1+", p2 is "+p2); System.out.println("After : p1 id is "+p1.id+", p1 name is "+p1.name+"; p2 id is "+p2.id+", p2 name is "+p2.name); System.out.println(); System.out.println("*-----Swap By Object Manipulation-----*"); System.out.println("Before : p3 is "+p3+", p4 is "+p4); System.out.println("Before : p3 id is "+p3.id+", p3 name is "+p3.name+"; p4 id is "+p4.id+", p4 name is "+p4.name); swapByObjectManipulation(p3, p4); System.out.println("After : p3 is "+p3+", p4 is "+p4); System.out.println("After : p3 id is "+p3.id+", p3 name is "+p3.name+"; p4 id is "+p4.id+", p4 name is "+p4.name); } static void swapByValue(int a, int b) { System.out.println("Enters : a is "+a+", b is "+b); int temp = a; a = b; b = temp; System.out.println("Exits : a is "+a+", b is "+b); } static void swapByReferenceType(Person p1, Person p2) { System.out.println("Enters : p1 is "+p1+", p2 is "+p2); Person temp = p1; p1 = p2; p2 = temp; System.out.println("Exits : p1 is "+p1+", p2 is "+p2); } static void swapByObjectManipulation(Person p3, Person p4) { System.out.println("Enters : p3 is "+p3+", p4 is "+p4); Person temp = p3; p3.id = p3.id; p3.name = p3.name; p4.id = temp.id; p4.name = temp.name; System.out.println("Exits : p3 is "+p3+", p4 is "+p4); } } /* * Sample Output * ------------- * * *-----Swap By Value-----* * Before : a is 1, b is 2 * Enters : a is 1, b is 2 * Exits : a is 2, b is 1 * After : a is 1, b is 2 * * *-----Swap By Reference Type-----* * Before : p1 is Person@18e8568, p2 is Person@33e5ccce * Before : p1 id is 1, p1 name is Person1.0; p2 id is 2, p2 name is Person2.0 * Enters : p1 is Person@18e8568, p2 is Person@33e5ccce * Exits : p1 is Person@33e5ccce, p2 is Person@18e8568 * After : p1 is Person@18e8568, p2 is Person@33e5ccce * After : p1 id is 1, p1 name is Person1.0; p2 id is 2, p2 name is Person2.0 * *-----Swap By Object Manipulation-----* * Before : p3 is Person@326de728, p4 is Person@25618e91 * Before : p3 id is 3, p3 name is Person3.0; p4 id is 4, p4 name is Person4.0 * Enters : p3 is Person@326de728, p4 is Person@25618e91 * Exits : p3 is Person@326de728, p4 is Person@25618e91 * After : p3 is Person@326de728, p4 is Person@25618e91 * After : p3 id is 3, p3 name is Person3.0; p4 id is 3, p4 name is Person3.0 * */ ``` The methods _swapByValue_ and _swapByReference_ produce similar output. Even though the reference type holds the address of an object as its value (Person), the value is just assigned onto the parameter and these parameters are no direct references to the object created in the caller. Java language doesn’t allow a programmer to create reference variables. It can be concluded from the above experiment that pass by reference is never really allowed in Java. Java is designed with C as the fundamental programming model and C++ for the OOP principles. Java passes values to methods and these values are just copied across parameters be it primitives or reference types. It is often misunderstood that since the reference types store the address of an object, it is passed by reference. Reference types are pointers and not reference variables. In fact, there are no reference variables or aliases/alternatives in Java as in C++. Answering the question, _Java passes only by value for both primitives and reference types!!!_ Useful links on the topic https://stackoverflow.com/questions/40480/is-java-pass-by-reference-or-pass-by-value https://stackoverflow.com/questions/1961146/memory-address-of-variables-in-java https://stackoverflow.com/questions/14612314/how-are-variable-names-stored-in-memory-in-c https://stackoverflow.com/questions/48204770/get-name-of-variable-from-its-address
vivekworks
359,244
What’re the Differences between Software Engineering, Application Lifecycle Management and Project Management?
A post by Franco Scarpa
0
2020-06-19T22:43:35
https://dev.to/francoscarpa/what-re-the-differences-between-software-engineering-application-lifecycle-management-and-project-management-264a
help, discuss, devops, management
francoscarpa
359,330
Rusty Boy - Week 1: Of Timing and Modes
Hello there! It's been a week since my last report and, as promised, I'm back here with the news of...
7,308
2020-06-22T03:37:35
https://dev.to/rainbowcookie32/rusty-boy-week-1-of-timing-and-modes-575i
gameboy, emulation, rust
*Hello there!* It's been a week since my last report and, as promised, I'm back here with the news of the rusty lad. It's been an *interesting* week. Let's jump into it. #### Monday I started the week by looking into Dr. Mario and why it wouldn't boot. I haven't seen this one getting to the menu on Rusty-Boy since forever, so it was about time I took a look. So I set a breakpoint after the Bootrom's execution and started stepping. I use BGB as my control emulator, since it's pretty accurate and it has a great debugger. ##### ___It's about Time___ After a while stepping, interrupts got enabled. This is where debugging starts to get tricky. My timing isn't great, especially when compared to BGB's, so I start triggering interrupts often while my control emulator just keeps running fine. My solution to this was to just set a breakpoint on the return address, and let the game run the interrupt routine. Doing this showed an interesting thing: the game would very frequently enter the Timer interrupt, and it'd spend a good chunk of time on it. Eventually, I hit Resume after entering an interrupt and the game never returned from it. That's where I decided to check something - what would happen if I disabled the Timer interrupt? Well, the game got to the menu just fine! ![Dr. Mario's Menu](https://dev-to-uploads.s3.amazonaws.com/i/0l9xr0rdhf9osl53mk00.png)<figcaption>Now that's something I haven't seen in a while!</figcaption> But good things don't last for long, and a second or two later, the game goes into a white screen and never recovers. It enters a loop where it waits for a certain display mode switch to happen, but the LCD is disabled, so it won't happen (as far as I know at least). It's not the first time I've seen this issue, which makes it a bit more interesting, but I poked around for a while and couldn't find an issue, so I moved on for the time being. ##### ___The Rogue Window - Part 1___ To finish the day, I took a look at the Window rendering. As I briefly mentioned last week, the window likes to render in the middle of the background in a few games. Apparently just pushing the window out of the screen was simpler than just, you know, disabling it. I'm not sure I really get why, but ok. I started looking at the most obvious thing - checking if the coordinates were actually correct. My test subject for this was Bomberman. It uses the window in fixed locations during its intro sequences, and it actually showed the issue perfectly. ![Broken Window Rendering](https://dev-to-uploads.s3.amazonaws.com/i/5uwyfkqworgkqy1j8p9a.png)<figcaption>The Window clearly is not supposed to be there!</figcaption> So I loaded the game on both Rusty-Boy and BGB, paused it on the roughly the same spot, and compared both emu's window coordinates. And yeah, the values were indeed different! Progress, right? Nope. A few minutes later I remembered a kind of important detail - Rusty Boy shows coordinates in *decimal* values, while BGB shows all values in *hexadecimal*. So I changed the debugger's formatting so it'd show hex values, and now the values are the same. So much for that theory then, back to the drawing board. #### Tuesday This one is barely worth mentioning, since I spent most of the day trying to fix networking issues around the house. Still managed to work on the emu a bit. I messed around with the Window's position a bit and came to the conclussion that the issue was definitely on the *blitting* stage. Blitting is basically the process of merging textures together (the very simplified explanation I work with). Since this is basically the most interesting thing that happened this day, I might as well explain a bit how I do rendering on Rusty Boy. ##### ___Rusty Rendering 101___ Rendering in Rusty Boy has been quite the rollercoaster, but currently it's done mostly using Textures. The Background and the Window both have their own Textures, which are drawn line by line and then sent to the UI thread for displaying when the Vblank period is about to end. Sprites and Tiles are cached. This cache is invalidated based on a hash of their memory sections. If it changes, then the cache gets nuked and regenerated. Tiles have 2 banks in memory, so they get also get one cache each. The rendering process begins on the emulation thread, on the Video chip side of things. It first checks whether or not it should regenerate caches, and acts accordingly. Then, if it's on the correct mode, it draws a line of the background and the window. The lines are drawn using the tiles in the cache, and which tile to use is indicated by the data in the background maps - these contain a value pointing to each tile that should be drawn on screen. For the background, the lines usually have an offset - the scrolling values. This allows games to move the background horizontally or vertically, but it can also be changed when reaching a specific line using interrupt to generate [some interesting effects](https://www.youtube.com/watch?v=NxKRRTW5934). The results are then saved as an array of color data, and sent to the UI thread. The UI thread will receive an object that contains 2 backgrounds (one scrolled for the screen, and a pure one), the window, and all the sprites. The actual textures are then generated and upscaled to the target resolution, so they can then be blitted into a final one which is showed on the Screen window. This is done for the background, the window (if it's enabled), and all sprites (if they should be displayed). The unscrolled Background and Window textures are also put into the Video Debugger - it can be useful to debug graphical issues (like the window being on top of the background when it shouldn't). ![debugger](https://dev-to-uploads.s3.amazonaws.com/i/y30toufogn1dfggsefyb.png)<figcaption>The background and the window, as shown on the Video Debugger</figcaption> I think that basically sums up the current rendering process. Let's move on. #### Wednesday Oh boy, Wednesday was quite a ride. I started the day by polishing code a bit here and there. I started with the Timer, since I haven't touched that in centuries. Nothing was fixed, but it looks better now at least. Then I moved to the Video file... Dear God why did I do that. ##### ___The Failed Cleanup Attempt___ My goal was basically to clean up interrupt requests and mode switching. This involves mostly 2 registers: LCD Status and Interrupts Flags. This LCD Status (also known as LCD STAT or just STAT) stores the current mode of the Video chip, and when it should cause interrupts. The Interrupt flags one is the register that stores the currently requested interrupts. If, say, the timer wants to request an interrupt, that register is the place to go. Now, when you change mode, you have to modify the first 2 bits of LCD STAT (should store 0-3 depending on the mode), and depending on other bits on the register, you may also have to request an interrupt. This whole process was a bit convoluted on Rusty-Boy, so I decided to get some fresh air and try to clean it up, maybe even fix something in the process, right? Yeah, no. ![Broken Bomberman](https://dev-to-uploads.s3.amazonaws.com/i/k4su4b9rm9mq9ss7kh7h.png)<figcaption>The cleanups broke everything</figcaption> Games ranged from not running, to showing broken graphics, and even executing invalid opcodes! How?! I did have some typos on the initial re-implementation of some things, but even after they were fixed games were still broken. I took the easy way out. I ran `git reset --hard` and kicked the cleanup to some random point in the future. I didn't want to deal with it for the time being. So I moved on to something else, which brings us to our next topic of the day. ##### ___The Input Hack___ I mentioned on the previous post that I had an input problem. Basically, button presses are sent from the UI thread to the emulation thread for the CPU to handle. The issue is that both threads run at very different speeds, so inputs tend to get lost in translation. If your ROM only checks for button presses (like an input test for example), it tends to register an input press if you try hard enough. But games do other things, not just constantly check for inputs, so you need to *really* try to hopefully get one press registered. It's a really ugly situation. Tl;Dr: You press a button, and RNGesus decides whether or not it'll get through. As you can probably imagine, this makes testing a bit difficult, since I can't get past menus in most cases. So I decided to implement a workaround (or hack) after I come up with a better fix (famous last words). This hack basically sends 4 input events per button press. Why 4 specifically? No idea, 4 seemed like a nice number in my mind. So with this hack in place, you can actually start playing stuff. Mostly Tetris, since it's the most reliable game so far. rex-run also works pretty nicely, it's a port of the dino game from Chrome, you know the one you get when you are offline? That one. It's a fun game that I have way more playtime than I'd like to admit. ![rex-run](https://dev-to-uploads.s3.amazonaws.com/i/vyw4s4235rz03hx8uefk.png)<figcaption>It's a bit hard to play at super speed</figcaption> Let's continue. #### Thursday This was "Pokemon Red Debugging" day, which of course turned into "Hit your head against a Wall" day. Nothing is never simple here. ##### ___Investigating Pokemon Red___ Ever since I moved away from SDL for rendering and into OpenGL+Dear Imgui, Pokemon Red just loops forever after the bootrom. My first instinct was trying to look into the commit to see if anything seemed bad, but this didn't go quite as planned. The commit is [kinda big](https://github.com/RainbowCookie32/rusty-boi/commit/87d2d7669b1d89a4d1852e805f09ad2a286e6aab), which made searching for differences a bit hard. I tried, but I couldn't spot any major differences that'd cause the game to get stuck like that. *What was going on?*. Well, time to get BGB running again then. After stepping through instructions for a while, I got to a point where Rusty-Boy would acknowledge an interrupt, but never come back from it. A Vblank interrupt to be more precise. This didn't really answer many questions, but rather brought a few more to the table - it's not the first time it calls a vblank interrupt, why does it get stuck on that one specifically? I poked around some things a bit more, but couldn't find a reason so I just wrapped the day there and went to bed. I don't really have a solid theory for that one, there might be some timing-related issues with interrupts, but I haven't stepped into the vblank routine yet. I'll probably take a look at a disassembly of the game first to have a better idea of what I'm looking at. #### Friday This day started a bit rough with me trying, again, to clean up mode switching and interrupts. As expected, it didn't go any better than the previous attempt, and ended up with the same solution. `git reset --hard`. Maybe next week. So I moved on to something that I had some confidence on, Sprites. ##### ___Sprites___ Sprites are pretty simple overall, they are basically tiles with flags. Each Sprite has an entry on a special region in memory, the OAM (Object Attribute Memory). The entries are made from 4 bytes: * Y position * X position * Tile ID * Flags (Priority, Flip on X or Y, palette to use) There can only be 40 sprites on memory at the same time. With the tile cache in place, the implementation was pretty painless. I added a Sprite struct that contained the screen coordinates, color data, and the flip flags for each sprite. And I cached them, same idea as the tile cache - have a hash of the memory region, regenerate the cache when the hash changes. Easy, right? Yeah, but not typo-proof. ![First Sprite](https://dev-to-uploads.s3.amazonaws.com/i/t87n3mhdl0o8smjldgpn.png)<figcaption>The first Sprite that got rendered</figcaption> In case you missed it, it's a zero on the top left corner of the screen. Just that. It didn't take me very long to notice what was wrong. I copy-pasted the code for hashing the tile banks and used it for sprites. But I never changed the memory region to hash! So if the tile cache wasn't invalidated, the sprites wouldn't either. Fixed that and... ![More Tetris Sprites](https://dev-to-uploads.s3.amazonaws.com/i/jyyrwhwp9sbgunlurv4m.png)<figcaption>It's a little confused, but it's got the spirit.</figcaption> Wasn't looking too great, but it was getting there. This one took a bit longer to figure out. The culprit for this one was the scaling. I was multiplying the *size* of the sprites by the scaling factor, but not the position. The X and Y coordinates were assuming, of course, a 160x144 screen - the Gameboy's screen. But after applying scaling, that's not the resolution we have. So after taking that into account, we have perfectly working sprites. Mostly. ![Evolution of Sprites](https://dev-to-uploads.s3.amazonaws.com/i/fw0g7a5qbq80gltvgupb.gif)<figcaption>Evolution of Sprites in Tetris</figcaption> Looking pretty good so far, but I'm still missing some things. Most notably 8x16 sprites, priority, and transparency. 8x16 sprites are probably going to happen soon, the others I have to read up a bit on. ##### ___The Rogue Window - Part 2___ A few hours after fixing the sprite's position, I got an idea, a spark of hope: *what if all this time I just had to scale the window coordinates, just like the sprites?* Just as I finished that thought my toaster yeeted my toasts, really dramatic. So I rushed to my PC to test it, scared that the moment of enlightenment would go away, and indeed, that was all that was needed. The window was no longer over things it shouldn't. ![Fixedman](https://dev-to-uploads.s3.amazonaws.com/i/ef0cxm3nwlkfdeflbpzi.png)<figcaption>Bomberman's intro was finally fixed!</figcaption> With the last window-related issue, I can probably say with a certain degree of certainty that the window is currently rendering perfectly. --- So, you are all caught up now. This is where Rusty-Boy is right now. This was a bit of a frustrating week, with a lot of things not really going anywhere, but Sprites and fixing the window saved it really. I'll probably try to figure out what's up with Dr. Mario's loop and Pokemon Red's interrupt. Hopefully it gets somewhere. See ya in a week! PS: I never linked the emu itself last week, so you can go check it out [here](https://github.com/RainbowCookie32/rusty-boi).
rainbowcookie32
359,418
Another newsletter for User Interface Frontend Developers
The UI Development Mentoring Newsletter contains a list of exciting and useful articles, tutorials, t...
0
2020-06-20T10:43:46
https://dev.to/starbist/another-newsletter-for-user-interface-frontend-developers-3oe4
news, uiweekly, css, career
The UI Development Mentoring Newsletter contains a list of exciting and useful articles, tutorials, tools, apps and everything else related to *user interface frontend development* and *freelancing* and it is sent to your inbox once a week. Subscribe here: https://mentor.silvestar.codes/reads#newsletter. 🙏
starbist
359,648
SVG Name Animation
Check out the animation which i've created by using SVG
0
2020-06-23T16:56:18
https://dev.to/caseyanmol/svg-name-animation-25o1
codepenanimation, svganimation, svg
--- title: SVG Name Animation published: true tags: codepenanimation , svganimation , svg description: Check out the animation which i've created by using SVG --- > Check out the cool animation which i've created by using SVG {% codepen https://codepen.io/caseyanmol/pen/xxZgaZB %}
caseyanmol
359,650
Virtual Environment for Python
Below you learn why need a Python virtual environment and how are you can use it with Python 3 (Why P...
0
2020-06-20T13:01:06
https://dev.to/importostar/virtual-environment-for-python-dn1
python
Below you learn why need a **Python virtual environment** and how are you can use it with Python 3 (<a href="https://python-commandments.org/python-2-vs-3/">Why Python 3?</a>). You should know <a href="https://pythonprogramminglanguage.com/how-to-run/">how to run Python</a> before setting up a virtual environment. If you use PyCharm, it sets up a virtualenv automatically. ### What is Virtual Environment? **Virtual environments** are particularly helpful if the program requires an individual environment, with a unique python version and specific module versions. It prevents package conflicts. You can use **virtualenv** to create your isolated environment. ### Why do you need a virtual environment? The **virtual environment** is a way to keep the python configuration isolated from other projects. One user has multiple virtual environments on a single computer, one for eahch project. Different libraries can be incorporated in each virtual environment. <img src="https://pythonbasics.org/wp-content/uploads/2018/03/virtualenv-modules.png" alt="virtual environment"> ### How to create a virtual environment using Python3? **Step1:** Install Virtual Environment pip3 install virtualenv Collecting virtualenv Downloading virtualenv-15.1.0-py2.py3-none-any.whl (1.8MB) 100% |████████████████████████████████| 1.8MB 367kB/s Installing collected packages: virtualenv Successfully installed virtualenv-15.1.0 **Step2:** In python 3, you can use this command **'python3 –m venv /path/to/create/the/virtual/env'**. -bash-4.2$ python3 -m venv test_venv -bash-4.2$ ls test_venv -bash-4.2$ **Step3:** Activate virtual environment -bash-4.2$ source test_venv/bin/activate (test_venv) -bash-4.2$ **Step4:** Install the required libraries, using <a href="https://pythonbasics.org/how-to-use-pip-and-pypi/">pip</a> For the example below,we have used 'flask' library. Flask lets you build web apps, you can <a href="https://pythonspot.com/flask-web-app-with-python/">make all kinds of things</a> or even <a href="https://gitpress.io/u/1282/flask_matplotlib">plot</a> (test_venv) -bash-4.2$ pip3 install flask Collecting flask Downloading https://files.pythonhosted.org/packages/9b/93/628509b8d5dc749656a9641f4caf13540e2cdec85276964ff8f43bbb1d3b/Flask-1.1.1-py2.py3-none-any.whl (94kB) 100% |████████████████████████████████| 102kB 3.8MB/s Collecting Jinja2>=2.10.1 (from flask) Using cached https://files.pythonhosted.org/packages/1d/e7/fd8b501e7a6dfe492a433deb7b9d833d39ca74916fa8bc63dd1a4947a671/Jinja2-2.10.1-py2.py3-none-any.whl Collecting click>=5.1 (from flask) Using cached https://files.pythonhosted.org/packages/fa/37/45185cb5abbc30d7257104c434fe0b07e5a195a6847506c074527aa599ec/Click-7.0-py2.py3-none-any.whl Collecting itsdangerous>=0.24 (from flask) Using cached https://files.pythonhosted.org/packages/76/ae/44b03b253d6fade317f32c24d100b3b35c2239807046a4c953c7b89fa49e/itsdangerous-1.1.0-py2.py3-none-any.whl Collecting Werkzeug>=0.15 (from flask) Using cached https://files.pythonhosted.org/packages/ce/42/3aeda98f96e85fd26180534d36570e4d18108d62ae36f87694b476b83d6f/Werkzeug-0.16.0-py2.py3-none-any.whl Collecting MarkupSafe>=0.23 (from Jinja2>=2.10.1->flask) Using cached https://files.pythonhosted.org/packages/b2/5f/23e0023be6bb885d00ffbefad2942bc51a620328ee910f64abe5a8d18dd1/MarkupSafe-1.1.1-cp36-cp36m-manylinux1_x86_64.whl Installing collected packages: MarkupSafe, Jinja2, click, itsdangerous, Werkzeug, flask Successfully installed Jinja2-2.10.1 MarkupSafe-1.1.1 Werkzeug-0.16.0 click-7.0 flask-1.1.1 itsdangerous-1.1.0 (test_venv) -bash-4.2$ More reading: * <a href="https://gumroad.com/l/dcsp">Learn Python programming</a> * <a href="https://virtualenv.pypa.io/en/stable/">More virtualenv</a>
importostar
359,747
Bad Security habits to lose
Security is such a vast topic. There are a lot of traps and false beliefs. Since the coronavirus...
21,638
2020-06-20T15:48:50
https://dev.to/spo0q/bad-security-habits-to-lose-2l7i
security
Security is such a vast topic. There are a lot of traps and false beliefs. Since the coronavirus crisis, hacking has been increasing, so you got to be prepared. The good news is that you can significantly mitigate major flaws with simple good practices. Hackers are looking for vulnerabilities. It's what they do. You'd be surprised how often the weakest link is the human factor. ## Fewer permissions, fewer problems We are developers, and we are human, we do stupid things, especially at the beginning of our career. Every year, I hear that sad story in which a rookie pushes bad commits exposing credentials in one of his public GitHub repositories. Not surprising. If forks are enabled, if you don't handle rights and permissions properly, it will happen sooner or later. An excellent practice is to only give the necessary privileges to developers and coworkers. I don't know you, but as a developer, I prefer not having access to things I don't need. This way, I got one less (potential) problem 😘. ## Use password managers and VPN Never store passwords in your browsers. Instead, use a password manager. As a developer, you have access to confidential information, and these credentials might be critical for business. You have to protect access. Using a password manager is more secure; it's faster, and you get extra cool features such as auto-filling passwords or password generators. As a developer, you may work remotely, but not necessarily at home. You may push some code just before your flight, and sometimes you might have to use public networks. If your employers do not provide any VPN connection, they're probably doing it wrong. Please consider asking them, and maybe they have not heard about it yet. ## Don't mess with your machine It is your responsibility to protect your machine. Don't install any cracked software. Don't do illegal stuff, including peer to peer downloads for games and movies. Of course, don't watch porn. Don't do hacking kinds of stuff, or at least use another machine, buy some Raspberry Pi, it's pretty cheap, install Kai Linux or whatever dedicated operating system. Unfortunately, the danger is sometimes less visible. Don't install whatever fancy GitHub repository unless it's a trusted source. It's not rare to get unsecured docker configurations, for example. Besides, be careful with permissions when installing applications. [Review your applications](https://github.com/settings/installations) regularly. ## Be careful with social networks If I am a hacker and know you work as a developer for a company in my line of fire, it is easier for me (and probably more efficient) to hack you. If you tweet all day long, I can get a lot of information about you and your habits with the Twitter API, and I can even become your "online friend." Knowing that you probably connect to a lot of stuff, including websites, applications, messengers, and internal networks, I can use your privileges to perform harmful actions. ## Keep your tools up-to-date You need to get the latest versions of all the software you use in your work. It includes operating systems, software, libraries, frameworks, etc. It takes time, and it can be a massive pain because of the incompatibilities, but necessary. ## Security in code Of course, you have to know security flaws such as XSS, CSRF, SQL injections, insecure references, unvalidated inputs, etc. There are A LOT of free ebooks and fantastic resources for that. However, it isn't effortless to learn those concepts. It gets worse when blog posts are not enough accurate or misleading, especially for that topic. Everybody says, "make yourself aware of those vulnerabilities," but it is not that easy. You could read the entire web without understanding the key-concepts. IMHO, the best pieces of advice I can give you are the following: * use security guidelines in your team (I love todo lists <3) * do code reviews Automatic tools are powerful, but you get a lot of false-positive results. Nothing compares to experience and pair programming. ## Wrap up I hope these security thoughts are useful, don't trust user inputs, and don't trust yourself cause you might be the breach. Be humble. Even with those good practices, you might get hacked. It's not bulletproof, nothing is, but it drastically reduces risks.
spo0q
359,794
Create a professional resume in a few minutes (for free).
Having a professional resume is the most important thing when you apply for a job, which depicts your...
0
2020-06-20T17:40:49
https://dev.to/rakshakannu/create-a-professional-resume-in-a-few-minutes-for-free-28ln
career, googlecloud
Having a professional resume is the most important thing when you apply for a job, which depicts your skills and experiences and could be the deciding factor for getting you shortlisted for the face to face interview out of all the applicants. 😟 Hence, if you don’t have your resume yet, let's start making it. 🥳 Fret not, you won't be spending a single penny to get those cool looking templates. 🤗 The easiest way to create a professional resume is by using **Google docs**. Yes! you read that right! 🤯 ## Step 1: Login to your google account and click on google docs. 👩🏻‍💻 ![Alt Text](https://dev-to-uploads.s3.amazonaws.com/i/fu0bcggwl8gcskmi53ac.png) ## Step 2: It will tell you to select the type of google doc. Go to the CV section and check out the templates available for creating a resume. ![Alt Text](https://dev-to-uploads.s3.amazonaws.com/i/qwoywwqm9wct7gjqb2gc.png) ## Step 3: Chose any one of those templates availabe. If you are confused about which one to chose, select Serif one. It looks highly professional and I prefer it too! 👌 ![Alt Text](https://dev-to-uploads.s3.amazonaws.com/i/jmuumre7ph6aqwwyratb.png) ## Step 4: Now the last step, Edit the template with all your details, And tadaaaa! your professional resume is ready! 🎉 ![Alt Text](https://dev-to-uploads.s3.amazonaws.com/i/klwymuqi4nyv74zgs1n0.png) ## Bonus tip: Save this resume as a google doc in your drive, so that it will be easier to update it now and then, and you can obviously download the pdf version of it whenever you want! 💎 Thanks for reading this, and I hope you liked it. 💖
rakshakannu
359,878
Métricas para seu time
Nesse artigo vou apresentar algumas métricas (não todas porque existem muitas), mas talvez as mais co...
0
2020-06-20T21:24:52
https://dev.to/womakerscode/metricas-para-seu-time-1e04
Nesse artigo vou apresentar algumas métricas (não todas porque existem muitas), mas talvez as mais conhecidas. Todas as empresas possuem fluxos de trabalho e devem aprender a administrá-los para direcionar melhor suas ações. As métricas não têm intenção de julgar as pessoas individualmente, mas sim, melhorar o fluxo. **“Gerencie o trabalho, não as pessoas.”** ###**Lead Time** O Lead Time consiste em medir o tempo entre o momento em que você se comprometeu com o cliente a fazer determinado trabalho até o momento da entrega do incremento. ####Como começar a medir? Comece registrando a data de quando houve o compromisso com o cliente, chamamos de Ponto de Comprometimento (Commitment Point). Quando você entregar o incremento marque a data de entrega e chamaremos de Ponto de Entrega (Delivery Point). Lead Time = Delivery Point – Commitment Point ####Qual é a importância dessa métrica? Você pode ter vários insights com esse indicador e de como melhorar o dia a dia. Podemos verificar através do gráfico CFD (Gráfico de Fluxo Acumulativo) se o item ficou, por exemplo, parado na fase de testes por muito tempo e ter ações para que não volte ocorrer esse problema. ###**Cycle Time** O tempo de ciclo se inicia quando uma nova tarefa entra no estágio de “em progresso” e alguém está, de fato, trabalho nela. ####Como começar a medir? Tempo de Ciclo = Trabalho em Progresso / Taxa de Transferência ###**Throughput** Vazão (Throughput) é a quantidade de itens que o time entregou em um período. ####Como começar a medir? Primeiro defina o período: semana, quinzena, sprint, mês, trimestre, semestre. Após definir o período, verifique quantos itens chegaram até o Delivery Point. ####Qual é a importância dessa métrica? Este indicador vai ajuda a dar uma visão dos itens finalizados e seria uma boa forma de aumentar este indicador se trabalhar com itens pequenos. ###**Aging** Envelhecimento (Aging) é uma métrica que observa a idade dos itens. Essa métrica consiste em saber quanto tempo um item ficou esperando antes de começar a trabalhar. ####Como começar a medir? Meça o tempo desde o momento em que o item foi solicitado até o momento onde o time começou a trabalhar. ####Qual é a importância dessa métrica? Um time ágil está trabalhando em itens que entregam valor, se existe um item velho será que ainda é relevante para o cliente? será que não estamos "perdendo tempo" ? Para finalizar lembre-se antes de sair implantando várias métricas/indicadores, escolha um e trabalhe fortemente em cima dele e melhor do que ter apenas números é ter ações para melhorar continuamente ;)
abquintino
361,781
Using MQTT on Angular Apps
When you’re building a website that needs to be updated in real-time, your first thought is probably...
0
2020-07-06T08:06:34
https://bugfender.com/blog/using-mqtt-on-angular-apps/
angular, javascript, mqtt
--- title: Using MQTT on Angular Apps published: true date: 06/07/2020 08:00 UTC tags: angular,javascript,js,mqtt canonical_url: https://bugfender.com/blog/using-mqtt-on-angular-apps/ --- When you’re building a website that needs to be updated in real-time, your first thought is probably to add WebSockets to your application. In this article, you will learn how to add MQTT to your angular web application. However Websockets is a low-level protocol and to use it, you’ll need to add another layer on top to manage the information you want to get. This is where MQTT protocol is handy, as it’s a higher-level protocol that simplifies working with data streams. ## What is MQTT? MQTT means Message Queuing Telemetry Transport. It’s a connectivity protocol used in the IoT world to communicate between machines, but has a whole load of other applications too. You can read more about [MQTT on Wikipedia](https://en.wikipedia.org/wiki/MQTT) and also on the [official MQTT site](http://mqtt.org/). Currently, MQTT protocol is used in a lot of IoT platforms to communicate between IoT devices.Currently, MQTT protocol is used in a lot of IoT devices. ## Architecture An MQTT protocol ecosystem has the following components: - **Publisher:** Responsible for publishing MQTT messages to the system. Usually an IoT device. - **MQTT Broker:** The server that gets the published data and sends it to the corresponding subscribers. - **Subscriber:** The device that is listening for incoming data from devices. ![MQTT Architecture](https://bugfender.com/wp-content/uploads/2020/06/MQTT_1.png) ### Publish/Subscribe Model As we have seen in the architecture overview, MQTT uses the publish/subscribe methodology. So they don’t know each other, they just need to agree on how data is going to be sent. It also allows the use of multiple publishers or subscribers, so various clients can create an MQTT connection and subscribe to data from a single device. ### MQTT Topics An MQTT Topic is the concept used to communicate between publishers and subscribers. When a subscriber wants to get data from a device, it subscribes to a specific topic, which will be where the device publishes its data. A Topic is a hierarchical UTF-8 string, and here you have an example: **/device/garden\_sensor/temperature** ## MQTT Over Websockets In the introduction, we said that MQTT is a high-level protocol and the great thing is that it can use different protocols to get its job done. It can adopt its own MQTT protocol, but this protocol is not supported by web browsers; however MQTT can also be used over WebSockets connection, so we can easily use MQTT on any web browser that supports WebSockets. ## Which MQTT Broker Should I Use? There are various MQTT brokers you can use for your project. On one hand you can use cloud/hosted solutions; alternatively you can choose an on-premise option, either by installing on your own servers or using through Docker. You can see a comprehensive list of the existing brokers in [this Github repo](https://github.com/mqtt/mqtt.github.io/wiki/brokers). In our case we have used the open source [Eclipse Mosquitto](https://mosquitto.org/) with great success. ## MQTT Client on Angular Apps Now let’s see how can we use MQTT protocol on an Angular app. The easiest way to do it is to use some of the existing Javascript libraries. In this case, we will use the [ngx-mqtt library](https://sclausen.github.io/ngx-mqtt/). This offers support for Javascript/Typescript observables, so it’s really helpful when writing an MQTT client on an Angular app. ### Installing ngx-mqtt You have all the information on the library site, but it’s as easy as installing the npm packages. ``` npm install ngx-mqtt --save ``` ### Configuration Once the library is installed, you need to initialize it. You can follow the instructions on the ngx-mqtt site, but you will probably have multiple environments in your Angular code, so you will need a different configuration for each environment. So let’s create an **mqtt** section in our environment files. Here’s an example: `src/environments/environment.prod.ts` ``` export const environment = { production: true, hmr: false, http: { apiUrl: '<https://api.myweb.com>', }, mqtt: { server: 'mqtt.myweb.com', protocol: "wss", port: 1883 } }; ``` You can edit all other environment configuration files to set the right values for each one. Now we need to initialize the MQTT library, and for this we recommend changing to `app.module.ts`: ``` ... import { IMqttServiceOptions, MqttModule } from "ngx-mqtt"; import { environment as env } from '../environments/environment'; const MQTT_SERVICE_OPTIONS: IMqttServiceOptions = { hostname: env.mqtt.server, port: env.mqtt.port, protocol: (env.mqtt.protocol === "wss") ? "wss" : "ws", path: '', }; @NgModule({ declarations: [AppComponent], imports: [ ... MqttModule.forRoot(MQTT_SERVICE_OPTIONS), ], ... }) export class AppModule { } ``` ### Creating Services With this you can now start using MQTT in your app, but to achieve a more structured code we recommend you create a service class for each **Topic** you are going to use. Let’s create a service that subscribes to a topic called **events** , where the Topic name is similar to `/events/deviceid`. For this we create the Typescript file `src/app/services/event.mqtt.service.ts`with the following code: ``` import { Injectable } from '@angular/core'; import { IMqttMessage, MqttService } from "ngx-mqtt"; import { Observable } from "rxjs"; @Injectable() export class EventMqttService { private endpoint: string; constructor( private _mqttService: MqttService, ) { this.endpoint = 'events'; } topic(deviceId: string): Observable<IMqttMessage> { let topicName = `/${this.endpoint}/${deviceId}`; return this._mqttService.observe(topicName); } } ``` Using this service class, we have all the MQTT-related code in a single file and now we only need to use this service when it’s needed. Remember to add all the services files to the **providers** section of your **AppModule,** otherwise you won’t be able to use them. ### Using the MQTT Services Now it’s time to use the MQTT services we have created. So, for example, let’s create an **EventStream** component that prints all the events that a device generates. The code of this file will be similar to: ``` import { Component, OnInit } from '@angular/core'; import { EventDataModel } from 'app/models/event.model'; import { Subscription } from 'rxjs'; import { EventMqttService } from 'app/services/api/event.mqtt.service'; import { IMqttMessage } from "ngx-mqtt"; @Component({ selector: 'event-stream', templateUrl: './event-stream.component.html', styleUrls: ['./event-stream.component.scss'], }) export class EventStreamComponent implements OnInit { events: any[]; private deviceId: string; subscription: Subscription; constructor( private readonly eventMqtt: EventMqttService, ) { } ngOnInit() { this.subscribeToTopic(); } ngOnDestroy(): void { if (this.subscription) { this.subscription.unsubscribe(); } } private subscribeToTopic() { this.subscription = this.eventMqtt.topic(this.deviceId) .subscribe((data: IMqttMessage) => { let item = JSON.parse(data.payload.toString()); this.events.push(item); }); } } ``` It’s important to remember that we need to **unsubscribe** from the subscription when we destroy the component. Now, we should have an Angular app that can subscribe to MQTT topics and show the user the information every time a device generates an MQTT message. ## Debugging MQTT Angular Apps When working with Angular and MQTT, there are more moving parts than in common Angular apps where you have your Javascript frontend and a RESTFul API to consume (usually also a Javascript backend). We can list a few extra things you need to take care of: - **Websockets** : they are not easy to debug with current browsers, especially when using MQTT as data is sent in binary format. - **MQTT Broker:** this is a new component you need to take care of and make sure you have the right configuration for each environment. - **Devices:** you might be able to test the app on some devices, but once the app is live in production, the users might have some devices you didn’t know about, or a firmware update of a device can break your code. ![Websockets Google Chrome debugging](https://bugfender.com/wp-content/uploads/2020/06/Annotation_2020-05-27_114446.png) _Google Chrome Websockets debugging. As you can see, information is hard to read because it’s shown in binary format._ This is why Bugfender can be really helpful in debugging MQTT Angular apps. You’ll probably experience some bugs when developing the app and trying to use it in the production environment, and probably also when the app is used in the real world. If you use Bugfender, you’ll be able to get all the Javascript exceptions that occur among your final users and if a device breaks your code, you’ll also be able to inspect the MQTT data that individual devices are sending. Moreover, Bugfender sends all console logs to our serves so you can see everything that’s happening in your Javasacript app remotely. If you want to know how to install Bugfender in your Angular app, you can check the [BugfenderSDK Angular App Sample](https://github.com/bugfender/BugfenderSDK-Angular-Sample). Install Bugfender: ``` npm i @bugfender/sdk ``` Initiate the library in your **AppModule** : ``` Bugfender.init({ appKey: '<YOUR_APP_KEY_HERE>', version: '<version>', build: '<build>', }); ``` If you don’t have an App Key you can get a free one just [signing up in Bugfender](https://dashboard.bugfender.com/signup). We recommend you install a [custom error handler](https://github.com/bugfender/BugfenderSDK-Angular-Sample/blob/master/src/app/app.error-handler.ts) so if there’s any Javascript exception, this is sent to Bugfender. Now, let’s update our component. We send the MQTT messages we get to Bugfender, so later we can check whether there’s any problem with the information sent by a particular device. ``` ... private subscribeToTopics() { this.subscription = this.eventMqtt.topic(this.deviceId) .subscribe((data: IMqttMessage) => { let item = JSON.parse(data.payload.toString()); Bugfender.sendLog({tag: 'MQTT', text: "Got data from device " + this.deviceId}) Bugfender.log(item); this.events.push(item); }); } ``` We also recommend that you add a log when a subscription to a topic is created, so you will know which device is causing problems. ![Bugfender remote console log](https://bugfender.com/wp-content/uploads/2020/06/Annotation_2020-05-27_120711.png) _Bugender Log Viewer with MQTT debugging information_ As you can see in the screenshot, we can easily identify the sensor that is sending the data and the data that is being sent. The good thing about using Bugfender is that you can enable or disable specific devices, so you can enable a certain device when you know there’s a problem and won’t waste logs with useless information. The Bugfender JS SDK is [our new SDK to complement the native iOS and Android SDK](https://dev.to/bugfenderapp/introducing-the-bugfender-web-sdk-3ccn-temp-slug-8174974). We are continuously creating new tutorials and content to help the JS developer community. If you want to be notified when new JS tutorials are available you can join our quarterly newsletter in the box below.
bugfenderapp
375,159
How to use git stash effectively
This post was originally posted in the newsletter GitBetter. If you are interested in lev...
0
2020-07-06T07:06:20
https://gitbetter.substack.com/p/useful-tricks-of-git-stash
git, beginners, programming, tutorial
--- title: How to use git stash effectively published: true tags: git, beginners, programming, tutorial canonical_url: https://gitbetter.substack.com/p/useful-tricks-of-git-stash --- ![](https://cdn.substack.com/image/fetch/w_1456,c_limit,f_auto,q_auto:good,fl_progressive:steep/https%3A%2F%2Fbucketeer-e05bbc84-baa3-437e-9518-adb32be77984.s3.amazonaws.com%2Fpublic%2Fimages%2F325441de-b490-41dc-91c0-7a0679a92b77_600x700.png) > #### This post was originally posted in the newsletter [GitBetter](https://gitbetter.substack.com/). If you are interested in leveling up your game in Git, you can subscribe to it. If you are using Git for a while, you might have come across git stash. Git stash helps you to temporarily save the changes in the working directory so that you will get a clean directory. Then you can apply those changes later in your git workflow. Lets’s see an example ![](https://cdn.substack.com/image/fetch/w_1456,c_limit,f_auto,q_auto:good,fl_progressive:steep/https%3A%2F%2Fbucketeer-e05bbc84-baa3-437e-9518-adb32be77984.s3.amazonaws.com%2Fpublic%2Fimages%2F43f0456d-c2b6-4a44-85b7-9168baecb5a0_560x356.png) You can see that there are some changes in the working directory. You can use git stash to save all the changes so that the working directory will be clean. ``` git stash ``` ![](https://cdn.substack.com/image/fetch/w_1456,c_limit,f_auto,q_auto:good,fl_progressive:steep/https%3A%2F%2Fbucketeer-e05bbc84-baa3-437e-9518-adb32be77984.s3.amazonaws.com%2Fpublic%2Fimages%2F79e482f2-5411-437a-b349-b04b0f19540c_674x283.png) After stashing, you can see that the changes in the tracked files are gone in the working directory. And also note that the untracked files are still present. Those saved changes can be accessed and used in the future or else kept aside forever. By default, stash won’t save the untracked files. But if you still need to stash the untracked files you can use ``` git stash -u ``` #### List all git stashes You can use git stash multiple times across the git directory. To view all your git stashes ``` git stash list ``` ![](https://cdn.substack.com/image/fetch/w_1456,c_limit,f_auto,q_auto:good,fl_progressive:steep/https%3A%2F%2Fbucketeer-e05bbc84-baa3-437e-9518-adb32be77984.s3.amazonaws.com%2Fpublic%2Fimages%2Fa98d10b2-3251-4d21-a660-af813a124df2_517x133.png) In the above image, you can see the list of git stashes. Each stash will have a name, the working directory, and the HEAD commit. Git stash name and the branch are very important. This helps you to identify the stash easily. Remember that stash works like stacks. The most recent stash will be at the top. #### View stash changes using show It will be useful to view the changes which have been stashed. ``` git stash show ``` The above command will show the changes in the latest stash (i.e) stash@{0} ![](https://cdn.substack.com/image/fetch/w_1456,c_limit,f_auto,q_auto:good,fl_progressive:steep/https%3A%2F%2Fbucketeer-e05bbc84-baa3-437e-9518-adb32be77984.s3.amazonaws.com%2Fpublic%2Fimages%2F27285f69-2478-4750-a9eb-34952fc77bbf_402x108.png) To view the changes of any particular stash ``` git stash show stash@{2} ``` To view the diff changes of stash, you can use ``` git stash show -p git stash show stash@{10} -p ``` ![](https://cdn.substack.com/image/fetch/w_1456,c_limit,f_auto,q_auto:good,fl_progressive:steep/https%3A%2F%2Fbucketeer-e05bbc84-baa3-437e-9518-adb32be77984.s3.amazonaws.com%2Fpublic%2Fimages%2F5dfba4df-1937-44bf-8c61-d73b27d1bfac_392x161.png) #### Applying stashed changes in the working directory Now you know how to stash the changes let’s see how to apply those changes in the working directory. ``` git stash apply ``` The above command will take the latest stash (i.e) stash@{0} an apply it to the working directory. ![](https://cdn.substack.com/image/fetch/w_1456,c_limit,f_auto,q_auto:good,fl_progressive:steep/https%3A%2F%2Fbucketeer-e05bbc84-baa3-437e-9518-adb32be77984.s3.amazonaws.com%2Fpublic%2Fimages%2F8d65a1d0-988a-4746-b47c-2418d181ed48_657x349.png) In the above image, you can see that changes in the latest stash are applied. To apply the particular stash, you can use ``` git stash apply stash@{5} ``` ##### Using pop There is also another option to applying the stash in the working directory. ``` git stash pop ``` This command will apply the changes of the latest stash and will also delete the stash from the stash list. Use this command when you don’t need the stash anymore after applying the stash. Use **apply** when you need to apply the stash and still, you don’t want to delete the stash from the list. #### Delete a stash ``` git stash drop ``` This will delete the latest stash. ``` git stash drop stash@{10} ``` This will drop the particular stash. #### Create a branch from git stash ``` git stash branch <branch_name> stash@{5} ``` This command will create a new branch with the specified stash name. And this will delete the stash from the list like **pop.** Thank you for reading :) If you got any new tricks you share, you can share it in the comments :) :) > #### This post was originally posted in the newsletter [GitBetter](https://gitbetter.substack.com/). If you are interested in leveling up your game in Git, you can subscribe to it.
srebalaji
376,390
async/await: under the hood
I'm really interested in concurrency strategies in programming languages, and because there's a lot o...
0
2020-06-30T23:15:26
https://arschles.com/blog/async-await/
webdev, javascript, serverless
I'm really interested in concurrency strategies in programming languages, and because there's a lot of written research out there on the topic, you can find lots of strategies out there. When you look at some of the more modern stuff, you'll find a [lot](https://www.microsoft.com/en-us/research/wp-content/uploads/2007/01/The-Joins-Concurrency-Library.pdf) [of](https://concurnas.com/) [literature](https://rust-lang.github.io/async-book/03_async_await/01_chapter.html) on just about the same pattern: `async`/`await`. `async`/`await` is picking up steam in languages because it makes concurrency _really_ easy to see and deal with. Let's look at how it works and why it helps, using Javascript to illustrate the concepts. >I'm a Javascript dabbler at best, but it's a great language to illustrate these concepts with. Don't go too hard on my JS code below 😅 # What It's About 🤔 `async`/`await` is about writing concurrent code easily, but more importantly, it's about writing the code so it's easy to **read**. ## Solving Concurrency Three Ways 🕒 This pattern relies on a feature called Promises in Javascript, so we're gonna build up from basics to Promises in JS, and cap it off with integrating `async`/`await` into Promises. >Promises are called Futures in many other languages/frameworks. Some use both terms! It can be confusing, but the concept is the same. We'll go into details later in this post. ### Callbacks 😭 You've probably heard about callbacks in Javascript. If you haven't, they're a programming pattern that lets you schedule work to be done in the future, after something else finishes. Callbacks are also the foundation of what we're talking about here. >The core problem we're solving in this entire article is how to run code after some concurrent work is being done. The syntax of callbacks is basically passing a function into a function: ```javascript function doStuff(callback) { // do something // now it's done, call the callback callback(someStuff) } doStuff(function(result) { // when doStuff is done doing its thing, it'll pass its result // to this function. // // we don't know when that'll be, just that this function will run. // // That means that the rest of our ENTIRE PROGRAM needs to go in here // (most of the time) // // Barf, amirite? console.log("done with doStuff"); }); // Wait, though... if you put something here ... it'll run right away. It won't wait for doStuff to finish ``` That last comment in the code is the confusing part. In practice, most apps don't want to continue execution. They want to wait. Callbacks make that difficult to achieve, confusing, and [exhausting to write](http://callbackhell.com/) and read 😞. ### Promises 🙌 I'll see your callbacks and raise you a `Promise`! No really, Promises are dressed up callbacks that make things easier to deal with. But you still pass functions to functions and it's still a bit harder than it has to be. ```javascript function returnAPromiseYall() { // do some stuff! return somePromise; } // let's call it and get our promise let myProm = returnAPromiseYall(); // now we have to do some stuff after the promise is ready myProm.then(function(result) { // the result is the variable in the promise that we're waiting for, // just like in callback world return anotherPromise; }).then(function(newResult) { // We can chain these "then" calls together to build a pipeline of // code. So it's a little easier to read, but still. // Passing functions to functions and remembering to write your code inside // these "then" calls is sorta tiring doMoreStuff(newResult); }); ``` We got a few small wins: - No more intimidating _nested_ callbacks - This `then` function implies a _pipeline_ of code. Syntactically and conceptually, that's easier to deal with But we still have a few sticky problems: - You have to remember to put the rest of your program into a `then` - You're still passing functions to functions. It still gets tiring to read and write that ### async/await 🥇 Alrighty, we're here folks! The `Promise`d land 🎉🥳🍤. We can get rid of passing functions to functions, `then`, and all that forgetting to put the rest of your program into the `then`. All with this 🔥 pattern. Check it: ```javascript async function doStuff() { // just like the last two examples, return a promise return myPromise; } // now, behold! we can call it with await let theResult = await doStuff(); // IN A WORLD, WHERE THERE ARE NO PROMISES ... // ONLY GUARANTEES // // In other words, the value is ready right here! console.log(`the result is ready: ${theResult}`); ``` Thanks to the `await` keyword, we can read the code from top to bottom. This gets translated to something or other under the hood, and what exactly it is depends on the language. In JS land, it's essentially `Promise`s most of the time. The results to us _programmers_ is always the same, though: - Programmers can read/write code from top to bottom, the way we're used to doing it - No passing functions into functions means less `})` syntax to ~~forget~~ write - The `await` keyword can be an indicator that `doStuff` does something "expensive" (like call a REST API) #### What about the `async` keyword⁉ In many languages including JS, you have to mark a function `async` if it uses `await` inside of it. There are language-specific reasons to do that, but here are some that you should care about: - To tell the caller that there are `Promise`s or `await`s happening inside of it - To tell the runtime (or compiler in other languages) to do its magic behind the scenes to "make it work"™ ## 🏁 And that's it. I left a lot of implementation details out, but it's really important to remember that this pattern exists more for human reasons rather than technical. You can do all of this stuff with callbacks, but in almost all cases, `async`/`await` is going to make your life easier. Enjoy! 👋
arschles
377,381
Managing bipolar disorder as a developer
A very personal video, where I talk about my experience with managing bipolar disorder and working as...
0
2020-07-01T14:12:27
https://dev.to/drnoir/managing-bipolar-disorder-as-a-developer-36hf
mentalhealth, development
A very personal video, where I talk about my experience with managing bipolar disorder and working as a web developer {% youtube JWpJaOTb4_8 %}
drnoir
380,582
VS Code Shortcuts That I Would Teach Myself if I Had a Time Machine With Limited Fuel
— "Hey, it's me. Listen up, I don't have much time." — "Wait, what?! What is happening?! Who are-How...
0
2020-07-22T14:26:28
http://paladini.dev/posts/vs-code-shortcuts-that-i-would-teach-myself-if-i-had-a-time-machine-with-limited-fuel/
webdev, vscode, productivity, tools
— "Hey, it's me. Listen up, I don't have much time." — "Wait, what?! What is happening?! Who are-How did you get in my house?! Wh-why do you look so much like me?!" — "I *am* you, you dum-dum. I came from the future *specially* to teach you some VS Code shortcuts. Now..." — "Wait. Are you *serious*? You could've brought back lottery results, stock market data, but you came all the way here to teach me freaking VS Code shortcuts?!" — "Listen, I really don't have much juice left on this thing... Just sit and pay attention please, this is impor..." — "Couldn't you have written these shortcuts, you know, on a piece of paper?" — "Shut up! This is important!" — "Okay, okay..." — "So, you should **stop clicking for files** in File Explorer and **start using Command/Ctrl+P**, then type the file name. Add :N and it will open exactly at that line number" ![Example gif](https://dev-to-uploads.s3.amazonaws.com/i/dknmw72cwqc9759p9mtz.gif) — "Ooooh, we have hologram gifs in the future, nice example" — "I know, *right*? Also, **stop navigating the File Explorer with your mouse** altogether and just **use Command/Ctrl+Shift+E and arrow keys**, ok?" ![Example gif](https://dev-to-uploads.s3.amazonaws.com/i/6wjl0po3vjkg8h1onzot.gif) — "Ok, cool..." — "Now, if you ever need to **focus on the panel again**, instead of clicking the edit area, just **press Command/Ctrl+1** and it will focus the first open panel" ![Example gif](https://dev-to-uploads.s3.amazonaws.com/i/len0ga2b2jeu27xqvbmt.gif) — "Cool, cool cool cool cool cool no doubt" — "**Use Command+Shift+[ and ] to navigate** through file tabs, try **Alt+Left and Right** if you run Windows in this timeline. This will save you a lot of time" ![Example 3 gif](https://dev-to-uploads.s3.amazonaws.com/i/1o6ppe9fulerd7h5z51j.gif) — "Hard to think of it as *a lot* of time but, yeah, okay… You're the one with the *time* machine" — "Use **Command/Ctrl+B to toggle the editor sidebar**, it will **save you some space** when coding on small screens" ![Example gif](https://dev-to-uploads.s3.amazonaws.com/i/8x29w73g654lo5omhzz5.gif) — "I knew that one!" — "Instead of scrolling so much, **use Control/Ctrl+G to go straight to the line you want**, do you copy?" ![Example gif](https://dev-to-uploads.s3.amazonaws.com/i/287qjeujlzkprorqrw0l.gif) — "Roger that" — "**Use Command/Ctrl+Shift+L** whenever you need to *select all occurrences* of some text ![Example gif](https://dev-to-uploads.s3.amazonaws.com/i/0t3jb9x2bfna6s47g1s7.gif) — "Handy! Next one please." — "**Command/Ctrl+W closes** the current tab, **Command/Ctrl+Shift+T reopens** it" — "The usual, nothing new he..." ![Example gif](https://dev-to-uploads.s3.amazonaws.com/i/rjao669s54wmblxnv9ec.gif) — "Wait, I have to return now. **Command/Ctrl+Shift+H is Find & Replace**, you'll always forget this one, don't be too hard on yourself" ![Example gif](https://dev-to-uploads.s3.amazonaws.com/i/bpzaslxon2eoyaoctply.gif) "Wait! I have *so many questions*! How did I even get a time machine? Does *this* creates a new parallel universe? Will 49ers ever win the Super Bowl again? Hey, wait! Waaait." --- EDIT: There is a whole lot of great shortcuts in the comments, you definitely should check them! --- Repo in the examples is [forem](https://github.com/forem/forem). Gifs (with a hard G) were recorded with [Kap](https://getkap.co/) on a 680x416 size with 12 fps. VS Code theme is [Cobalt2](https://github.com/wesbos/cobalt2-vscode) and the font is [Envy Code R](https://damieng.com/blog/2008/05/26/envy-code-r-preview-7-coding-font-released). --- ## Hey, let's connect 👋 [Follow me on Twitter](https://twitter.com/paladini_dev) and let me know you liked this article! And if you *really* liked it, make sure to share it with your friends, that'll help me a lot 😄
vtrpldn
382,222
Briefing 27
Original Post Date: 6/25/2020 Author: IvanCoHe IN LIGHT OF THE NEW LEAKS I SAW SOMETHING TH...
0
2020-07-04T17:00:12
https://dev.to/smleaks/briefing-27-3jh
*Original Post Date: 6/25/2020* *Author: IvanCoHe* ## IN LIGHT OF THE NEW LEAKS I SAW SOMETHING THAT CLEARED UP SOME SHIT *They told us there were no active volcanoes here but yknow, they have been known to be wrong... on many levels:*<br> ![](https://cdn.discordapp.com/attachments/685994642768265235/725671046753157171/f245182c-5f04-462a-b58f-258ec9ad6992.png)<br> What if the ember forests are products of that volcanic activity? **Openable warehouse gate:**<br> ![](https://cdn.discordapp.com/attachments/685994642768265235/725671420197208064/unknown.png)<br> I think that something will be there. Probably lore stuff, but who knows.<br> **Jetpack**<br> Don't quote me on this, but i'm seeing this being an Exosuit upgrade, kinda like a NMS styled jetpack<br> *Editors Note:* IvanCoHe (the person whos been writing all of these brefings) left shortly after this for unknown reasons. (Ivan if you see this we hope you come back some day.)
trbodev
382,306
Learning Linked Lists
I'll start by going over the basics. What is a linked list? A linked list is a form of data structur...
0
2020-07-04T18:55:55
https://dev.to/123jackcole/learning-linked-lists-6bf
beginners, javascript, computerscience, algorithms
I'll start by going over the basics. What is a linked list? A linked list is a form of data structure. In a linked list the data in the structure is connected together in a sequence of objects. Take a look at this diagram from Wikipedia to better understand. ![Linked List Diagram from Wikipedia](https://dev-to-uploads.s3.amazonaws.com/i/7mxbvnnevi9csbq6bgct.png) Each segment (or what is commonly referred to as a node) has two parts. The data it stores, and a pointer that references the next element in the chain. Fun fact, a node is defined as "a place where a leaf and stem join on a plant." ![Alt Text](https://dev-to-uploads.s3.amazonaws.com/i/kqqwu984ij5ku500a1xq.jpeg) This makes sense when thinking about data structures, each node is a new path that originates from the same structure. Now that all of this makes sense in theory, how does it look when we implement it in code? Well a node could look like this. ![Alt Text](https://dev-to-uploads.s3.amazonaws.com/i/mnq234r2v00iq9inrq3n.png) Then to create nodes all we would need to do is something like `node1 = new Node(5) node2 = newNode(4)`. Now we have two nodes, one containing the integer 5 and the other containing the integer 4, but they both have no form of connection. To manage our nodes a good solution is to create another class for the list itself. ![Alt Text](https://dev-to-uploads.s3.amazonaws.com/i/y3irsu2rhinenxjvhfvi.png) Now we have a class for the list but no way to add in any of our nodes. So let's add it a method that utilizes our node class. ![Alt Text](https://dev-to-uploads.s3.amazonaws.com/i/lsawn4e85dxbwtpgw49u.png) Let's go through what this is doing step by step. We pass in the data that we want to add to our list. We then create a new node containing that data. We see if the linked list has any nodes, if it doesn't we assign that node to be the head (the name for the first node in a linked list). If there is already a head we initialize a current variable that will help us keep track of which node we are looking at and set it to be the head. We then iterate through the list to the end with a while loop. Then we add in our new node to the end of the list. This is only the bare bone functionality that needs to be in a linked list. What if we wanted to remove an node from the list? Count how many nodes there are in the list? Insert a node in a specific index in the list. Think about how you could implement these methods in the LinkedList class. Another thing to think about. You probably noticed that because the nodes in a linked list only reference the **next** node, it's impossible to navigate backwards through the list. There's actually another structure called a doubly linked list that, you guessed it, contains **two** pointers. One pointing to the next node, and on pointing to the previous node. ![Alt Text](https://dev-to-uploads.s3.amazonaws.com/i/5iidppmgc68j692mp3wp.png) Think about how you would implement this in the code examples that we went over and what new functionality you could add! If you want to start with the code from this post, you can get it [here](https://github.com/123JackCole/linked_lists).
123jackcole
390,590
Spotify's Random FAIL
As a programmer, I don't consider endless streaming music to be a luxury. Good tune-age is, quite li...
7,423
2020-07-10T14:13:56
https://dev.to/bytebodger/spotify-s-random-fail-14d4
javascript, programming, ux, math
As a programmer, I don't consider endless streaming music to be a luxury. Good tune-age is, quite literally, a core requirement of my workspace. To satisfy that need, I'm a Spotify Premium member. For the most part, it's an epic service. If I divided my monthly bill by the hours of music I receive, it would easily be one of best values I've ever purchased. But that doesn't mean that Spotify is without faults. And at certain points in the past, those faults have driven me absolutely **INSANE**. [NOTE: This is the second half of my treatise on randomness - and how it can ruin your users' experience. In the first article, I outlined some of the cognitive biases that can undermine "random" features in applications. You can read it here: https://dev.to/bytebodger/random-can-break-your-app-58bo] <br/><br/> ![Alt Text](https://dev-to-uploads.s3.amazonaws.com/i/i9tryzgfrlr3m7a7dltq.jpg) ## Spotify Don't Know Shuffle I have playlists. Most hardcore Spotify users do. My blues playlist has 436 tracks. My drum-n-bass playlist has 613 tracks. Most of my heavily-curated playlists have somewhere between 400 and 700 tracks. I often switch between my playlists depending upon what's going on in my day and where I need my "headspace" to be. When I'm in frenetic code-euphoria mode, I'm cranking out my drum-n-bass list. When I'm in a more contemplative place, I might be listening to traditional jazz. So over the course of a single day, I might spend an hour-or-two listening to as many as 10 different playlists. Here's the problem: When I switch to a new playlist, I want to come into that playlist as though I've just switched the radio dial to a targeted genre station. That station doesn't know "where I left off". That station doesn't know what I might have heard yesterday. The station just keeps cranking along, oblivious to whether I'm listening or not. The station has an expansive list of tracks they'll play. And they play those tracks, more-or-less randomly, over the course of several days. And I want my Spotify experience to mirror this. But Spotify stubbornly, angrily, obstinately, pig-headedly _refuses_ to let me have this experience. This refusal comes in the form of their utter disregard for their so-called "shuffle" function. <br/><br/> ![Alt Text](https://dev-to-uploads.s3.amazonaws.com/i/ah97mvnox9uenmy8eh94.jpg) ## A Shuffling Fraud If you've ever used Spotify yourself, you might be thinking: <br/> > But Spotify _has_ a shuffle feature. It's a button that looks like two crossing arrows. <br/>And of course, you'd be right. Spotify does indeed have such a feature. But the feature has nothing to do with a "shuffle". It's a _lie_. Spotify does "shuffle" the same way that Republicans do "civil rights". It's a button that does... something. But whatever it's doing, it has no relation to the label. You see, in a perfect world, "shuffling" implies a true randomization of the data set. As I covered in the previous article, "random" doesn't mean that it will satisfy what every layperson views as "random". "Random" means _truly damn random_. In other words, when you truly _randomize_ a data set, it will have no bearing on any previous results. "Random" can, in fact, contain "trends" (although they are trends that will evaporate once you try to track them). But when you use Spotify's "shuffle" feature, you'll find that those _trends_ pop up all-too-often. You'll find that certain songs, somehow, keep creeping up to the top of your playlist. And other songs _never_ seem to get played. If you understand probabilities the way I do (and as a high-stakes poker player, I have some serious experience with this), at first you'll brush these repetitions off as the kind of fleeting coincidences that can occur in a truly _random_ data set. But after you spend _hundreds of hours_ listening to your playlists, you'll eventually come to understand that these strange coincidences have nothing to do with the vagaries of randomness. <br/><br/> ![Alt Text](https://dev-to-uploads.s3.amazonaws.com/i/hf2jvs68ctje366g02vx.jpg) ## The Goal I thought my "quest" was simple. I didn't think I was chasing the Holy Grail. _All I wanted_ was to get a fresh SHUFFLE of my playlists any time I desired. What do I mean by "shuffle"?? Well, think of it just like a deck of cards. Between _every_ poker hand, the cards are thoroughly shuffled. (In any modern context, this is done by an automatic shuffling machine.) This means that every hand is a completely new, completely independent event. Yes, it's possible that you'll hear the same song that you heard in your last session. And it's possible that you'll "miss" other songs over multiple sessions. But I'm perfectly fine with that. I just want my playlists to be played in a truly _random_ manner. I want to know that, every time I "shuffle" a playlist, the Humpty Dance _could_ come up as the first song in the mix. Or... I may not hear it again for awhile. _That's_ the true nature of randomness. But Spotify doesn't work this way. How do I _know_ that??? Well, I'm glad you asked... <br/><br/> ![Alt Text](https://dev-to-uploads.s3.amazonaws.com/i/pvgcr8unqtzt0qbm9y2s.jpg) ## Know-It-Alls I'm not the only one annoyed with Spotify's not-so-randomness. Many others have noticed that some of their songs get played _repeatedly_. While other songs simply never get played. If you wanna get a sense for the scope of the problem, just google "spotify shuffle sucks" and behold the massive menu of rage posts. Their own "community" forum site has many threads complaining about the issue. One of those threads has _189 pages_ of ongoing comments, spanning back over _years_. Is this a case of a tone-deaf company completely ignoring an issue? Not exactly. This is a case of an arrogant company swearing that they've fixed the issue. They published this cheeky explanation of their approach way back in 2014 where they graciously congratulate themselves for their high-minded brilliance: https://engineering.atspotify.com/2014/02/28/how-to-shuffle-songs/ They acknowledge that the "shuffle" algorithm isn't at all random. They brag about how they've supposedly fixed it by implementing a better algorithm that accounts for peoples' misconceptions about randomness. And for the last 6+ years, they've stubbornly refused to do anything else about it - even though there are _thousands_ of ongoing complaints across the internet about their super-janky faux shuffler. But their shuffle algorithm doesn't even work the way that they say it does. If you spend excruciating amounts of time diving into the behavior of their application, it quickly becomes quite clear that some songs just get repeatedly _ignored_. This isn't a case of me seeing nonexistent patterns in the noise. I can pretty much _prove_ that their "improved", better-than-random algorithm just can't be bothered to play certain songs. In fact, I put up a repeatable use-case in their own forums. You can read it here: https://community.spotify.com/t5/Ongoing-Issues/Please-stop-marking-shuffle-complaints-as-quot-not-an-issue-quot/idc-p/1783738#M49827 You'll also notice that I titled the post in their community forums as `Please stop marking shuffle complaints as "not an issue" or "implemented"`. I gave it that title, because that's _exactly_ what they do. User after user after frustrated user complains about the exact same thing. And their response is simply to mark the complaint as "not an issue" or "implemented". For the post above, in which I gave them a detailed write-up of how to recreate the issue, they answered: <br/> > We understand your situation! We're looking into it and we're working on our shuffle algorithm. Keep an eye on any updates soon. Take care. <br/>Then... they marked the ticket as "Not An Issue". <br/><br/> ![Alt Text](https://dev-to-uploads.s3.amazonaws.com/i/03nn803pw4gki9u8kfft.jpg) ## A Frustrating Problem This probably feels like it's just a long angry rant about a particular company that can't be bothered to fix its own software. But I'm writing this up on Dev.to because there are valuable lessons for us to take from this example as programmers. Spotify went down this path because people inherently misunderstand randomness. I get that. But they decided to fix a "problem" - by introducing another problem. Most people just don't _grok_ random sequences. They have 100 songs in their playlist. Five of those songs are by Justin Bieber. After the playlist is _randomly shuffled_, they hear two Justin Bieber songs in a row. And they start thinking: "Heyyy! _That's_ not random!" But... it _is_. If you shuffle your 100-song playlist that has 5 Bieber tracks, it's perfectly possible that you _might_ end up hearing 2 of those tracks in a row. The same concept is at play when you thoroughly shuffle a deck of playing cards and two aces are dealt out in a row. It's absolutely possible. And it doesn't mean that the shuffle wasn't "random". <br/><br/> ![Alt Text](https://dev-to-uploads.s3.amazonaws.com/i/jyg0cv2cqbjj71ctqied.jpg) ## Don't Be Like Spotify To be clear, Spotify was justified in trying to rig their "shuffle" feature. Because if your users repeatedly _perceive_ that there's a problem in your app, then there _is_ a problem in your app. It won't do any good to yell at them that they just don't understand randomness. The mismatch between perception and reality is often most acute whenever we try to implement _random_ features in our apps. It could be a music playlist. It could be a "quote of the day". It could be a game where the damage incurred by your character is calculated as a random die roll. In all these examples, it's tempting to just slap a random number generator on it and call it a day. But if too many of your users _perceive_ that the process isn't random, they may become frustrated to the point that they're no longer your users. In fact, if they're _really_ frustrated, they may even complain to your potential future users. In the most extreme cases, you may reach a situation where you simply have no users - even though your random algorithm was mathematically flawless. So if randomness carries the risk of being misinterpreted by your users, how can you solve the problem? Well, you _could_ choose to follow the patented Spotify Method: <br/> 1. Make an obtuse change to your algorithm and brag about it in a blog post.<br/><br/> 1. Offer no options to the user in the UI.<br/><br/> 1. Any time someone complains about the new algorithm, mark their complaint as "Implemented" or "Not An Issue" - without making any changes.<br/><br/> If this approach doesn't appeal to you, then, congratulations! You're not a douchebag. So what other options do you have?? Well... here are some thoughts: <br/> **Don't make monolithic decisions for your users.** Whenever possible, give your users _options_. I don't mind that Spotify felt it necessary to implement some kind of "enhanced" shuffle algorithm. That's fine. But give me the _option_ to turn it off. Or maybe, somewhere in the "Settings", allow me to actually _choose_ which algorithm I prefer when shuffling. <br/> **Don't treat your API as a fix for UX problems.** I bring this up because Spotify does have an API that will allow tech-types like us to build our own shuffle features. I eventually solved this by writing my own custom shuffler that leverages their API. There are a handful of other "Spotify shufflers" out there on the web. But this should never be the "answer" to problems inside your app. It's wonderful if you can manage to supply a robust API that allows users to extend your app's functionality. But the vast majority of your users will only ever use your app... _inside your app_. They either don't know how to build API integrations - or they can't be bothered to. <br/> **Be _transparent_ with your algorithms.** We tend to protect our algorithms more than we protect our children. But when you have a feature that frustrates your users, that frustration can be multiplied by their ignorance of _how_ the app is actually working. I'm not saying that you need to hand over your complete code base. But for something as "magical" as shuffling, it would go a long way toward mollifying your users if you just explain to them - clearly, accurately, and concisely - exactly how the sausage gets made. The Spotify experience is especially aggravating because, after extensive research and testing, I was able to repeatedly demonstrate that _their algorithm does not work in the way they claim it works_. And yet, they refuse to do anything about it. In fact, they refuse to even acknowledge the issue in any way. <br/> **Give users a history of past results.** This can go a long way toward alleviating user frustration. It's only natural that, when I'm using your battle simulator, it _feels_ to me like I lose at a disproportionate rate. But if I can view a history of my last 500 battles, it's at least possible that I may look back over that history and realize that the world (your app) isn't truly tilted against me. <br/> **Carefully consider if randomness is what you truly _want_ in your app.** Once you understand that users inherently misunderstand randomness, it's reasonable to ask yourself whether you really want to use randomness at all. For example, imagine that my app is an online media player that continually streams a selection of video highlights from local high school athletics. Let's also imagine that I have a library of 10,000 such clips to choose from. It would be incredibly simple to just load up the IDs for all 10,000 and then randomly select one after another after another. But I can almost guarantee that this will lead to complaints from my users. You see, it's inevitable that, in my random video queue, I'll eventually play two, or three, or four highlights all in a row _from the same high school_. It's also inevitable that some of my viewers will start griping about the idea that my app is "biased" toward one school, or against their favorite school. It probably makes more sense to spend some time _categorizing_ the video clips by school, by sport, by player, etc. Once they're categorized, I can write a more tailored "randomization" algorithm that will take these factors into account before building the video queue. Yes, that requires more work, and more forethought. But if it fosters the long-term success of my application, it's well worth it. <br/><br/> ## Conclusion In the end, there are some times when "true" randomness is absolutely necessary. But be warned, it's almost impossible to implement a feature based on randomness that won't lead at least _some_ of your users to complain about the non-randomness (that they perceive). How you choose to address those perceptions will go a long way toward determining the success, and the public acceptance, of your application.
bytebodger
382,321
My website now loads in less than 1 sec! Here's how I did it! ⚡
Hi there! The reason why you're here is probably because you wanna know what I did to load my portfo...
0
2020-07-04T18:43:30
https://dev.to/cmcodes/my-website-now-loads-in-less-than-2-sec-here-s-how-i-did-it-hoj
javascript, webperf, webdev, showdev
Hi there! The reason why you're here is probably because you wanna know what I did to load my portfolio website in just **0.8 seconds** and achieved a **performance score of 97** on lighthouse. Link to my portfolio and its source code is at the bottom. I will lay out all my tips and tricks over here, which I implemented to achieve this! Let's get this thing started! 🤘 > NOTE: According to Lighthouse, "Values are estimated and may vary. The performance score is [based only on these metrics](https://github.com/GoogleChrome/lighthouse/blob/d2ec9ffbb21de9ad1a0f86ed24575eda32c796f0/docs/scoring.md#how-are-the-scores-weighted)." This report was generated on 2nd of August, 06:29:22 PM IST. These scores might reflect a bit different on your machine due to internet connection speed or multiple extensions running in the background or I might add some features later. Also, I have "clearly" mentioned above that these scores were generated by Google Lighthouse. Don't expect the same score on any other tool. So, please don't try to troll on this basis and save your energy. Peace! ✌ # Tip #1 # Don't use a large DOM tree. >My portfolio contains 487 DOM elements with a maximum DOM depth of 13 and a maximum of 20 child elements only! If your DOM tree is very large, then it will slow down the performance of your webpage: * Memory performance Using general query selectors such as document.querySelectorAll('li'), stores references to a multiple nodes which can consume the memory capabilities of the device. * Network efficiency and load performance A big DOM tree has many nodes (not visible in first load), which slows down load time and increases data costs for your users. * Runtime performance Whenever a user/ script interacts with your webpage, the browser needs to recompute the position and styling of nodes. having complicated style rules can slow down the rendering. # Tip #2 # Don't use enormous network payloads. > My portfolio has a total network payloads size of just 764 KB. The total payload size of your website should be below 1600 KB. To keep it low, you can do the following: * Defer requests until they're needed. * Minify and compress network payloads. * Set the compression level of JPEG images to 85. > Always remember, large network payloads cost large amounts of money. # Tip #3 # Don't use GIFs. Rather use PNG/ WebP format for dispalying static images. But if you want to display animated content then instead of using large GIFs (inefficient & pixelated) consider using MPEG4/ WebM video format. Now, you will say what if I want their features like: * Automatic play. * Continuous loop. * No audio. Well let me rescue you from this, the HTML5 `<video>` element allows recreating these behaviors. ```html <video autoplay loop muted playsinline> <source src="my-animation.webm" type="video/webm"> <source src="my-animation.mp4" type="video/mp4"> </video> ``` # Tip #4 # Preload key requests Suppose your page is loading a JS file which fetched another JS and a CSS file, the page won't appear completely until both of those resources are downloaded, parsed, and executed. If the browser would be able to start the requests earlier, then there would be much time saving. Luckily, you can do so by declaring preload links. `<link rel="preload" href="style.css" as="style">` # Tip #5 # Don't try multiple page redirects. Redirecting slows down the load speed of your webpage. When a browser requests a resource that has been redirected, the server returns an HTTP response. The browser must then make another HTTP request at the new location to retrieve that resource. This additional trip across the network can delay the loading of the resource by hundreds of milliseconds. If you want to divert your mobile users to the mobile version of your webpage, consider redesigning your website to make it responsive. # Tip #6 # Preconnect to required origins. Using the keyword `preconnect` gives a signal to the bowser to establish early connections to important third-party origins. `<link rel="preconnect" href="https://www.google.com">` Doing so establishes a connection to the origin, and that informs the bowser that you want the process to start ASAP. # Tip #7 # Encode your images efficiently. A compression level of 85 is considered good enough for JPEG images. You can optimize your images in many ways: * Avoiding GIFs. * Using image CDNs. * Compressing images. * Lazy loading images. * Using WebP image format. * Serving responsive images. # Tip #8 # Minify your JavaScript files. Minification is the process of removing whitespace and any code that is not necessary to create a smaller but perfectly valid code file. By minifying your JavaScript files, you can reduce the payload size and parsing time for the script. > I use [JavaScript Minifier](https://javascript-minifier.com/) for the same. # Tip #9 # Minify your CSS files. CSS files occupy more whitespace than any other file. By minifying them, we can save some bytes for sure! Do you know that you can even change a color value to its shorthand equivalent, like #000000 can be reduced to #000, and will work just fine! > I use [CSS Minifier](https://cssminifier.com/) for the same. # Tip #10 # Resize your images. I can bet this is the most given advice when it comes to webperf because the size of images is far far far greater than any text script file, so an over-sized image might be an overkill. You should never upload images that are larger than what's rendered on the screen, that will do no good. You can either just simply resize your image dimensions or use: * Responsive images. * Image CDNs. * SVG instead of icons. Thank you for reading so far! 😄 Hope you learned something new from this! 😃 Here's the link to my portfolio website 👉 [cmcodes](https://cmcodes1.github.io) Here's the link to my portfolio source code 👇 {% github cmcodes1/cmcodes1.github.io no-readme %} Check it out and do let me know your views! Eager to hear your opinion. 😁 Feel free to share your portfolio link in the comments below. I would be very happy to have a look at them. 😊 Happy Coding! 👨‍💻
cmcodes
382,420
In Depth Laravel - Master Laravel in 32 hours
Become a professional Laravel developer from this course Check full detail at https://inde...
0
2020-07-04T19:40:29
https://dev.to/sarthaksavvy/in-depth-laravel-master-laravel-in-32-hours-3h4l
laravel, php, vue, javascript
# Become a professional Laravel developer from this course Check full detail at https://indepthlaravel.com ### What you will get * 28 Chapters * 288 Videos * Beginner * 32.70 hour of content * Lifetime Access * Access anywhere * Real Project * Certificate ## What you will learn * Acquaintance with the laravel * What are MVC * Project 1 - Advanced Todo App using Livewire * Project 2 - URL shortener using Vuejs * Project 3 - Eventile - An Event Ticket App API * Project 4 - Test Driven Blog * Project 5 - Support Ticket system with Laravel Livewire * Deploying every project on server Here is the quote from creator of laravel about the course {% twitter 1279449627738042369 %} If you want to know more about the course, you can visit https://indepthlaravel.com or just DM me on twitter or shoot an email I hope this rich content makes your life easier while learning Laravel
sarthaksavvy
382,451
React App - Typescript PWA Builder Code
If you dont want to follow a guide, and you need a preset builder only replace the 'project-name' wit...
0
2020-07-04T21:48:32
https://dev.to/edisonsanchez/react-app-typescript-pwa-builder-code-2lfo
If you dont want to follow a guide, and you need a preset builder only replace the 'project-name' with your ProjectName. ``` npx create-react-app project-name --typescript cd project-name npm install -D @typescript-eslint/eslint-plugin @typescript-eslint/parser babel-eslint eslint eslint-config-airbnb eslint-config-prettier eslint-plugin-import eslint-plugin-jest eslint-plugin-jsx-a11y eslint-plugin-prettier eslint-plugin-react husky lint-staged prettier react-test-renderer require-context.macro tslint tslint-config-prettier tslint-plugin-prettier tslint-react npm install npm audit fix curl https://gist.githubusercontent.com/Edisonsan/a02104c9aabc8f0cfce0413f995905d1/raw/b9c32b9643e5f83ed3f1b9f2a8b66cfb26753e37/.env --output .env https://gist.githubusercontent.com/Edisonsan/2df55435733f2047be938388566df2cd/raw/5f6f15cf9a82e94e3656fa8978d2583c198be12e/react.eslintrc.js --output eslintrc.js curl https://gist.githubusercontent.com/Edisonsan/2b6ba8fb90fddc8c519c5aca5a71204d/raw/a2f92762928d17847b36a88f27efb04c348e8859/react.prettierrc --output .prettierrc curl https://gist.githubusercontent.com/Edisonsan/d81b57f53190e6a0d575024edffa937c/raw/32212726a5e44d5342992f23e48f2b871bbec5f0/react.tsconfig.json --output tsconfig.json curl https://gist.githubusercontent.com/Edisonsan/58752594362c916391f5291f62a69cbc/raw/ff909c497c7987585eb94fdf45e3bab45829f863/react.tslint.json --output tslint.json npx -p @storybook/cli sb init --story-format=csf-ts npm install -D @storybook/addon-actions @storybook/addon-docs @storybook/addon-knobs @storybook/addon-links @storybook/addon-storyshots @storybook/preset-create-react-app @storybook/react @types/styled-components curl https://gist.githubusercontent.com/Edisonsan/deb70c41bb429e7c31de4f736b3d30f4/raw/914a074cfe2b8555bea6fc30a81d6199620acfa2/react.storybook.addon.ts --output ./.storybook/addons.ts curl https://gist.githubusercontent.com/Edisonsan/acd830caf63db46df7bcaf61650dfba9/raw/297d4d48aeab72fa0c1575654a0565640ce42fcc/react.storybook.config.ts --output ./.storybook/config.ts curl https://gist.githubusercontent.com/Edisonsan/bf667058922b2196a089eb01684266af/raw/a9213daaeb437ed3fc7acaca2d81a817e9b05636/react.stortbook.main.ts --output ./.storybook/main.ts curl https://gist.githubusercontent.com/Edisonsan/d655ac1f18a35824987fbcd438f840cd/raw/bba9d8e03c3d95185f4b192dad415fd87e1c7c46/react.webpack.config.ts --output ./.storybook/webpack.config.ts npm install pwacompat @material-ui/core @material-ui/icons apollo-boost aws-amplify aws-sdk axios material-ui-image moment moment-timezone prop-types react-apollo react-device-detect react-helmet react-icons react-router-dom serve styled-components ``` And this to your package.json ```json scripts: { ... "lint-ts": "tslint -c tslint.json 'src/**/*.{ts,tsx}'", "lint-js": "eslint 'src/**/*.{js,jsx}' --quiet --fix", "lint": "tslint -c tslint.json src/**/*.{ts,tsx} --fix --format verbose", "storybook": "start-storybook -p 9009 -s public", "build-storybook": "build-storybook -s public", ... }, ... "husky": { "hooks": { "pre-commit": "export CI=true && yarn build && lint-staged && yarn test", "pre-push": "export CI=true && yarn build && lint-staged && yarn test" } }, "lint-staged": { "*.{ts,tsx}": [ "tslint -c tslint.json" ], "*.{js,jsx}": [ "eslint --fix" ] } ... ``` #Convert to PWA Generate icons using the following platforms. - [Real FavIcon Generator](https://realfavicongenerator.net) - [Fav Icons](https://favicon.io) ``` npm install -g serve ``` Copy all the images into ./public/favicons/ Update the head in HTML file: index.html in /public ```html <head> <meta charset="utf-8" /> <meta name="viewport" content="minimum-scale=1, initial-scale=1, width=device-width, shrink-to-fit=no" /> <meta name="author" content="Edison Sanchez" /> <meta name="apple-mobile-web-app-capable" content="yes" /> <meta name="apple-mobile-web-app-title" content="project-name" /> <meta name="apple-mobile-web-app-status-bar-style" content="black" /> <link rel="apple-touch-icon" href="%PUBLIC_URL%/favicons/apple-touch-icon-iphone-60x60.png" /> <link rel="apple-touch-icon" sizes="57x57" href="%PUBLIC_URL%/favicons/apple-icon-57x57.png" /> <link rel="apple-touch-icon" sizes="60x60" href="%PUBLIC_URL%/favicons/apple-icon-60x60.png" /> <link rel="apple-touch-icon" sizes="72x72" href="%PUBLIC_URL%/favicons/apple-icon-72x72.png" /> <link rel="apple-touch-icon" sizes="114x114" href="%PUBLIC_URL%/favicons/apple-icon-114x114.png" /> <link rel="apple-touch-icon" sizes="120x120" href="%PUBLIC_URL%/favicons/apple-icon-120x120.png" /> <link rel="apple-touch-icon" sizes="144x144" href="%PUBLIC_URL%/favicons/apple-icon-144x144.png" /> <link rel="apple-touch-icon" sizes="180x180" href="%PUBLIC_URL%/favicons/apple-icon-180x180.png" /> <link rel="icon" type="image/png" href="%PUBLIC_URL%/favicons/favicon-16x16.png" sizes="16x16" /> <link rel="icon" type="image/png" href="%PUBLIC_URL%/favicons/favicon-32x32.png" sizes="32x32" /> <link rel="icon" type="image/png" href="%PUBLIC_URL%/favicons/favicon-96x96.png" sizes="96x96" /> <link rel="icon" type="image/png" href="%PUBLIC_URL%/favicons/android-chrome-512x512.png" sizes="512x512" /> <link rel="mask-icon" href="%PUBLIC_URL%/favicons/safari-pinned-tab.svg" color="#000000" /> <meta name="theme-color" content="#ffffff" /> <meta name="description" content="project-description" /> <meta name="msapplication-TileColor" content="#000000" /> <!-- Fonts Robot & Material UI --> <link rel="stylesheet" type="text/css" href="https://fonts.googleapis.com/css2?family=Roboto:ital,wght@0,100;0,300;0,400;0,500;0,700;0,900;1,100;1,300;1,400;1,500;1,700;1,900&display=swap" /> <link rel="stylesheet" href="https://fonts.googleapis.com/icon?family=Material+Icons" /> <!-- manifest.json provides metadata used when your web app is installed on a user's mobile device or desktop. See https://developers.google.com/web/fundamentals/web-app-manifest/ --> <link rel="manifest" href="%PUBLIC_URL%/manifest.json" /> <script async src="https://unpkg.com/pwacompat" crossorigin="anonymous"></script> <!-- Notice the use of %PUBLIC_URL% in the tags above. It will be replaced with the URL of the `public` folder during the build. Only files inside the `public` folder can be referenced from the HTML. Unlike "/favicon.ico" or "favicon.ico", "%PUBLIC_URL%/favicon.ico" will work correctly both with client-side routing and a non-root public URL. Learn how to configure a non-root public URL by running `npm run build`. --> <title>project-name</title> </head> ``` Cambiar el manifest.json en public ```json { "short_name": "project-name", "name": "project-description", "icons": [ { "src": "./favicons/android-chrome-192x192.png", "sizes": "192x192", "type": "image/png" }, { "src": "./favicons/favicon-512x512.png", "sizes": "512x512", "type": "image/png" } ], "start_url": ".", "display": "standalone", "theme_color": "#ffffff", "background_color": "#ffffff", "dir": "ltr", "lang": "en-US", "orientation": "portrait-primary" } ``` Update index.tsx change .unregister by .register Run and build, test with incognito on Chrome, open Lighthouse PWA and just one error should be result: No SSL. #Install and Initialize Bit ``` bit init bit login ```
edisonsanchez
382,456
How to Watch Live TV Online for Free!
With the looming threat of covid-19, I foresee every week or two where I'm huddled in my bedroom tryi...
0
2020-07-04T20:55:18
https://dev.to/247acecast/how-to-watch-live-tv-online-for-free-2ooj
livetv, livetvonline, watchlivetvonline
With the looming threat of covid-19, I foresee every week or two where I'm huddled in my bedroom trying to remain safe. i don't know about you, but the thought of days worth of boredom doesn't sound too exciting. It got me wondering if there are TV shows and movie streaming online for free, which resulted in me making this post! Before i begin, let me say i do know all about Netflix. 😀 But that costs money! One thing I've noticed is that a lot of “freebie & frugal” sites all push paid options for cutting the cord and ditching cable. Sure, some are great. I split a YouTube TV account with my friends and that's cool. But shouldn't there be … you know any, free methods as well? Why do all the other sites push paid-services with their affiliate links? is it not the point of ditching a monthly cable subscription to truly save money? Thus, I've come up with this post to show you how you can watch live, local TV for absolutely free with no subscriptions whatsoever. ## 247Acecast 247Acecast is your no. 1 destination to watch and stream live TV channels online for free. They offer you with HD & SD quality live stream broadcasts & videos to any Live TV Event that's televised and available round the globe. Visit [247acecast](http://www.247acecast.com) to learn more
247acecast
382,981
How I motivates myself to code more.
When coding, staying motivated is sometime a big thing. It might be challenging. I do get tired somet...
0
2020-07-05T07:24:36
https://dev.to/abdulsalam/how-i-motivates-myself-to-code-more-ie6
When coding, staying motivated is sometime a big thing. It might be challenging. I do get tired sometimes when I'm coding. I feel like quitting and finding other things to do. Then I took a bold step of analysing what the problem is. I wrote a post about it. It's one of the best decision I made. It was my first post. I discovered I have been forcing myself to code stuff I don't really love doing. It was actually as a result of having a wrong mindset. I was feeling my learning or what I code is a competition I'm having with others. Which is wrong. After publishing the post, I was able to filter out what I love doing. I started doing it and everything changed. Each morning, I look forward to sit in front of the screen and code the entire day. I enjoy writing more JavaScript. I do get stuck, it's a little bit frustrating but also interesting. The feeling when I got stuck is one thing I love. I found myself thinking about the problem and how to solve it which in turn increase my problem solving skills. Discover what you love doing and take your time to learn and grow in your own way. Thanks for reading!
abdulsalam
423,992
Redux Toolkit, and integrating React with Redux
In this final post of the Redux series I will demonstrate how to use the React-Redux package to make...
8,067
2020-08-17T10:29:15
https://dev.to/zenulabidin/redux-toolkit-and-integrating-react-with-redux-5dd8
In this final post of the Redux series I will demonstrate how to use the React-Redux package to make state changes update React UI components. I will also show you how to use the Redux Toolkit package to simplify Redux development. So let's begin. ## React-Redux Let's begin with React-Redux first. As mentioned in the previous post, you create a React project with Redux support using: ```js npx create-react-app my-app --template redux ``` This automatically installs React-Redux into your project. There are two key differences in React-Redux projects versus plain Redux projects: 1. `useSelector()` is used instead of `subscribe()` and `getState()`. It returns the value of a state part. 2. `useDispatch()` is used instead of `dispatch()`. It returns a handle to the `dispatch()` method. In a React-Redux app, you don't access the Redux state directly, you use `useSelector()` and `useDispatch()` within components to read and write Redux state. Whenever Redux state is updated, it will automatically trigger a re-render of the React component that uses that state (via `useSelector()` returning a different value). State is dispatched the normal way, using the handle to the `dispatch()` method returned by `useDispatch()`: ```js export function SomeComponent { const dispatch = useDispatch() //... return ( <button onClick={() => dispatch({type: "SomeAction"})}>Click me</button> ) } ``` As for `useSelector()`, that is invoked with a function passed as an argument that returns the relevant part of the state. So this works: ```js const selectCount = state => state.counter.value const count = useSelector(selectCount) ``` By intuition, this also works: ```js const count = useSelector(state => state.counter.value) ``` Finally, you need to pass a Redux store to the main React component so it can propogate that store to child components for them to use. This is done by rendering a `Provider` component above the main `App` component: ```js import { Provider } from 'react-redux' import { createStore } from 'redux' // ... ReactDOM.render( <Provider store={configureStore({ reducer: someReducer })}> <App /> </Provider>, document.getElementById('root') ) // Now the store is accessible from the <App> component and // its child components ``` ### An example React-Redux component The following component was taken from the Redux.js tutorial and is also available [here](https://redux.js.org/tutorials/essentials/part-2-app-structure#the-react-counter-component). Key parts of the app are indicated with comments. ```js import React, { useState } from 'react' import { useSelector, useDispatch } from 'react-redux' /* * These are our action creator functions. They return action objects. */ import { decrement, increment, incrementByAmount, incrementAsync, selectCount } from './counterSlice' import styles from './Counter.module.css' export function Counter() { /* * `useSelector()` calls `useState()` under the hood causing * this component to update if the value returned from * `useSelector()` changes. */ const count = useSelector(selectCount) /* * `useDispatch()` returns the dispatch object from the Redux * store variable. * Notice in the onClick prop of the <button> tags this * dispatch function is called with the return value of the * `increment` and `decrement` action creators (an action * object) */ const dispatch = useDispatch() const [incrementAmount, setIncrementAmount] = useState('2') return ( <div> <div className={styles.row}> <button className={styles.button} aria-label="Increment value" onClick={() => dispatch(increment())} > + </button> <span className={styles.value}>{count}</span> <button className={styles.button} aria-label="Decrement value" onClick={() => dispatch(decrement())} > - </button> </div> {/* omit additional rendering output here */} </div> ) } ``` ## Redux Toolkit It's time to cover the second topic of this post, Redux Toolkit. Redux Toolkit exports `configureStore()` and `createSlice()` functions. If the first one sounds familiar it's because this function exists in Redux as well. But this function is exported from Redux Toolkit so you don't have to import anything from Redux directly. It is used the same way as the Redux `configureStore()`. As for `createSlice()`, this is the convenience method that generates action creators I was talking about in the previous post. It generates actions in the form `"name"/"reducer"`, where `"name"` is the name of the action creator you give it (some people call "name" a namespace), and `"reducer"` is the name of each reducer. Note that I said each reducer, `createSlice()` accepts several reducers by means of keys in objects. (Please remember that actions are strings that can have any possible value.) The input object should also contain an `initialState` property that is an object with the initial state values. `createSlice()` returns what is called a *slice* which is just an action creator that has an `actions` property that is an object of action creators, and a `reducer` property that is the actual reducer function. It is a formal name the Redux community gave it as opposed to a subjective term like "feature" or "a state part". This is the format of the object that is passed to `createSlice()`: ```js import { createSlice } from '@reduxjs/toolkit' export const counterSlice = createSlice({ name: 'counter', initialState: { value: 0 }, reducers: { // If we don't use a parameter we can omit it like // we did to `action`. increment: state => { return state.value + 1 }, decrement: state => { return state.value - 1 }, incrementByAmount: (state, action) => { return state.value + action.payload } } }) ``` Here's a recap of the properties in the parameter object and returned object: * Input object: - `name`: name of the slice - `initialState`: Initial state of the slice - `reducers`: an object containing each reducer name and its associated function * Output object - `actions`: action creators returning actions of the form `"name"/"<REDUCER-FUNCTION-NAME>"`. Each action can be accessed by its name, such as `slice.actions.increment`. - `reducer`: The reducer function made from combining the reducers passed in the input. A note about action creators: You can pass a single argument to the action creator to use as the `payload` property. So you type `incrementByAmount(5)` to set the `action.payload` to 5. This works for the other actions to even though I didn't list an action parameter for it, the only reason I didn't list one is because the reducers don't use it. You might be wondering at this point how can the reducers be combined into one. The answer here is by using a function that Redux exports called `combineReducers()`. This function takes an object as input with each slice as a key and its associated reducer as a value. Here's an example: ```js const rootReducer = combineReducers({ users: usersReducer, posts: postsReducer, comments: commentsReducer }) ``` In fact we can just pass the `reducers` property of the input to this function to get our reducer. In practice though, you don't do this yourself, you let `createSlice()` do this for you. ### And we're done This concludes the Redux series. I hope this series helped you become familiar with Redux development. If you see any errors in this post, please let me know so I can correct them.
zenulabidin
383,107
FYI: The UI Development Mentoring Newsletter is now called UI Dev Newsletter
Subscribe here: https://tinyletter.com/starbist. Or here: https://mentor.silvestar.codes/reads#newsle...
0
2020-07-05T09:06:42
https://dev.to/starbist/fyi-the-ui-development-mentoring-newsletter-is-now-called-ui-dev-newsletter-5bbn
news, uiweekly, css
Subscribe here: https://tinyletter.com/starbist. Or here: https://mentor.silvestar.codes/reads#newsletter. UI Dev Newsletter is a hand-curated list of articles, tutorials, opinions, and tools related to User Interface development. Enjoy the read and happy coding! P.S. I would appreciate it if you could spread the word about the newsletter. I have already prepared [the tweet](https://twitter.com/intent/tweet?text=UI%20Dev%20Newsletter%20is%20a%20hand-curated%20list%20of%20resources%20related%20to%20User%20Interface%20development.%20Subscribe%20today!%20%F0%9F%99%8F&url=https%3A%2F%2Ftinyletter.com%2Fstarbist) to save you some time.
starbist
383,235
Easy peasy First Odd Int
In a given array, find the first integer that appears an odd number of times. Given that only one int...
7,646
2020-07-05T11:05:50
https://dev.to/divyajyotiuk/easy-peasy-first-odd-int-133o
todayilearned, javascript, beginners
In a given array, find the first integer that appears an odd number of times. Given that **only one** integer occurs odd number of times. One line solution to this is by using the infamous reduce operation of Javascript. ```javascript const findOddInt = (arr) => arr.reduce((a, b) => a ^ b); ``` Always go for functional and tuned solution, reason it being faster ;) For those who are wondering, **^** is the symbol for XOR. `a^a = 0` and `0^a = a`. So, all the numbers that occur even times will get reduced to 0 and the number that occurs odd number of times would remain.
divyajyotiuk
383,250
D3.js Creating a Bar Chart from Ground Up
Creating a bar chart is not that difficult, or is it? Today, we are going to dissect the basic...
0
2020-07-05T14:57:06
https://sahansera.dev/d3-creating-bar-chart-ground-up/
javascript, d3, beginners
--- title: D3.js Creating a Bar Chart from Ground Up published: true date: 2020-07-05 14:57:00 UTC tags: javascript, d3, beginners canonical_url: https://sahansera.dev/d3-creating-bar-chart-ground-up/ cover_image: https://dev-to-uploads.s3.amazonaws.com/i/txlv1jxytcjuvs23fx7p.jpg --- Creating a bar chart is not that difficult, or is it? Today, we are going to dissect the basic elements of a bar chart and create it from the ground up using D3.js. It’s pretty easy to copy bits and pieces and construct a bar chart. But, the motivation behind this post is to cover the concepts behind creating a bar chart. > You can clone the finished version of this tutorial -[D3 Bar Chart repo](https://github.com/sahan91/D3.js-Bar-Chart) I will be using D3.js [v5.16.0](https://github.com/d3/d3/releases/tag/v5.16.0) which is the latest version of as of yet. Before jumping into coding, first, we need to understand what is the anatomy of a D3 chart. ### Anatomy of a D3 Bar Chart Again, I’m going to keep this as simple as possible. We won’t be covering stuff like calling a Web API, loading a CSV, filtering, cleaning, sorting etc. D3 uses SVG and its coordinate system under the hood - i.e. 0px, 0px are at top left corner. So, let’s start with a blank SVG and set its width and height. **HTML Structure** ```html <!DOCTYPE html> <html lang="en"> <head> <title>D3 Playground</title> <style> svg { background-color: #ccc; } rect { stroke: black; stroke-width: 0.5px; } </style> </head> <body> <script src="https://cdnjs.cloudflare.com/ajax/libs/d3/5.16.0/d3.min.js"></script> <svg></svg> <script>// Our code goes here</script> </body> </html> ``` Now we will add our initial JS code to set things up. ```js var data = [1, 2, 3, 4, 5]; var width = 800, height = 300; var margins = {top: 20, right: 20, bottom: 20, left: 20}; // Create the SVG canvas var svg = d3.select('svg') .attr('width', width) .attr('height', height); ``` Following diagram shows the key elements we will be having in our bar chart. ![d3-creating-bar-chart-ground-up-1](https://sahansera.dev/static/1889639235bd951248cb00f5ccc2c459/11d19/d3-creating-bar-chart-ground-up-1.png) ### Scales Now we let’s set a scale to our data across x and y axes. By using scales, we can define how each data element can be **_mapped_** to pixels on the screen. Let’s create our scale for **x** axis, ```js var xScale = d3.scaleBand() .domain([0, 1, 2, 3, 4]) .range([0, width - (margins.left+margins.right)]); ``` `scaleBand` is used when you have ordinal values for your axis. So, it will take any amount of ordinal values in the `domain` function and spit out values specified in the `range` function. The reason why we deduct the margins is that we need our bars to fit within the margins of our chart. We will now get values from 0px to 760px. And the scale for y axis, ```js var yScale = d3.scaleLinear() .domain([1, 5]) .range([margins.top, 100]); ``` Since our **y** axis is going to have quantitative continuous values, we choose the `scaleLinear` function to map our **y** values. In our dataset, the min is 1 and the max is 5. So we provide 1 and 5 as an array into the `domain`. Now our `range` is from 10px to 100px. Why 100px? Just bear with me on this one. Now let’s add some margins around in our SVG canvas. Otherwise, you will see clipping and other sorts of problems when you have data on your chart. For this we can use a SVG [group element <g></g>](https://developer.mozilla.org/en-US/docs/Web/SVG/Element/g) and a [transformation](https://developer.mozilla.org/en-US/docs/Web/SVG/Attribute/transform). ```js svg.append('g') .attr('transform', 'translate('+ margins.top +','+ margins.left +')') ``` This is clearly visualised in Mike Bostock’s [Observable notebook](https://observablehq.com/@d3/margin-convention). ![d3-creating-bar-chart-ground-up-2](https://sahansera.dev/static/6d7949b0ed42e251f411cc66a82ddf42/11d19/d3-creating-bar-chart-ground-up-2.png) Let’s add the rest of the code to draw the bars. ```js svg.append('g') .attr('transform', 'translate('+ margins.top +','+ margins.left +')') .selectAll('rect') .data(data) .enter() .append('rect') .attr('x', function(d, i) { return xScale(i); // We only need the index. i.e. Ordinal }) .attr('y', function(d, i) { return yScale(d); // We need to pass in the data item }) .attr('width', xScale.bandwidth()) // Automatically set the width .attr('height', function(d, i) { return yScale(d); }) .attr('fill', 'lightblue'); ``` In the above code, we have put our bars into a <g> element to group them so that we can transform them easily. Since we are using <code>translate</code> method, it will add 10px to x and y coordinates of each element we will be drawing inside it. The rest of the code works according to D3 <a href="https://sahansera.dev/d3-js-join-semantics/">data joins</a>.</g> Let’s run this and see, ![d3-creating-bar-chart-ground-up-3](https://sahansera.dev/static/5764a150876367773e92fb111bee7da3/11d19/d3-creating-bar-chart-ground-up-3.png) Our DOM looks likes this now, ```html <svg width="800" height="300"> <g transform="translate(20,20)"> <rect x="0" y="20" width="152" height="20" fill="lightblue"></rect> <rect x="152" y="40" width="152" height="40" fill="lightblue"></rect> <rect x="304" y="60" width="152" height="60" fill="lightblue"></rect> <rect x="456" y="80" width="152" height="80" fill="lightblue"></rect> <rect x="608" y="100" width="152" height="100" fill="lightblue"></rect> </g> </svg> ``` Oops, why is it like upside down? Remember that the SVG coordinates start from the top-left corner. So everything gets drawn relative to that point. Which means we need to change the range of our y values. Let’s fix this. ```js var yScale = d3.scaleLinear() .domain([1, 5]) .range([height - (margins.top+margins.bottom)*2, 0]); ``` Wait, what’s this calculation? We are basically setting the max and min values for our y range. In other words, we need our max y value to go up until 220px because we need to account for the height of the bar as well. ![d3-creating-bar-chart-ground-up-4.png](https://sahansera.dev/static/701626a121b324c8c70b4b125fd47953/11d19/d3-creating-bar-chart-ground-up-4.png) Almost there, but the heights look weird. That’s because we changed our y scale. Now, let’s fix the height. ```js .attr('height', function(d, i) { return height - (margins.top+margins.bottom) - yScale(d); }) ``` Remember, we need to deduct the top and bottom margins from the total height so that whatever the value we get from `yScale` will not exceed that boundary. Cool, now we are getting somewhere 😁 ![d3-creating-bar-chart-ground-up-5](https://sahansera.dev/static/cb8c46f67a6d469de1688d3994c8b813/11d19/d3-creating-bar-chart-ground-up-5.png) ### Axes D3’s axes API is pretty straight forward. You can utilise that to add horizontal and vertical axes to any graph. To wrap up our bar chart, let’s add the axes. **X axis** ```js svg.append('g') .attr('transform', 'translate('+ margins.left +','+ (height - margins.top) +')') .call(d3.axisBottom(xScale)); ``` **Y axis** ```js svg.append('g') .attr('transform', 'translate('+ margins.left +','+ margins.top +')') .call(d3.axisLeft(yScale)); ``` ![d3-creating-bar-chart-ground-up-6](https://sahansera.dev/static/2d02c59db6fa26f633d41f7e4b523a16/11d19/d3-creating-bar-chart-ground-up-6.png) Looks okay, but the axes are a bit off. So let’s fix that. ```js var margins = {top: 30, right: 30, bottom: 30, left: 30}; ``` Simple! When creating a graph in D3 always remember to use variables when possible so that you can easily fix if something’s not looking good. And we are done! ![d3-creating-bar-chart-ground-up-7](https://sahansera.dev/static/816f006aff0212a91a70dd6a877444df/11d19/d3-creating-bar-chart-ground-up-7.png) Great! and we are done ✅ ### References 1. [https://developer.mozilla.org/en-US/docs/Web/SVG/Element/g](https://developer.mozilla.org/en-US/docs/Web/SVG/Element/g) 2. [https://observablehq.com/@d3/margin-convention](https://observablehq.com/@d3/margin-convention)
sahan
383,376
The Eight Buffalo Rule: How to stop writing unreadable code
Eight Buffalo Buffalo buffalo Buffalo buffalo buffalo buffalo Buffalo buffalo. The eigh...
0
2020-07-05T13:49:21
https://dev.to/mattpocockuk/the-nine-buffalo-rule-how-to-stop-writing-unreadable-code-2hl4
beginners, tutorial, codenewbie, learning
# Eight Buffalo > Buffalo buffalo Buffalo buffalo buffalo buffalo Buffalo buffalo. The eight-buffalo sentence above is commonly cited as the longest grammatically correct sentence you can write with a single word. On the surface, it looks like nonsense. None of the words communicate any intent. You can't pick out which are the nouns, the verbs, or the adjectives. There appears to be no structure, just a string of Buffalo with an occasional capital letter. But the sentence is not nonsense, because you've been told it's not nonsense. There is *something* at the heart of these words that you must decipher. # Communicating Intent This might be how you feel when you look at 'unreadable' code. You know that the code does something, because the computer understands it. Like the eight Buffalo, it's grammatically correct. But the code is not communicating its intent to you. No clear mental pictures spring to mind. You have to pick through, word by word, to extract the meaning. Let's break down the buffalo, and see what they can teach us about writing readable code. # The buffalo are from New York Buffalo is a place - the city of Buffalo, in New York. Whenever a capital letter is used in the sentence, it's referring to the city. > **Buffalo** buffalo **Buffalo** buffalo buffalo buffalo **Buffalo** buffalo. From that, we can deduce that when 'Buffalo buffalo' are mentioned, it's talking about buffalo from the city in New York. Let's help ourselves out by exchanging 'Buffalo' for 'New York'. > New York buffalo New York buffalo buffalo buffalo New York buffalo. Alright, we're getting somewhere. The sentence is not completely decoded, but now we have a mental picture of a buffalo from New York, perhaps wearing a New York Nicks cap and eating a hot dog. In coding terms, we renamed a variable. We took 'Buffalo' and renamed it 'New York'. With that small change, we now have a mental model that we can use to help decode the rest of the sentence. # 'buffalo' means 'to bully' To buffalo someone means to bully them. TIL. Let's apply what we learned before and rename another variable. But which do we rename? > New York buffalo New York buffalo buffalo buffalo New York buffalo. Because of our mental model, we know that 'New York buffalo' makes grammatical sense on its own. So let's rename every 'buffalo' to 'bully' that isn't a part of the 'New York buffalo' pairing. > New York buffalo New York buffalo bully bully New York buffalo. Another mental model comes to mind: buffalo from New York bullying other New York buffalo. We've learned two things - what the New York buffalo are doing, and who they're doing it to. This time, we've renamed a function. A well-named function can not only clarify _what_ is being done, but also _why_ it's being done and _who_ it's being done to. Functions are the verbs of development, and thus are the most important to name correctly. # Adding separations But we're still not at full clarity. The sentence still feels mashed up - too many words and not enough punctuation. Let's add some joining words. > Buffalo from New York, whom other New York buffalo bully, bully other buffalo from New York. Suddenly, clarity. The separating words and punctuation help give a rhythm to the sentence. The relationships between the words are clearly explained, and each clause of the sentence has enough room to breathe. Here, we've modularised our sentence. The parts that relate to each other are grouped together. The individual parts are spaced out into separate sections, so you can focus on one piece at a time. # It's all buffalo to me The most interesting part of this exercise is that, once it's explained, this sentence becomes clearer: > Buffalo buffalo Buffalo buffalo buffalo buffalo Buffalo buffalo. Imagine you did the coding equivalent of writing this sentence. To you, it might seem perfectly clear. You don't need the renamed variables, renamed functions, and modularisation to understand your code's intent. After all, the code's intent _is_ your intent. Once in a while, take a moment and step back. Consider whether you're writing buffalo. The moment you notice it, your code will improve.
mattpocockuk
383,385
Escaping the tyranny of stack overflow
Hi guys. As someone who has recently entered the world of coding, I have used stack overflow like any...
0
2020-07-05T14:07:39
https://dev.to/mohammadpishdar/escaping-the-tyranny-of-stack-overflow-56eh
Hi guys. As someone who has recently entered the world of coding, I have used stack overflow like anyone else to ask questions. At first, I was so happy and excited that I'm about to be a member of a community of like-minded people where I can get insights from professionals whenever I need help but it didn't last long until I have realised what I perceived at first as a community of friendly coders that are ready to help each other and those who are new to the field is in fact nothing more than a highly hierarchical society when those so-called "reputable" users play the role of Gods and often punish us newbies with their ultimate weapon "down votes" or ridicule and belittle us for asking questions that they too stupid to waste their precious time. I have tolerated such behaviours while I was constantly bombarded with harsh down votes and unfriendly comments mainly because as a newbie everyone tells you stack overflow is the only place you can get help for your coding questions and sometimes something that may seem like a stupid thing to an experienced coder may give a newbie like me hours and hours of headache and confusion and may even lead to so many people to leave their pursue of learning how to code, until just yesterday I have noticed they have just banned my account from asking questions which is not only unfair but is in direct contrast with the ultimate philosophy of such communities which is to help each other to become better coders. That's why I said enough is enough, so I decided to search for a community where all members have the same basic rights and respect no matter how much experience they have and where newbies like me can count of more experience fellows to seek answers to their questions. I hope this will be the place for me to stay and develop into a better coder for the years to come. I'm not so sure how the things are working here, so I appreciate if anyone reading this can tell me if there is a special place for inexperienced coders like me to ask their questions. Thank you for taking time to read this and hopefully I can become a better coder and be able to help others in the future.
mohammadpishdar
383,511
When to choose NoSQL over SQL?
The agenda of this blog is simple. We’ll discuss various parameters that we keep in mind while decidi...
0
2020-07-05T17:11:33
https://dev.to/ombharatiya/when-to-choose-nosql-over-sql-536p
sql, nosql, database, architecture
The agenda of this blog is simple. We’ll discuss various parameters that we keep in mind while deciding a perfect database for our Application Service. In terms of data engineering, data pressure is the ability of the system to process the amount of data at a reasonable cost or a reasonable time. When one of those dimensions is broken, that’s a technology trigger and new inventions happen that result in new data technologies. In simple terms … > SQL is not obsolete, it’s just that now we have a different choice. Before we jump up to comparing [SQL](https://en.wikipedia.org/wiki/SQL) and [NoSQL](https://en.wikipedia.org/wiki/NoSQL) databases, let’s take some time to appreciate the fact that SQL has been long into the industry (over 30+ years) and still has a good place in the modern application development environment. ## **Comparison Time …** 🤞 1. **SQL:** Optimized for Storage **NoSQL:** Optimized for Compute/Querying 2. **SQL:** Normalized/relational **NoSQL:** Denormalised(Unnormalized)/Hierarchical 3. **SQL:** Table based data structure **NoSQL:** Depending on DBs, the data structures are … ★ Key-Values(DynamoDB, Redis, Voldemort) ★ Wide-column i.e. containers for rows(Cassandra, HBase) ★ Collection of Documents(MongoDB, CouchDB, DynamoDB) ★ Graph Structures(Neo4J, InfiniteGraph) 4. **SQL:** Ad hoc queries **NoSQL:** Instantiated views 5. **SQL:** Scale Vertically & Expensive. Can Scale Horizontally but challenging & time-consuming **NoSQL:** Scale Horizontally & Cheap 6. **SQL:** Fixed schema, altering requires modifying the whole database **NoSQL:** Schemas are dynamic 7. **SQL:** Good for OLAP **NoSQL:** Good for OLTP at scale 8. **SQL:** ACID(Atomicity, Consistency, Isolation, Durability) properties **NoSQL:** BASE(Basically Available, Soft state, Eventual consistency) properties ## **When to choose NoSQL?** 👍 For our application service, when it comes down to ... ✔ Well-known and well-understood types of access patterns ✔ Want simple queries ✔ Not much data calculation involved ✔ Have a common business process ✔ OLTP apps If this is true, then NoSQL is a perfect Database and would be most efficient. We have to structure the data model specifically to support the given access pattern. ## **When NOT to choose NoSQL?** 👎 If our application service has the requirements to support ... ✔ Ad-hoc queries. e.g. bi analytics use case or OLAP application ✔ May require “reshaping” the data ✔ Complex queries, inner joins, outer joins, etc. ✔ Complex value calculations **So in brief, for our application service, if we understand the access patterns very well, they’re repeatable, they’re consistent, and scalability is a big factor, then NoSQL is a perfect choice.** _PS: Mature developers don’t use the word “flexible” for NoSQL databases. There is a difference in being dynamic and flexible. Data model design is an intelligent engineering exercise in NoSQL databases._ What your opinion over my discussion up here? Why do you choose NoSQL over SQL? ... Thanks for reading this blog! Add a ❤ if you liked the comparison. Leave a comment below if you have any questions/feedback. I'm gonna write a **Series on DynamoDB** here, [follow me for updates](https://dev.to/ombharatiya). More About Author: [Om Bharatiya](https://www.linkedin.com/in/ombharatiya) Happy Coding <3
ombharatiya
383,538
Tell me what is / why MVC ?
I know, MVC stands for Model View Controller. Its neither a technology nor a programming language. It...
0
2020-07-05T17:58:59
https://dev.to/manishfoodtechs/tell-me-what-why-mvc-2ggj
help, discuss
I know, MVC stands for Model View Controller. Its neither a technology nor a programming language. Its an architectural pattern commonly used for developing user interfaces that divides an application into three interconnected parts. ... ***Is it necessary? Without it any performance issue?***
manishfoodtechs
383,544
How to create a blog using Laravel and Voyager?
I've just published my very first video course on how to build a blog using Laravel and Voyager. Tur...
0
2020-07-05T18:11:16
https://dev.to/bobbyiliev/how-to-create-a-blog-using-laravel-and-voyager-jg
laravel, linux, php
I've just published my very first video course on how to build a blog using Laravel and Voyager. Turned out to be a lot more challenging than I expected! The quality ended up not as good as I imagined 😅 but was a great learning experience! I went through the process of setting up a server, installing all of the required services like Nginx, PHP, MySQL, setting up VS Code, choosing an HTML template, and setting up Laravel and Voyager! {% youtube RrhpbFCOlZ0 %}
bobbyiliev
383,563
Things I learned while building my side project
Gitify lets you interact with Git from browser extension.
0
2020-07-05T19:25:15
https://dev.to/akshay090/things-i-learned-while-building-my-side-project-3nil
showdev, github, extension, githunt
--- title: Things I learned while building my side project published: true description: Gitify lets you interact with Git from browser extension. tags: showdev, github, extension, githunt cover_image: https://dev-to-uploads.s3.amazonaws.com/i/yyeq8krv82vifcyaymic.png --- **TLDR :** I build this project called gitify, by which you can interact with Git from browser extension. Check it out and give it a ⭐ if you like it. {% github Akshay090/gitify %} Few months back I had discussed this idea of a browser extension with my friends from which I could clone and open a GitHub repository in VsCode instantly, as I like to check out projects form GitHub and it would be cool to interact with Git from browser. Then after procrastination for months I decided to work on this, coincidentally there was also an [online hackathon](https://github.com/Akshay090/gitify) that weekend by MLH. Trust me if it wasn't for the hackathon I doubt if I would have ever started this project. That feeling to make a MVP in limited time is truly something. I started out by listing the basic features I needed to implement : Git Clone, Open in VsCode. Hmm.. why not add Git Push and Pull, this covers most of the Git commands I use. A browser extension alone can't communicate with Git, I also had to implement a server, this would run on the user system. ## Building Browser Extension The GitHub UI has changed recently. So I decided to not to go with the approach of injecting buttons into page and keep everything in browser extension Popup. I decided to go with this starter repo : [web-extension-starter](https://github.com/abhijithvijayan/web-extension-starter), this is a really good starter project for building cross browser extension. I starter working with the react-typescript setup in it. I was fairly new to both TypeScript and React Hooks, working with them was a really good learning experience. TypeScript can be annoying but trust me it's really worth it. The most helpful and annoying tool was eslint. If it wasn't for eslint my Hooks code would have looked completely different. In the begining I would frequently use ```// eslint-disable-next-line react-hooks/exhaustive-deps ``` I took some time to understand React Hooks, read this article by [Dan Abramov](https://overreacted.io/a-complete-guide-to-useeffect/), tried to solve the bugs where the Effect would fire multiple times and finally managed to work without using the exhaustive-deps. React Hooks are really easy to understand but difficult to master. They feel like black magic sometimes. I had to use this [useEffectDebugger](https://github.com/Akshay090/gitify/blob/fd3285391da652b5ad1ebaa1d05fa0986cef29f0/source/utils/index.ts#L95) to figure out some bugs. ## Building the Server Recently I started learning Golang, totally on a whim as I saw it on Coursera. I made some notes on it too, you can [find it here](https://github.com/Akshay090/golang-notes). So as you have guessed, I decided to write the server in Golang, as Golang generates binary it would be easy to distribute and install. I used this [simple-go-server](https://github.com/enricofoltran/simple-go-server) as a starter. Initially I used to perform the git operation using [go-git](https://github.com/go-git/go-git) which is A Git implementation in pure Go, but later on I switched to os/exec. To make it easy to use for others I had to convert this server code to something which can run in background so that it won't be too annoying. I came accross this project : [kardianos/service](https://github.com/kardianos/service). I tried out the example code and it worked perfectly in my system, but apparently I didn't know how to convert my server code to a system service, as there were no proper blog post on how to use it, with windows in particular.While researching I made [this gist](https://gist.github.com/Akshay090/d4f2e0f91a99b516d9d638a1e1a60a0d) of projects which use kardianos/service. I decided to switch to other options, like system tray. To implement the System tray I choose [trayhost](https://github.com/cratonica/trayhost), as I found it comparatively faster than the alternative [systray](https://github.com/getlantern/systray). Then I added an icon to the generated exe by refering [this repo](https://gitlab.com/gozoo/rc-demo). I used [gopherize.me](https://gopherize.me/) to generate the logo/icon, you should definitely check it out. ## Releasing with GitHub actions. I used [anton-yurchenko/git-release](https://github.com/anton-yurchenko/git-release) to Publish a GitHub Release, it publishes assets and works along with a Changelog.md file making the relases descriptive. The [gitifyServer](https://github.com/Akshay090/gitifyServer) runs the GitHub action in a windows runner and the one in [gitify](https://github.com/Akshay090/gitify) repo runs in ubuntu runner. This project was really fun to build, it currently works on windows only as I don't have either mac or linux to test on them. If you would like to add support it would be really appreciated.
akshay090
397,132
Minimalist Roadmap to Becoming a Full-Stack Developer
I fear not someone who has practiced 10,000 kicks once, but I fear someone who has practiced one...
0
2020-07-14T12:31:31
https://dev.to/ericdouglas/minimalist-roadmap-to-becoming-a-full-stack-developer-259b
javascript, react, node, mongodb
> I fear not someone who has practiced 10,000 kicks once, but I fear someone who has practiced one kick 10,000 times. > > Bruce Lee When we are starting to learn about web development, we really struggle to find a clear and feasible path to guide us on this journey. Although we have a lot of great schools that certainly will help to conquer this challenge, they might be really expensive. We have an awesome alternative to this: Udemy courses! They contain a lot of useful content and are really affordable. For me, this is the absolute sweet spot in education: students can access the content paying a small amount, and instructors receive their very deserved reward for investing (a lot of) time preparing the courses. I truly love Udemy courses for this reason ❤. But one thing we do not have in Udemy is a roadmap to guide new students about what to study and in which order. So with this roadmap below, you can without doubts become a professional developer, and after finish those courses, you will have enough knowledge to decide for your own your next steps 😉 Good luck on your journey! > **PROTIP**: invest some time finding/developing your learning methodology. ## HTML & CSS - Udemy: [Modern HTML & CSS From The Beginning (Including Sass)](https://www.udemy.com/course/modern-html-css-from-the-beginning) ## Git - FreeCodeCamp: [Git and GitHub for Beginners - Crash Course](https://www.youtube.com/watch?v=RGOj5yH7evk) ## JAVASCRIPT - Udemy: [The Modern Javascript Bootcamp Course](https://www.udemy.com/course/javascript-beginners-complete-tutorial) ## REACT - Udemy: [Complete React Developer (w/ Redux, Hooks, GraphQL)](https://www.udemy.com/course/complete-react-developer-zero-to-mastery) ## NODE.JS - Udemy: [Node.js API Masterclass With Express & MongoDB](https://www.udemy.com/course/nodejs-api-masterclass) ## MONGODB - Udemy: [MongoDB - The Complete Developer's Guide](https://www.udemy.com/course/mongodb-the-complete-developers-guide)
ericdouglas
383,657
Create React Doc: A Markdown Doc Site Generator For React
Markdown doc site generator for React
0
2020-07-05T19:52:43
https://dev.to/muyunyun/create-react-doc-write-markdown-site-with-no-build-configuration-hk7
markdown, blog
--- title: Create React Doc: A Markdown Doc Site Generator For React published: true description: Markdown doc site generator for React tags: ['markdown', 'blog'] cover_image: https://user-images.githubusercontent.com/19354791/86540722-06202600-bf3a-11ea-9fc0-1d7aa5f11cad.png --- # Create React Doc [Create React Doc](https://github.com/MuYunyun/create-react-doc) is a markdown doc site generator for React. You can write markdown sites or blogs with no build configuration just like create-react-app. ## Features * Write markdown docs with no build configuration. * `Lazy load` for markdown data. * Generate menu autoly based file directory. * Support deploy to [GitHub Pages](https://pages.github.com/). ## Sites built with create-react-doc ![](https://user-images.githubusercontent.com/19354791/86540953-577ce500-bf3b-11ea-8dc5-1728d08d46cc.png) * [muyunyun's blog](http://muyunyun.cn/blog) <sub>[(github)](https://github.com/MuYunyun/blog) * [create react doc](http://muyunyun.cn/create-react-doc) ## Quick Overview ```bash npx create-react-doc my-doc npm install && cd my-doc npm start ``` Then open [http://localhost:3000/]() to see your doc. When you're ready to deploy to production, create a minified bundle with npm run build. ## Usage [create-react-doc](https://github.com/MuYunyun/create-react-doc) is very easy to use. You don’t need to install or configure tools like webpack or Babel. They are preconfigured and hidden so that you can focus on the code. You only install it as a package so that you can create your own website or blog. You may choose one of the following methods: ### npx ```bash npx create-react-doc my-doc ``` ### npm ```bash npm init create-react-doc my-doc ``` ### yarn ```bash yarn create create-react-doc my-doc ``` Once the installation is done, you can open your project folder: ``` npm install && cd my-doc ``` Inside the newly created project, you can run some built-in commands: ### `npm start` or `yarn start` Runs the doc in development mode. Open [http://localhost:3000]() to view it in the browser. The page will automatically reload if you make changes to the code. ### `npm run build` or `yarn build` Builds the doc for production to the build folder. It correctly bundles React in production mode and optimizes the build for the best performance. The build is minified and the filenames include the hashes. Your doc site is ready to be deployed. ### `npm run deploy` or `yarn deploy` The doc'll deployed to GitHub Pages rely `user`, `repo` in [config.yml](https://github.com/MuYunyun/create-react-doc#configyml) ## config.yml There is some configuration provided for you to adjust doc sites. ```bash # Site title title: Time Flying # Witch files to show as Menu ## you can also set detailed dir, such as BasicSkill/css menu: React,BasicSkill,Algorithm ## set init open menu keys menuOpenKeys: /BasicSkill # Github ## if you want to show editing pages on github or deploy to GitHub Pages, you should config these arguments. user: MuYunyun repo: blog branch: master # the default value of branch is master deploy_branch: gh-pages # which branch to deploy.(default: gh-pages) # publish: # if you want upload to gitlab or other git platform, you can set full git url in it # Available values: en| zh-cn language: en ``` ## Advanced Usage * If you not want to show some private files, you can set it in `.gitignore`, and the file'll be ignored to show in the docs. It'll provide more features in the future, looking forward to your comment [there](https://github.com/MuYunyun/create-react-doc/issues/new)! Thank your read very much.
muyunyun
383,695
Create a JavaScript library. Add callbacks
And here is a new part of creating a library of modal windows in JavaScript. This time we are impleme...
7,207
2020-07-07T10:42:03
https://dev.to/alexandrshy/create-a-javascript-library-add-callbacks-2e64
javascript, typescript, webdev, tutorial
And here is a new part of creating a library of modal windows in JavaScript. This time we are implementing two small improvements. First, we'll add the ability to use callbacks to the configuration. And secondly, we'll improve the keyboard control. By tradition, I'm sharing a video version with you, for those who want to see how I wrote it 🎬 {% youtube biGhmm0ly5w %} ## Callback As per [MDN](https://developer.mozilla.org/en-US/docs/Glossary/Callback_function): "A callback function is a function passed into another function as an argument, which is then invoked inside the outer function to complete some kind of routine or action". A small use case: ```js const addition = (a, b) => a + b; const multiplication = (a, b) => a * b; const count = (a, b, callback) => callback(a, b); console.log(count(10, 20, addition)); // 30 console.log(count(10, 20, multiplication)); // 200 ``` In our example, the first two functions `addition` and` multiplication` simply perform a mathematical action with two parameters and return the result of the calculation. But the count method takes three parameters, the first two are numbers, and the third is the action that you need to do with numbers. This is the callback. In this context, such an example may seem redundant. All the convenience of callbacks is revealed when we need to wait for any action or result And this perfectly shows the situation that can occur when using a library with `hasAnimation`. If we need to perform some kind of functionality not immediately after clicking on the button that will open the modal window, but only after it is fully opened, callbacks will help us. Let's add this code: ```js constructor({ ... onOpen = () => {}, onClose = () => {}, beforeOpen = () => true, beforeClose = () => true, }: ConfigType) { this.$modal = document.querySelector(selector); this.onOpen = onOpen; this.onClose = onClose; this.beforeOpen = beforeOpen; this.beforeClose = beforeClose; ... } close(event?: Event) { const isContinue = this.beforeClose(event); if (!isContinue) return; ... this.preparationClosingModal(event); } preparationClosingModal(event?: Event) { if (this.hasAnimation) { const handler = () => { ... this.onClose(event); this.$modal?.removeEventListener('animationend', handler); }; this.$modal?.addEventListener('animationend', handler); } else { ... this.onClose(event); } } ``` For the open method, we'll need to do the same with `this.onOpen` and` this.beforeClose`. The `this.onOpen` and` this.onClose` methods play the role of events that report the corresponding action of the modal window. Such methods will be called as soon as the animation ends at the modal window (or immediately if the animation is disabled). Such methods are conveniently used, for example, to send analytics in order to track interactive user actions. The `this.beforeOpen` and` this.beforeClose` methods, as you may have noticed, have a slight difference, they should return a boolean value. This is done intentionally to add flexibility in window configuration. For example, it is convenient to use such methods to block a modal window until the animation is completed (if opening animation takes considerable time, this may be necessary), or to block the state of the window until a certain action is taken by the user (such as filling out a feedback form). As you can see, we added just a few methods, but significantly expanded the configuration options. ## Keyboard control The main idea of ​​implementation is to prepare the library for the final parts, which will implement support for accessibility and convenient keyboard control. This time we'll add one small action, which for me personally is very convenient. This closes the modal window by clicking on `Esc`. And if you try to look for solutions to track `Esc`, you'll most likely see this code: ```js document.addEventListener('keyup', function (event) { if (event.keyCode === 27) console.log('Esc button was pressed'); }); ``` And then one interesting embarrassment happened. If you watched my video, you could see that to determine which key was pressed, I used [keyCode](https://developer.mozilla.org/en-US/docs/Web/API/KeyboardEvent/keyCode) ```js onKeydown(event: KeyboardEvent) { if (event.keyCode === KEY_CODE.ESC) this.close(); } ``` But if you look at the code now, you'll see another solution. It happened because `keyCode` has been the standard way to determine the type of key pressed for many years. This has great support for browsers. But the fact is that now this is deprecated and it is no longer recommended to use it. `keyCode` was deprecated because in practice it was "inconsistent across platforms and even the same implementation on different operating systems or using different localizations." The new recommendation is to use [key](https://developer.mozilla.org/en-US/docs/Web/API/KeyboardEvent/key) or [code](https://developer.mozilla.org/en-US/docs/Web/API/KeyboardEvent/code). However, there are also minor difficulties, the fact is that `KeyboardEvent.key` is implemented differently in different browsers. For example, in IE11 `KeyboardEvent.key` uses `Esc` rather than `Escape` for the corresponding keyboard button, because it was implemented before the specification was completed. More detailed browser support can be found [here](https://caniuse.com/#search=KeyboardEvent.key). This will look like an implementation with compatibility support for older browsers ```js export const KEY = { ESC: 'Esc', ESCAPE: 'Escape', CODE: 27, } addEventListeners() { document.addEventListener('keyup', this.onKeyup); } removeEventListeners() { document.removeEventListener('keyup', this.onKeyup); } /** * Keyboard press handler * * @param {KeyboardEvent} event - Event data */ onKeyup(event: KeyboardEvent) { const key = event.key || event.keyCode; if (key === KEY.ESCAPE || key === KEY.ESC || key === KEY.CODE) this.close(event); } ``` However, we can leave a more compact form, since we don't need support on so many old browsers ```js /** * Keyboard press handler * * @param {KeyboardEvent} event - Event data */ onKeyup(event: KeyboardEvent) { if (event.key === KEY.ESCAPE || event.key === KEY.ESC) this.close(event); } ``` Now, with the modal window open, we have a handler for clicking the Esc key on the keyboard. This handler calls the `close` method and after closing the modal window we remove the click handler. You can see the complete solution in the repository. {% github Alexandrshy/keukenhof %} ___ Next time we will consider a very extensive topic of accessibility when working with modal windows. Subscribe, it'll be interesting! See you soon 👋
alexandrshy
383,703
How to Add a favicon to the site in Rails 6 using Webpacker
In Rails 6, Adding an icon to the HTML tab is very easy with 3 simple steps. 1) Add an image 2) Ref...
0
2020-07-06T00:18:03
https://dev.to/kattak2k/adding-a-favicon-to-your-site-using-webpacker-in-rails-6-2m2h
ruby, webpack, rails, html
In Rails 6, Adding an icon to the HTML tab is very easy with 3 simple steps. 1) [Add an image](#add) 2) [Reference an image](#reference) 3) [Link an image to HTML head](#link) For the basic understanding on Webpacker, you may refer the useful guide by Chris Oliver ([Webpacker Setup](https://gorails.com/episodes/using-webpack-in-rails-with-webpacker-gem)) ###Here is how our directory structure would look like. ``` app |-controllers |-javascript |-images |-brand_icon.png |-brand_icon.ico |-packs |- application.js |-stylesheets |- applicaiton.scss ``` ### 1) Add an image <a name="add"></a> The images directory will hold all the images that we link in the project. We can add a types *.png, .ico, or .jpeg*, but I'd prefer *.png* as it supports better colors. Let us save a home image as brand_icon.png to app/javascript/images/* ![Brand_icon](https://img.icons8.com/fluent/48/000000/home.png "Brand Icon") ### 2) Reference an image <a name="reference"></a> Declare a constant in *packs/application.js* file, to refer all the images in *javascript/images* ```javascript const images = require.context('.../images', true) ``` Now, with this reference, we can embed all the images in our HTML with a pack tag. ```erb <%= image_pack_tag 'example.png' %> ``` ### 3) Link an image to HTML head <a name="link"></a> Don't forget to link the JavaScript pack in Rails views using the javascript_pack_tag helper. Now finally, embed the newly downloaded home_icon in HTML view with a helper method favicon_pack_tag. ```erb <!DOCTYPE html> <html> <head> <%= javascript_pack_tag 'application', 'data-turbo-links-track': 'reload'%> <%= favicon_pack_tag 'brand_icon.png' %> </head> <body> </body> </html> ``` After compiling, the HTML would look like this. ```html <link rel="shortcut icon" type="image/x-icon" href="pack/media/images/brand-icon-a3423sf.png"> ``` As we can see the icon is being pointed to the image in the pack directory. ###Result ![home_tab_icon](https://user-images.githubusercontent.com/53492744/86545305-f681ec80-befb-11ea-8966-b36ccfa29b29.png) That's all we need, CHEERS!!
kattak2k
383,709
AWS 🔒 How to restrict access by IP
Hi there! In today's post, I would like to show you how you can restrict access to your AW...
0
2020-07-05T22:09:38
http://securityblog.cloud/aws-how-to-restrict-access-by-ip.html
aws, security, iam, policy
## Hi there! In today's post, I would like to show you how you can restrict access to your AWS Account. Very often companies use static IP addresses to access the Internet. So if you know that access to your AWS account has to happen from specific IP, why allow it from the whole Internet. Here is a logic schema of how we are going to make restriction: ![logic schema](https://dev-to-uploads.s3.amazonaws.com/i/5sc5minben5lxr9i8huq.png) ⚠The most important part is an **IAM policy** that will **enforce our restriction**. The policy denies any user's actions made from untrusted IP. To make so, we have to create a condition and specify two keys: * `aws:SourceIp` * `aws:ViaAWSService` By the first one, we allow access from our IPs, by the second one we allow AWS Services to access our resources without the restriction.  Your policy may look like it: ``` yaml { "Version": "2012-10-17", "Statement": { "Effect": "Deny", "Action": "*", "Resource": "*", "Condition": { "NotIpAddress": { "aws:SourceIp": [ "XXX.XXX.XXX.0/24", "YYY.YYY.YYY.0/24" ] }, "Bool": {"aws:ViaAWSService": "false"} } } } ``` The good way to apply our restriction is to use IAM users' groups. IAM users groups usage is a good practice to handle permissions. But our approach will work with a single user as well. Depends on your case you may or may not use IAM groups. So next, create a group, attach a policy with necessary accesses and with IP restriction. ![Create a Group](https://dev-to-uploads.s3.amazonaws.com/i/j76yb4c0iutgsia4ljwb.gif) Now even if API keys or a user's credentials will be compromised, an attacker has to avoid one more security mechanism in your AWS Account. Bye!👋 *Photo by Markus Spiske on Unsplash*
vitali
384,002
Data Types In Javascript
There are 3 types of data types in Javascript: primitive and composite and data types. Primitive dat...
0
2020-07-06T02:23:11
https://dev.to/aidoskashenov/data-types-in-javascript-4ob9
javascript
There are 3 types of data types in Javascript: primitive and composite and data types. Primitive data types are simple types like "Strings", Number, Boolean, _undefined_ and _null_. Composite data are Arrays, Objects and Functions. Primitive data types are those that can hold only one type of value and cannot be subject to use of a methods, whereas objects and arrays can hold multiple data units and all the methods and functions are using objects as their arguments. Everything is an Object in Javascript and that's why Javascript is called an _Object Oriented Language_ However, some of the sources distinguish 3 types of data separating _undefined_ and _null_ as a "special" data type. These two types can be confusing, but to put it simply, _undefined_ means that a variable was never defined in the code, and null means that there is no value.
aidoskashenov
384,230
How Can You Use Elm to be a Better Front End Programmer? Interview with Richard Feldman
Richard Feldman, the author of "Elm in Action", got interviewed by GOTO about Elm. He said Elm won't...
0
2020-07-06T07:15:30
https://dev.to/ancatrusca1/how-can-you-use-elm-to-be-a-better-front-end-programmer-interview-with-richard-feldman-39hp
functional, frontend, elm
Richard Feldman, the author of "Elm in Action", got interviewed by [GOTO about Elm](https://gotopia.tech/bookclub/episodes/upgrade-your-frontend-game-be-an-elm-wizard). He said Elm won't take over the world but sure is a fun language to use that compiles in less than 4 seconds and will definitely change your perspective on things even if you won't end up programming in Elm. Richard and Thomas went over the benefits of using Elm in a large organization, one of which is actually moving away from the dependencies nightmare. They also give some advice on how to use Elm in Action to learn Elm. [YouTube Video](https://youtu.be/X2e_zZa5OnE) [Website link](https://gotopia.tech/bookclub/episodes/upgrade-your-frontend-game-be-an-elm-wizard) if you'd rather read the whole thing
ancatrusca1
384,238
DEV.to Lookalike App with React
My First Project with React
0
2020-07-06T07:29:34
https://dev.to/gerwinjonathan/dev-to-lookalike-app-with-react-31ao
react, beginners, api, webdev
--- title: DEV.to Lookalike App with React published: true description: My First Project with React tags: react, beginners, api, webdev cover_image: https://dev-to-uploads.s3.amazonaws.com/i/0bpm70snj6dmjd4xjcp0.PNG --- ## Introduction Today, I would like to post my very first project on DEV.to. This project is called __DEV.to lookalike app__. The purpose of this project is to __implement API on React__. ## Results Here are the example of my project so far. * Get Articles from API ![Alt Text](https://dev-to-uploads.s3.amazonaws.com/i/0bpm70snj6dmjd4xjcp0.PNG) * Get Detail Articles from API ![Alt Text](https://dev-to-uploads.s3.amazonaws.com/i/ci2eknpzlj68zhmsma5x.PNG) ## Table Of Contents * [Preparation](#preparation) * [Component](#component) * [How it Works](#how-it-works) * [Code](#code) ### Preparation <a name="preparation"></a> __First thing first__. * Install __React App__ with __npm__. ```npm i create-react-app <name_project>``` * Install Library on React. (I use React Hooks, React Icons, Reactstrap (Bootstrap), React LazyLoad, React Markdown) ```npm i bootstrap reactstrap react-lazyload react-icons react-markdown --save``` ### Component <a name="component"></a> There are 3 components such as: __API__, __Menu__, and __Articles__. * API You can find API in settings and put it into your app. Locate the API in separate folder called ```api```. * Menu You can find Menu in headers in ```component``` folder. There are 2 menus, ```header``` and ```sidebar```. * Article You can find 2 group of articles, called ```ArticleComponent``` and ```DetailArticleComponent```. ### How it Works <a name="how-it-works"></a> The first step is making Card component. You can find Card on reactstrap. Use props in CardComponent to pass the value. The second step is make fetch data from API. useState and useEffect are important to fetch the data from API. Once it done, add map to iterate every value on article. The third step make them available in App.js by import the page and pass them into App.js. Finally, make the same procedure for retrieve the detail. I use ID in every articles for detail. Do the same thing. ### Code <a name="code"></a> For details, you can visit my repository. [Demo Code](https://github.com/gerwinjonathan/DEV.to-API-with-React.git) I hope this is just the beginning of my projects. Looking for next features.
gerwinjonathan
384,275
18 Essential Videos That Fundamentally Shaped My Understanding of JavaScript
Learning JavaScript is a wild, tempestuous journey. With so much to learn, it is difficult to keep up with the times. Here are 18 videos I consider to be "essential" in learning JavaScript at a deeper level. Each of these videos once sparked a "eureka moment" within me that ultimately helped in piecing together the JavaScript puzzle.
7,642
2020-07-08T11:29:03
https://dev.to/somedood/18-essential-videos-that-fundamentally-shaped-my-understanding-of-javascript-3ib
javascript, node, learning
--- series: "Some Dood\'s Curated List of Essential Learning Materials" title: "18 Essential Videos That Fundamentally Shaped My Understanding of JavaScript" published: true description: "Learning JavaScript is a wild, tempestuous journey. With so much to learn, it is difficult to keep up with the times. Here are 18 videos I consider to be \"essential\" in learning JavaScript at a deeper level. Each of these videos once sparked a \"eureka moment\" within me that ultimately helped in piecing together the JavaScript puzzle." cover_image: "https://dev-to-uploads.s3.amazonaws.com/i/dvi7ktu6s10mqfdb7j7e.png" tags: javascript, node, learning --- Learning JavaScript is a wild, tempestuous journey. When I first studied the language four years ago, I wouldn't have known how long this journey would be. I wouldn't have expected how my first few lines of humble JavaScript would eventually become my crucial stepping stone into the world of web development. I owe a vast majority of my current knowledge to the pioneers who walked this journey before me. Their ideas and innovations paved the path that allowed me to stand and build on the shoulders of giants. A few weeks ago, I wrote about [facing the Unknown with an inquisitive sense of "constructive stupidity"](https://dev.to/somedood/the-key-to-effective-learning-is-constructive-stupidity-1a6k), where I advocated for acknowledging and accepting gaps in knowledge as a means of effective learning. With so much to learn about JavaScript—and web development in general—I cannot imagine how intimidating the Unknown would be for those who are new to the language as I once was, hence this article. Below is a curated list of 18 videos and conference talks that have fundamentally shaped my understanding of JavaScript. Without these brilliant individuals making their knowledge free and available for all, I wouldn't be where I am now in my JavaScript journey. For each of these videos, I have had a "eureka moment" that helped me piece together the bigger picture when I first watched it. I definitely required further research, but everything started to "click" from that point on. It was the missing piece to the puzzle, so to speak. Through this list of "essential videos", I hope to nudge JavaScript developers in the right direction as the pioneers have done to me. > **NOTE:** Not all of the videos below are necessarily targeted towards beginners. This list tackles multiple aspects of the JavaScript ecosystem: language features, Node.js, runtime internals (such as the event loop), performance, optimizations, security, and some ES6 features. # What the heck is the event loop anyway? [Philip Roberts] {% youtube 8aGhZQkoFbQ %} No list of "essential JavaScript videos" can ever be complete without an exploration into the legendary event loop. In this famously approachable talk, Philip Roberts sets up the foundational groundwork required to dive into the rabbit hole that is the event loop. # Further Adventures of the Event Loop [Erin Zimmer] {% youtube u1kqx6AenYw %} Now that we're equipped with the basic intuition, Erin Zimmer's talk goes deeper into the technical details of the event loop without losing sight of the approachable narrative. Through her excellent visualizations, Zimmer explains the underlying intermediate steps during each iteration of the event loop. # In The Loop [Jake Archibald] {% youtube cCOL7MC4Pl0 %} In this talk, Jake Archibald makes the literal notion of a "loop" as the centerpiece of his event loop visualizations. Setting out to remove UI jank in the browser, he unravels the mysteries of the render loop, the [`globalThis.setInterval`](https://developer.mozilla.org/en-US/docs/Web/API/WindowOrWorkerGlobalScope/setInterval) timers, and the [`window.requestAnimationFrame`](https://developer.mozilla.org/en-US/docs/Web/API/window/requestAnimationFrame) hook. # Everything You Need to Know About Node.js Event Loop [Bert Belder] {% youtube PNa9OMajw9w %} With all the confusion about the true nature of the event loop, Bert Belder debunks some unfortunately common misconceptions that arise from _not-so-accurate_ diagrams and visualizations. # The Node.js Event Loop: Not So Single Threaded [Bryan Hughes] {% youtube zphcsoSJMvM %} The term "single-threaded" is often haphazardly thrown around when talking about JavaScript. In this talk, Bryan Hughes demonstrates how the language itself may be single-threaded, but despite that, its overall runtime is certainly not. On a related note, he discusses the implications of Node.js' finite thread pool from a performance standpoint. # Memory: Don't Forget to Take Out the Garbage [Katie Fenn] {% youtube H_BYkp5sfpM %} > _"Memory is a finite resource. We can't add more memory into our customer's machines. We can only use it, discard it, and then reuse it. We have to be good shepherds of what is given to us because we can't get any more."_ Although the JavaScript engine's internal garbage collector has made memory management a trivial topic, Katie Fenn reminds us that negligence towards memory usage has disastrous consequences when it comes to application performance and user experience. Throughout her various examples during the talk, she demostrates how easy it is to lose track of unused variables, lingering event listeners, and rogue timers. # Broken Promises [James Snell] {% youtube XV-u_Ow47s0 %} > _"In a promise chain, the only place you should have synchronous code is in the final `Promise#then` handler."_ The introduction of [ES6 promises](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise) has revolutionzed the semantics of asynchronous programming in JavaScript. However, with greater power comes a greater surface of misuse. In this talk, James Snell walks through the plethora of ways promises can, will, and have been misused. From mixed callbacks to redundant wrappers, this is a critically essential presentation on mastering promises. # You Don't Know Node [Samer Buna] {% youtube oPo4EQmkjvY %} > _"Most educational content about Node teaches Node packages... but those Node packages actually wrap the Node runtime. And when you run into problems, you're most likely running into problems in the [Node runtime] stack itself. So if you don't know the Node runtime, you're in trouble."_ With so many NPM packages abstracting away the core of Node.js, Samer Buna takes a step back to invite us to think more carefully about our familiarity with Node fundamentals. In his Q&A-style talk, Buna shares some tidbits of knowledge and trivia about the internals of Node.js. # Iterators in JavaScript using Quokka.js [Mattias Petter Johansson] {% youtube W4brAobC2Hc %} In this video, Mattias Petter Johansson (or simply "MPJ" of [Fun Fun Function](https://www.youtube.com/channel/UCO1cgjhGzsSYb1rsB4bFe4Q)) explains how a [`for...of` loop](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/for...of) works under the hood, which is basically just a native JavaScript implementation for the [Iterator Design Pattern](https://www.tutorialspoint.com/design_pattern/iterator_pattern.htm). # Generators in JavaScript [Mattias Petter Johansson] {% youtube QOnUcU8U_XE %} Refactoring the code example from his previous video on iterators, MPJ demonstrates how [ES6 generators](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/function*) are just "syntactic sugar" over iterators. # Stream into the Future [Matteo Collina] {% youtube dEFdt_6fW-0 %} Streams form the foundation of Node.js' core libraries: file system interactions, data compression, and networking—all of these use streams in one way or another. After a short crash course on stream fundamentals, Matteo Collina introduces their latest achievement for Node.js: a stream abstraction that makes use of asynchronous iterators. With the [`for await...of` loop](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/for-await...of), one can interact with streams without having to worry about the nasty memory leaks and pitfalls that Collina presents in his talk. # Learning Functional Programming with JavaScript [Anjana Vakil] {% youtube e-5obm1G_FY %} Using bright and clever analogies for terminologies and concepts, Anjana Vakil gives an approachable introduction to functional programming in JavaScript, devoid of all the intense mathematical jargon associated with it. # javaScript call apply and bind [techsith] {% youtube c0mLRpw-9rI %} The idea of functions being "first-class citizens" in JavaScript often trip up many beginners—myself especially included then. When mixed in with the nuances of the `this` keyword, all of `this` just becomes one blurry mess of JavaScript jargon. In this video, ["techsith"](https://www.youtube.com/user/techSithTube) differentiates between the [`Function#call`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function/call), [`Function#apply`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function/apply), and [`Function#bind`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function/bind) methods. In doing so, he provides critical insight into fully understanding `this`. # Prototypes in JavaScript [Mattias Petter Johansson] {% youtube riDVvXZ_Kb4 %} Unlike many traditional object-oriented languages such Java and C++, JavaScript does not implement the classical model of inheritance, where classes directly inherit properties and methods from their parents. Instead, JavaScript uses "prototypal inheritance", where object instances of JavaScript "classes" share and hold references to "prototype" objects. This is quite a tricky concept to grasp. It took a very long time for everything to "click", but when it finally did, I owed much of my understanding to MPJ's [series of videos on object creation](https://www.youtube.com/playlist?list=PL0zVEGEvSaeHBZFy6Q8731rcwk0Gtuxub). The video above served as a supplement that further solidified the big picture of prototypal inheritance. # JavaScript Event Capture, Propagation and Bubbling [Wes Bos] {% youtube F1anRyL37lE %} The mechanisms of event dispatching and handling are integral features of the HTML DOM. In this video, Wes Bos explains what it means for events to "propagate" during the "capture phase" and the "bubble phase". Knowing when to take advantage of each phase allows for more powerful event handling techniques such as "event delegation" and default behavior cancellation. # Fizz buzzkill - Answering tricky JS interview questions [Russell Anderson] {% youtube cMxI8n393ZM %} Similar to [Samer Buna's Q&A-style talk on Node fundamentals](#you-dont-know-node-samer-buna), Russell Anderson tests our general knowledge about some fundamental concepts, techniques, and idioms in the JavaScript language. In a beginner-friendly manner, he presents the answers to questions that will inevitably come up during a JavaScript interview. # Writing Secure Node Code: Understanding and Avoiding the Most Common Node.js Security Mistakes [Guy Podjarny] {% youtube QSMbk2nLTBk %} Given that the JavaScript ecosystem vastly relies on shared code and deeply nested dependencies, we face a concerning reality that an overwhelming portion of the code we deploy comes from third parties. Although this arguably increases productivity and speeds up development time, it also brings the unfortunate consequence of exposing our applications to greater attack surfaces. In this talk, Guy Podjarny discusses the importance of vigilance and caution when it comes to external code. # JavaScript Metaprogramming - ES6 Proxy Use and Abuse [Eirik Vullum] {% youtube _5X2aB_mNp4 %} [ES6 proxies](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Proxy) enable us to intercept and hook into various aspects of the language. This new age of metaprogramming in JavaScript opens the doors to more powerful polyfills, language extensions, and custom behaviors. However, given its immense scope over the semantics of the language, Eirik Vullum reminds us to use proxies responsibly. His talk contrasts the wondrous possibilities of proxies and its equally wondrous vectors for potential abuse. ___ _For your convenience, I have compiled these videos into an [unlisted YouTube playlist](https://www.youtube.com/playlist?list=PLdUuF9OvrfuUTmjDNPaUSK9Utyh70l1KR). Although I cannot possibly list down **all** of the videos that contributed to my understanding of JavaScript, I hope you will still find great value in my humble list of videos._
somedood
384,335
Pod uses dynamic environment variable
TL; DR This post is build-up on the Merge ConfigMap and Secrets post.It is another use of...
0
2020-07-06T09:06:51
https://storage-chaos.io/dell-csi-isilon-custom-envvars.html
kubernetes, csi, dell, isilon
--- title: Pod uses dynamic environment variable published: true date: 2020-06-19 07:00:00 UTC tags: #kubernetes #csi #dell #isilon canonical_url: https://storage-chaos.io/dell-csi-isilon-custom-envvars.html --- # TL; DR This post is build-up on the [Merge ConfigMap and Secrets](/configmap-and-secret.html) post.It is another use of [initContainers](https://kubernetes.io/docs/concepts/workloads/pods/init-containers/), [templating](https://docs.ruby-lang.org/en/master/ERB.html) and [entrypoint](https://docs.docker.com/engine/reference/builder/#entrypoint) to customize a container startup. # The premise I worked on a Kubernetes architecture where the hosts of the cluster had several NIC Cards connected to different networks (one to expose the services, one for management, one for storage, etc.). When to create and mount an NFS volume, the [CSI driver for PowerScale/Isilon](https://github.com/dell/csi-isilon/) passes a client IP that is used to create the export array-side.The driver picks the IP return by the fieldRef<sup id="fnref:1" role="doc-noteref"><a href="#fn:1">1</a></sup> `status.hostIP`, as you can see [here](https://github.com/dell/csi-isilon/blob/master/helm/csi-isilon/templates/node.yaml#L113)). The problem is that IP is used to serve Kubernetes services (aka the Internal IP displayed by `kubectl get node -o wide`). So how to change that value to use the storage network-related IP ? # The implementation In my setup, I know which NIC card connects to which network (in this case `ens33`).The patch to the native [csi-isilon](https://github.com/dell/csi-isilon/) deployment aims to : 1. Have a simple way to get the IP address of a specific NIC card 2. Pass that information on the driver startup The first piece of configuration is to create a custom [entrypoint](https://docs.docker.com/engine/reference/builder/#entrypoint) that will set the `X_NODE_IP` variable with the proper. Here I use an [ERB](https://docs.ruby-lang.org/en/master/ERB.html) template in which I call the `ip addr` [command in a subshell](https://ruby-doc.org/core-2.7.1/Kernel.html#method-i-60) with `%x@ @` syntax, then I extract the IP with the [substring](https://ruby-doc.org/core-2.7.1/String.html#method-i-5B-5D) `[/inet\s+(\d+(\.\d+){3})/,1]`. If you use IPv6 or another NIC card you can easily adjust it at line 9 of the following snippet. It is not displayed in the configuration above, but the `ip addr` command works because the Isilon Node Pod has access to the host network thanks to `hostNetwork: true` in its definition. <noscript><pre>400: Invalid request</pre></noscript><script src="https://gist.github.com/d4260e4e17910bbdefbbecce4286074f.js?file=nodeip-configmap.yaml"> </script> The second step is to add an [initContainers](https://kubernetes.io/docs/concepts/workloads/pods/init-containers/) to the [DaemonSet](https://github.com/dell/csi-isilon/blob/master/helm/csi-isilon/templates/node.yaml) to generate a new entrypoint, and then force the driver Pod to use the new entrypoint : <noscript><pre>400: Invalid request</pre></noscript><script src="https://gist.github.com/d4260e4e17910bbdefbbecce4286074f.js?file=isilon-ds.yaml"> </script> To apply the patch you can create the config map with : ``` kubectl create -f nodeip-configmap.yaml ``` And patch the Isilon daemon set with : ``` kubectl patch daemonset isilon-node -n isilon --patch "$(cat isilon-ds.patch)" ``` # Wrap-up The same tools (ERB, ConfigMap, initContainer, Entrypoint), can be use to tune pretty much any Kubernetes Pod deployments to customize or add extra-capabilities to your Pod startup (integration with [Vault](https://www.vaultproject.io/), tweak program startup, etc.). 1. The list of fieldRef possible values is documented [here](https://kubernetes.io/docs/tasks/inject-data-application/downward-api-volume-expose-pod-information/#capabilities-of-the-downward-api), [↩︎](#fnref:1)
coulof
384,419
☄️ How to update version's cache of your package in pkg.go.dev?
Introduction Hi, DEV people! 😉 Sometimes, when you publish a new version of your Go...
4,444
2020-07-06T11:56:27
https://dev.to/koddr/how-to-update-version-s-cache-of-your-package-in-pkg-go-dev-39ij
go, tutorial, beginners, fiber
## Introduction Hi, DEV people! 😉 Sometimes, when you publish a new version of your Go package, [pkg.go.dev](https://pkg.go.dev) may still give away an old version for a long time. This also means, that if other people are using your package, **not be able** to update to the new version until the cache is updated. Let's fix this! 👌 <a name="toc"></a> ### 📝 Table of contents - [A little story from real-life](#ch-1) - [Solution](#ch-2) <a name="ch-1"></a> ## A little story from real-life That's what we did at **Fiber** Go web framework a few months ago. {% github gofiber/fiber no-readme %} After fixed a major bug, a new **Fiber** version could not be installed on users projects **for about a couple of hours**, because the cache was not updated. But the press release for the fix was already out (_in official repository, Twitter, etc._) and users wanted to update and could not. Worst-case scenario, isn't it? 😨 [↑ Table of contents](#toc) <a name="ch-2"></a> ## Solution Save this command to a `Makefile` (or a task manager you're using now): ```Makefile # ... update-pkg-cache: GOPROXY=https://proxy.golang.org GO111MODULE=on \ go get github.com/$(USER)/$(PACKAGE)@v$(VERSION) # ... ``` And use it, like this: ```bash make update-pkg-cache USER=gofiber PACKAGE=fiber VERSION=1.12.4 ``` > Where: > > - `USER` your GitHub user or organization name > - `PACKAGE` a name of your package to update cache > - `VERSION` a version number to update cache **It's that simple and clear!** [↑ Table of contents](#toc) <a name=""></a> ## P.S. If you want more articles (like this) on this blog, then post a comment below and subscribe to me. Thanks! 😻 And of course, you can help me make developers' lives even better! Just connect to one of my projects as a contributor. It's easy! My projects that need your help (and stars) 👇 - 🔥 [gowebly][gowebly_url]: A next-generation CLI tool for easily build amazing web applications with Go on the backend, using htmx & hyperscript and the most popular atomic/utility-first CSS frameworks on the frontend. - ✨ [create-go-app][cgapp_url]: Create a new production-ready project with Go backend, frontend and deploy automation by running one CLI command. - 🏃 [yatr][yatr_url]: Yet Another Task Runner allows you to organize and automate your routine operations that you normally do in Makefile (or else) for each project. - 📚 [gosl][gosl_url]: The Go Snippet Library provides snippets collection for working with routine operations in your Go programs with a super user-friendly API and the most efficient performance. - 🏄‍♂️ [csv2api][csv2api_url]: The parser reads the CSV file with the raw data, filters the records, identifies fields to be changed, and sends a request to update the data to the specified endpoint of your REST API. - 🚴 [json2csv][json2csv_url]: The parser can read given folder with JSON files, filtering and qualifying input data with intent & stop words dictionaries and save results to CSV files by given chunk size. <!-- Footer links --> [gowebly_url]: https://github.com/gowebly [cgapp_url]: https://github.com/create-go-app [yatr_url]: https://github.com/koddr/yatr [gosl_url]: https://github.com/koddr/gosl [csv2api_url]: https://github.com/koddr/csv2api [json2csv_url]: https://github.com/koddr/json2csv
koddr
384,814
#JulyOT - Getting Started with NVIDIA Jetson Nano: Object Detection
Erik and Paul configure a Jetson Nano device for use with DeepStream SDK using samples provided from NVIDIA. Part 1 of a 5 part series created for #JulyOT - more details @ http://julyot.com
0
2020-07-06T19:05:15
https://dev.to/azure/julyot-getting-started-with-nvidia-jetson-nano-object-detection-3moe
ai, computervision, nvidia, iot
--- title: #JulyOT - Getting Started with NVIDIA Jetson Nano: Object Detection published: true description: Erik and Paul configure a Jetson Nano device for use with DeepStream SDK using samples provided from NVIDIA. Part 1 of a 5 part series created for #JulyOT - more details @ http://julyot.com tags: artificialintelligence, computervision, nvidia, iot --- Erik and Paul configure a Jetson Nano device for use with DeepStream SDK using samples provided from NVIDIA. Part 1 of a 5 part series created for #JulyOT - more details @ http://julyot.com The full steps to reproduce this project can be found on github @ https://github.com/toolboc/Intelligent-Video-Analytics-with-NVIDIA-Jetson-and-Microsoft-Azure For more information on the services employed, check out: http://aka.ms/deepstreamdevguide https://github.com/leandromoreira/digital_video_introduction https://github.com/leandromoreira/ffmpeg-libav-tutorial http://dranger.com/ffmpeg
toolboc
385,208
DNS Explained. Introduction/History
Introduction Imagine this scenario. Netflix has a lot of fresh content being released. Yo...
7,661
2020-07-28T16:56:24
https://dev.to/blake/dns-explained-introduction-history-1an7
networking, dns, network, domain
# Introduction Imagine this scenario. Netflix has a lot of fresh content being released. You decide that you want to watch the next season of [_The Politican_](https://www.netflix.com/title/80241248). So, you open up your favorite browser, type in `netflix.com`, and hit enter. Almost instantly, Netflix's profile selection screen pops up. You probably already know that an HTTP(S) request over a TCP connection is made to Netflix's servers and that Netflix sends back a HTTP(S) response, which is eventually rendered by your browser as the screen you end up seeing. However, a key part is missing here. In order to make a TCP connection, you need four things: 1) The Source IP 2) The Source Port Number 3) The Destination IP 4) The Destination Port Number The above four requirements are often referred to as the "TCP 4-Tuple". Now, you already have the source IP and port number, because you are the source! And thanks to [IANA](https://www.iana.org/assignments/service-names-port-numbers/service-names-port-numbers.xhtml), the destination port number is already known based on the protocol used (HTTP: 80/HTTPS: 443). The only thing missing to make the TCP connection is the destination IP address. DNS is how you obtain it. ## Why do we have domain names? First of all, why do we even have domain names? If we typed the destination IP address, the problem of obtaining the IP address wouldn't exist. This is correct, but would involve the end-user memorizing the IP addresses of all the sites they wish to visit. You could probably memorize a few IPv4 addresses, but good luck memorizing 5+, or even a single IPv6 address. Domain names exist so humans don't have to memorize IP addresses. In addition, IP addresses for hosts can change; having a domain name point automatically to the updated address is really handy. ## History Before diving straight into DNS, it is beneficial to know the history of the system and the motivations behind its creation. The predecessor of DNS was the `hosts.txt` file for ARPANET (the predecessor of the Internet). This plain-text file was centrally maintained by the Stanford Research Institute and mapped domain names to addresses of computers on ARPANET. Since the number of hosts on ARPANET was under 1,000 at the time, it was a sufficient solution to mapping domain names. However, there were significant drawbacks. The first drawback is that updates to the file were manually processed by hand. This resulted in long initial delays. Second, once the original file at Stanford was updated, all hosts on ARPANET also had to have an updated copy of the hosts.txt file. This resulted in propagation times being measured in the span of *days*. Imagine not having your domain name be accessible for days after you submit an update! Third, once a domain was claimed, nobody else could have it. If MIT claimed "mail", then George Washington University could not claim "mail". There was no hierarchy, so great domain names couldn't be used by multiple organizations (like "mit.mail" "gwu.mail" which are possible today). As you can imagine, this simple file "system" wasn't going to cut it for when the future internet comes around with thousands of hosts. A new scalable and automatic system had to be made and put in place. ## Defining DNS [Wikipedia](https://en.wikipedia.org/wiki/Domain_Name_System) defines DNS as, "a hierarchical and decentralized naming system for computers, services, or other resources connected to the Internet or a private network." I don't know about you, but this definition doesn't really tell me much. Let's reword that a bit. **DNS is a hierarchical naming system that maps strings (called fully-qualified domain names or FQDN) to values called resource records (which can contain a corresponding IP address).** Simply put, you query DNS with a domain name (e.g. www.netflix.com) and DNS will eventually return an IP address back to you. This returned value is the destination IP address needed to complete the TCP 4-Tuple. ## Diving Deeper DNS at its core is a key-value system where the key is a fully-qualified domain name and the value is a resource record. Though DNS has additional components that are vital to the overall health and performance of the system. We have described a real-life use case for DNS, in addition to briefly going over the need for domains in general, DNS' history and technical definition. Keep reading the "DNS Explained." series to dive deeper into more DNS topics including the RRR model and resolution!
blake
388,107
How To Install WordPress on Ubuntu 20.04 with a LAMP Stack
This tutorial is intended for those who desire to install and administer a Wordpress instance on an unmanaged cloud server via the command line.
0
2020-07-08T17:55:44
https://www.digitalocean.com/community/tutorials/how-to-install-wordpress-on-ubuntu-20-04-with-a-lamp-stack
wordpress, linux, tutorial, cloud
--- title: How To Install WordPress on Ubuntu 20.04 with a LAMP Stack published: true tags: wordpress, linux, tutorial, cloud description: This tutorial is intended for those who desire to install and administer a Wordpress instance on an unmanaged cloud server via the command line. canonical_url: https://www.digitalocean.com/community/tutorials/how-to-install-wordpress-on-ubuntu-20-04-with-a-lamp-stack --- ### Introduction WordPress is an extremely popular open-source technology for making websites and blogs on the internet today. Used by 63% of all websites that use a content management system (CMS), WordPress sites represent 36% of all websites that are currently online. There are many different approaches to getting access to WordPress and some setup processes are more complex than others. This tutorial is intended for those who desire to install and administer a Wordpress instance on an unmanaged cloud server via the command line. Though this approach requires more steps than a ready-made WordPress installation, it offers administrators greater control over their WordPress environment. Depending on your needs and goals, you may find other options that are more suitable. As open-source software, WordPress can be freely downloaded and installed, but to be available on the web, you will likely need to purchase cloud infrastructure and a domain name. Continue following this guide if you are interested in working through the server-side installation and set up of a WordPress site. This tutorial will be using a LAMP (**L**inux, **A**pache, **M**ySQL, and **P**HP) stack, which is one option for a server architecture that supports WordPress by providing the Linux operating system, Apache web server, MySQL database, and PHP programming language. We’ll install and set up WordPress via LAMP on a Linux Ubuntu 20.04 server. ## Prerequisites In order to complete this tutorial, you will need access to an Ubuntu 20.04 server and will need to complete these steps before beginning this guide: - Set up your server by following our [Ubuntu 20.04 initial server setup guide](https://www.digitalocean.com/community/tutorials/initial-server-setup-with-ubuntu-20-04), and ensure you have a non-root `sudo` user. - **Install a LAMP stack** by following our [LAMP guide](https://www.digitalocean.com/community/tutorials/how-to-install-linux-apache-mysql-php-lamp-stack-on-ubuntu-20-04) to install and configure this software. - **Secure your site**: WordPress takes in user input and stores user data, so it is important for it to have a layer of security. TLS/SSL is the technology that allows you to encrypt the traffic from your site so that your and your users’ connection is secure. Here are two options available to you to meet this requirement: - **If you have a domain name...** you can secure your site with Let’s Encrypt, which provides free, trusted certificates. Follow our [Let’s Encrypt guide for Apache](https://www.digitalocean.com/community/tutorials/how-to-secure-apache-with-let-s-encrypt-on-ubuntu-20-04) to set this up. - **If you do not have a domain...** and you are just using this configuration for testing or personal use, you can use a self-signed certificate instead. This provides the same type of encryption, but without the domain validation. Follow our [self-signed SSL guide for Apache](https://www.digitalocean.com/community/tutorials/how-to-create-a-self-signed-ssl-certificate-for-apache-in-ubuntu-18-04) to get set up. When you are finished with the setup steps, log into your server as your `sudo` user and continue below. ## Step 1 — Creating a MySQL Database and User for WordPress The first step that we will take is a preparatory one. WordPress uses MySQL to manage and store site and user information. We have MySQL installed already, but we need to make a database and a user for WordPress to use. To get started, log into the MySQL root (administrative) account by issuing this command (note that this is not the root user of your server): ```command mysql -u root -p ``` You will be prompted for the password you set for the MySQL root account when you installed the software. --- **Note**: If you cannot access your MySQL database via root, as a `sudo` user you can update your root user’s password by logging into the database like so: ```command sudo mysql -u root ``` Once you receive the MySQL prompt, you can update the root user’s password. Here, replace `new_password` with a strong password of your choosing. ```custom_prefix(mysql>) ALTER USER 'root'@'localhost' IDENTIFIED WITH mysql_native_password BY 'new_password'; ``` You may now type `EXIT;` and can log back into the database via password with the following command: ```command mysql -u root -p ``` --- Within the database, we can create an exclusive database for WordPress to control. You can call this whatever you would like, but we will be using the name **wordpress** in this guide. Create the database for WordPress by typing: ```custom_prefix(mysql>) CREATE DATABASE wordpress DEFAULT CHARACTER SET utf8 COLLATE utf8_unicode_ci; ``` **Note**: Every MySQL statement must end in a semi-colon (`;`). Check to make sure this is present if you are running into any issues. Next, we are going to create a separate MySQL user account that we will use exclusively to operate our new database. Creating specific databases and accounts can support us from a management and security standpoint. We will use the name **wordpressuser** in this guide, but feel free to use whatever name is relevant for you. We are going to create this account, set a password, and grant access to the database we created. We can do this by typing the following command. Remember to choose a strong password here for your database user where we have `password`: ```custom_prefix(mysql>) CREATE USER 'wordpressuser'@'%' IDENTIFIED WITH mysql_native_password BY 'password'; ``` Next, let the database know that our **wordpressuser** should have complete access to the database we set up: ```custom_prefix(mysql>) GRANT ALL ON wordpress.* TO 'wordpressuser'@'%'; ``` You now have a database and user account, each made specifically for WordPress. We need to flush the privileges so that the current instance of MySQL knows about the recent changes we’ve made: ```custom_prefix(mysql>) FLUSH PRIVILEGES; ``` Exit out of MySQL by typing: ```custom_prefix(mysql>) EXIT; ``` In the next step, we’ll lay some foundations for WordPress plugins by downloading PHP extensions for our server. ## Step 2 — Installing Additional PHP Extensions When setting up our LAMP stack, we only required a very minimal set of extensions in order to get PHP to communicate with MySQL. WordPress and many of its plugins leverage additional PHP extensions. We can download and install some of the most popular PHP extensions for use with WordPress by typing: ```command sudo apt update sudo apt install php-curl php-gd php-mbstring php-xml php-xmlrpc php-soap php-intl php-zip ``` This will lay the groundwork for installing additional plugins into our WordPress site. **Note:** Each WordPress plugin has its own set of requirements. Some may require additional PHP packages to be installed. Check your plugin documentation to discover its PHP requirements. If they are available, they can be installed with `apt` as demonstrated above. We will need to restart Apache to load these new extensions, we’ll be doing more configurations on Apache in the next section, so you can wait until then, or restart now to complete the PHP extension process. ```command sudo systemctl restart apache2 ``` ## Step 3 — Adjusting Apache's Configuration to Allow for .htaccess Overrides and Rewrites Next, we will be making a few minor adjustments to our Apache configuration. Based on the prerequisite tutorials, you should have a configuration file for your site in the `/etc/apache2/sites-available/` directory. In this guide, we'll use `/etc/apache2/sites-available/wordpress.conf` as an example here, but you should substitute the path to your configuration file where appropriate. Additionally, we will use `/var/www/wordpress` as the root directory of our WordPress install. You should use the web root specified in your own configuration. If you followed our [LAMP tutorial](https://www.digitalocean.com/community/tutorials/how-to-install-linux-apache-mysql-php-lamp-stack-on-ubuntu-20-04), it may be your domain name instead of `wordpress` in both of these instances. **Note:** It's possible you are using the `000-default.conf` default configuration (with `/var/www/html` as your web root). This is fine to use if you’re only going to host one website on this server. If not, it’s better to split the necessary configuration into logical chunks, one file per site. With our paths identified, we can move onto working with `.htaccess` so that Apache can handle configuration changes on a per-directory basis. ### Enabling .htaccess Overrides Currently, the use of `.htaccess` files is disabled. WordPress and many WordPress plugins use these files extensively for in-directory tweaks to the web server’s behavior. Open the Apache configuration file for your website with a text editor like nano. ```command sudo nano /etc/apache2/sites-available/wordpress.conf ``` To allow `.htaccess` files, we need to set the `AllowOverride` directive within a `Directory` block pointing to our document root. Add the following block of text inside the `VirtualHost` block in your configuration file, making sure to use the correct web root directory: ``` <Directory /var/www/wordpress/> AllowOverride All </Directory> ``` When you are finished, save and close the file. In nano, you can do this by pressing `CTRL` and `X` together, then `Y`, then `ENTER`. ### Enabling the Rewrite Module Next, we can enable `mod_rewrite` so that we can utilize the WordPress permalink feature: ```command sudo a2enmod rewrite ``` This allows you to have more human-readable permalinks to your posts, like the following two examples: ``` http://example.com/2012/post-name/ http://example.com/2012/12/30/post-name ``` The `a2enmod` command calls a script that enables the specified module within the Apache configuration. ### Enabling the Changes Before we implement the changes we’ve made, check to make sure we haven’t made any syntax errors by running the following test. ```command sudo apache2ctl configtest ``` You may receive output like the following: ``` AH00558: apache2: Could not reliably determine the server's fully qualified domain name, using 127.0.1.1. Set the 'ServerName' directive globally to suppress this message Syntax OK ``` If you wish to suppress the top line, just add a `ServerName` directive to your main (global) Apache configuration file at `/etc/apache2/apache2.conf`. The `ServerName` can be your server’s domain or IP address. This is just a message, however, and doesn’t affect the functionality of your site. As long as the output contains `Syntax OK`, you are ready to continue. Restart Apache to implement the changes. Make sure to restart now even if you have restarted earlier in this tutorial. ```command sudo systemctl restart apache2 ``` Next, we will download and set up WordPress itself. ## Step 4 — Downloading WordPress Now that our server software is configured, we can download and set up WordPress. For security reasons in particular, it is always recommended to get the latest version of WordPress from their site. Change into a writable directory (we recommend a temporary one like `/tmp`) and download the compressed release. ```command cd /tmp curl -O https://wordpress.org/latest.tar.gz ``` Extract the compressed file to create the WordPress directory structure: ```command tar xzvf latest.tar.gz ``` We will be moving these files into our document root momentarily. Before we do, we can add a dummy `.htaccess` file so that this will be available for WordPress to use later. Create the file by typing: ```command touch /tmp/wordpress/.htaccess ``` We’ll also copy over the sample configuration file to the filename that WordPress reads: ```command cp /tmp/wordpress/wp-config-sample.php /tmp/wordpress/wp-config.php ``` We can also create the `upgrade` directory, so that WordPress won’t run into permissions issues when trying to do this on its own following an update to its software: ```command mkdir /tmp/wordpress/wp-content/upgrade ``` Now, we can copy the entire contents of the directory into our document root. We are using a dot at the end of our source directory to indicate that everything within the directory should be copied, including hidden files (like the `.htaccess` file we created): ```command sudo cp -a /tmp/wordpress/. /var/www/wordpress ``` Ensure that you replace the `/var/www/wordpress` directory with the directory you have set up on your server. ## Step 5 — Configuring the WordPress Directory Before we do the web-based WordPress setup, we need to adjust some items in our WordPress directory. ### Adjusting the Ownership and Permissions An important step that we need to accomplish is setting up reasonable file permissions and ownership. We’ll start by giving ownership of all the files to the **www-data** user and group. This is the user that the Apache web server runs as, and Apache will need to be able to read and write WordPress files in order to serve the website and perform automatic updates. Update the ownership with the `chown` command which allows you to modify file ownership. Be sure to point to your server’s relevant directory. ```command sudo chown -R www-data:www-data /var/www/wordpress ``` Next we’ll run two `find` commands to set the correct permissions on the WordPress directories and files: ```command sudo find /var/www/wordpress/ -type d -exec chmod 750 {} \; sudo find /var/www/wordpress/ -type f -exec chmod 640 {} \; ``` These permissions should get you working effectively with WordPress, but note that some plugins and procedures may require additional tweaks. ### Setting Up the WordPress Configuration File Now, we need to make some changes to the main WordPress configuration file. When we open the file, our first task will be to adjust some secret keys to provide a level of security for our installation. WordPress provides a secure generator for these values so that you do not have to try to come up with good values on your own. These are only used internally, so it won’t hurt usability to have complex, secure values here. To grab secure values from the WordPress secret key generator, type: ```command curl -s https://api.wordpress.org/secret-key/1.1/salt/ ``` You will get back unique values that resemble output similar to the block below. **Warning!** It is important that you request unique values each time. Do **NOT** copy the values below! ``` define('AUTH_KEY', '1jl/vqfs<XhdXoAPz9 DO NOT COPY THESE VALUES c_j{iwqD^<+c9.k<J@4H'); define('SECURE_AUTH_KEY', 'E2N-h2]Dcvp+aS/p7X DO NOT COPY THESE VALUES {Ka(f;rv?Pxf})CgLi-3'); define('LOGGED_IN_KEY', 'W(50,{W^,OPB%PB<JF DO NOT COPY THESE VALUES 2;y&,2m%3]R6DUth[;88'); define('NONCE_KEY', 'll,4UC)7ua+8<!4VM+ DO NOT COPY THESE VALUES #`DXF+[$atzM7 o^-C7g'); define('AUTH_SALT', 'koMrurzOA+|L_lG}kf DO NOT COPY THESE VALUES 07VC*Lj*lD&?3w!BT#-'); define('SECURE_AUTH_SALT', 'p32*p,]z%LZ+pAu:VY DO NOT COPY THESE VALUES C-?y+K0DK_+F|0h{!_xY'); define('LOGGED_IN_SALT', 'i^/G2W7!-1H2OQ+t$3 DO NOT COPY THESE VALUES t6**bRVFSD[Hi])-qS`|'); define('NONCE_SALT', 'Q6]U:K?j4L%Z]}h^q7 DO NOT COPY THESE VALUES 1% ^qUswWgn+6&xqHN&%'); ``` These are configuration lines that we can paste directly in our configuration file to set secure keys. Copy the output you received now. Next, open the WordPress configuration file: ```command sudo nano /var/www/wordpress/wp-config.php ``` Find the section that contains the example values for those settings. ``` . . . define('AUTH_KEY', 'put your unique phrase here'); define('SECURE_AUTH_KEY', 'put your unique phrase here'); define('LOGGED_IN_KEY', 'put your unique phrase here'); define('NONCE_KEY', 'put your unique phrase here'); define('AUTH_SALT', 'put your unique phrase here'); define('SECURE_AUTH_SALT', 'put your unique phrase here'); define('LOGGED_IN_SALT', 'put your unique phrase here'); define('NONCE_SALT', 'put your unique phrase here'); . . . ``` Delete those lines and paste in the values you copied from the command line: ``` . . . define('AUTH_KEY', 'VALUES COPIED FROM THE COMMAND LINE'); define('SECURE_AUTH_KEY', 'VALUES COPIED FROM THE COMMAND LINE'); define('LOGGED_IN_KEY', 'VALUES COPIED FROM THE COMMAND LINE'); define('NONCE_KEY', 'VALUES COPIED FROM THE COMMAND LINE'); define('AUTH_SALT', 'VALUES COPIED FROM THE COMMAND LINE'); define('SECURE_AUTH_SALT', 'VALUES COPIED FROM THE COMMAND LINE'); define('LOGGED_IN_SALT', 'VALUES COPIED FROM THE COMMAND LINE'); define('NONCE_SALT', 'VALUES COPIED FROM THE COMMAND LINE'); . . . ``` Next, we are going to modify some of the database connection settings at the beginning of the file. You need to adjust the database name, the database user, and the associated password that you configured within MySQL. The other change we need to make is to set the method that WordPress should use to write to the filesystem. Since we’ve given the web server permission to write where it needs to, we can explicitly set the filesystem method to "direct". Failure to set this with our current settings would result in WordPress prompting for FTP credentials when we perform some actions. This setting can be added below the database connection settings, or anywhere else in the file: ``` . . . // ** MySQL settings - You can get this info from your web host ** // /** The name of the database for WordPress */ define( 'DB_NAME', 'wordpress' ); /** MySQL database username */ define( 'DB_USER', 'wordpressuser' ); /** MySQL database password */ define( 'DB_PASSWORD', 'password' ); /** MySQL hostname */ define( 'DB_HOST', 'localhost' ); /** Database Charset to use in creating database tables. */ define( 'DB_CHARSET', 'utf8' ); /** The Database Collate type. Don't change this if in doubt. */ define( 'DB_COLLATE', '' ); . . . define('FS_METHOD', 'direct'); ``` Save and close the file when you are finished. ## Step 6 — Completing the Installation Through the Web Interface Now that the server configuration is complete, we can complete the installation through the web interface. In your web browser, navigate to your server’s domain name or public IP address: ``` https://server_domain_or_IP ``` Select the language you would like to use: ![WordPress language selection](https://assets.digitalocean.com/articles/wordpress_lamp_1604/language_selection.png) Next, you will come to the main setup page. Select a name for your WordPress site and choose a username. It is recommended to choose something unique and avoid common usernames like “admin” for security purposes. A strong password is generated automatically. Save this password or select an alternative strong password. Enter your email address and select whether you want to discourage search engines from indexing your site: ![WordPress setup installation](https://assets.digitalocean.com/articles/wordpress_lamp_1604/setup_installation.png) When you click ahead, you will be taken to a page that prompts you to log in: ![WordPress login prompt](https://assets.digitalocean.com/articles/wordpress_lamp_1604/login_prompt.png) Once you log in, you will be taken to the WordPress administration dashboard: ![WordPress login prompt](https://assets.digitalocean.com/articles/wordpress_lamp_1604/admin_screen.png) At this point, you can begin to design your WordPress website! If this is your first time using WordPress, explore the interface a bit to get acquainted with your new CMS. ## Conclusion Congratulations, WordPress is now installed and is ready to be used! At this point you may want to start doing the following: * Choose your permalinks setting for WordPress posts, which can be found in `Settings > Permalinks`. * Select a new theme in `Appearance > Themes`. * Install new plugins to increase your site’s functionality under `Plugins > Add New`. * If you are going to collaborate with others, you may also wish to add additional users at this time under `Users > Add New`. You can find additional resources for alternate ways to install WordPress, learn how to install WordPress on different server distributions, automate your WordPress installations, and scale your WordPress sites by checking out the [WordPress Community tag on DigitalOcean](https://www.digitalocean.com/community/tags/wordpress).
lisaironcutter
389,432
Upload your project/files in GitHub using commands
Upload your project/files in GitHub using following commands; Tell the GitHub who are you; $ git c...
0
2020-07-09T10:46:19
https://dev.to/100rabhcsmc/upload-your-project-files-in-github-using-commands-1hn8
python, github
Upload your project/files in GitHub using following commands; Tell the GitHub who are you; $ git config --global user.email"saurabhchavan052@gmail.com" $ git config --global user.name"100rabhcsmc" Lets git .. $ git init $ git add -A#adding file $git commit -m "your commit" $git remote add origin reponame $git push origin master #if you got any error using this command then you can use following command $ git push --force origin master thanku.... :)
100rabhcsmc
389,950
Is there cheese down that hole?
I have a good friend who has a saying: “Is there cheese down that hole?” It’s of course a literal re...
0
2020-07-09T16:31:01
https://dev.to/thinkster/is-there-cheese-down-that-hole-38fk
impact, webdev, productivity, change
I have a good friend who has a saying: “Is there cheese down that hole?” It’s of course a literal reference to mice looking for cheese down a hole, but it’s also a reference to questioning whether a course of action has the potential for a valuable result we actually want. So many times in our lives, we are simply reactive. Someone does something, and we react. We go into “lizard brain” mode. We simply do what our impulses are telling us to do. It may “feel” right, but is it the right course of action? Let’s look at an example: Someone cuts you off in traffic. You can ignore it, you can speed up, flip them off as you pass them, pull rudely in front and slam on your brakes, etc. But before you do that, ask yourself: Is there cheese down that hole? Or…Our spouse/significant other says that we hurt them by something we did. But yet, just yesterday they did basically the same thing to us. Our first urge is to accuse them of hypocrisy. Again, is there cheese down that hole? A coworker makes a personal attack during a planning meeting. You’re so pissed that you’re ready to attack them back. Is there cheese down that hole? There are so many times when we feel like we’re letting others walk on us if we don’t react to their actions. That we have to “stand up” for ourselves by attacking back. But that is simply our own human frailties coming out. There are plenty of examples of those who didn’t “react” when they were attacked. They asked themselves about the cheese (although probably not with this particular phrase). Is there cheese down the hole you’re in? Happy coding! Signup for my newsletter [here](https://thinkster.io/?previewmodal=signup?utm_source=devto&utm_medium=blog&utm_term=istherecheese&utm_content=&utm_campaign=blog). Visit Us: [thinkster.io](https://thinkster.io?utm_source=devto&utm_medium=blog&utm_term=istherecheese&utm_content=&utm_campaign=blog) | Facebook: @gothinkster | Twitter: @GoThinkster
josepheames
391,579
How to get more people to join your Discord community by adding an invite widget to your README
Inspired by shields.io, we've created a service that generates SVG images that mimic Discord's invite...
0
2020-07-10T15:01:54
https://dev.to/pedrofracassi/how-to-get-more-people-to-join-your-discord-community-by-adding-an-invite-widget-to-your-readme-9ne
showdev, github
Inspired by shields.io, we've created a service that generates SVG images that mimic Discord's invite widgets, shown on the app when you send an invite link to a chat. Adding these to your README is an easy way to get more people interested in joining your community! These look really cool on your repository README, or even in GitHub's new [profile READMEs](https://dev.to/ypedroo/have-you-seen-github-s-cool-new-feature-an7)! ![Invidget in a GitHub repository](https://dev-to-uploads.s3.amazonaws.com/i/dg9r30xbcg543k8xwkgj.png) ![Invidget in a GitHub profile](https://dev-to-uploads.s3.amazonaws.com/i/o9wddb65iid6zh6bzehu.png) It's super simple. Just add your invite code to the end of the URL, throw it into your browser... ``` https://invidget.switchblade.xyz/2FB8wDG ``` ...and you'll get a nice SVG widget! ![Invidget Widget Example](https://dev-to-uploads.s3.amazonaws.com/i/iptvjwgyvrmw7bwtf6ar.png) It even supports discord's - awfully ugly - light theme, by adding the `theme` query parameter to the URL: ``` https://invidget.switchblade.xyz/2FB8wDG?theme=light ``` ![Light Invidget Widget Example](https://dev-to-uploads.s3.amazonaws.com/i/yirmz99zlxwc3qc8llbt.png) ...and you can set it to render in your language! ``` https://invidget.switchblade.xyz/2FB8wDG?language=pt ``` ![Portuguese Invidget Widget Example](https://dev-to-uploads.s3.amazonaws.com/i/m76qnuw175p2b28m43i7.png) After selecting your language and fighting with your collaborators over light or dark theme, you can then add it to your README, linking to your Discord community, like so: ``` [![Join our Discord server!](https://invidget.switchblade.xyz/2FB8wDG)](http://discord.gg/2FB8wDG) ``` > Again, remember to replace the invite above code with one that takes people to your server. --- *Invidget* is [open source](https://github.com/SwitchbladeBot/invidget), and we still have a bunch of features planned, so feel free to open a PR or two!
pedrofracassi
394,225
Imperative and declarative programming
Nowadays, programming has become the main routine for people inserted in the technology market. Wheth...
0
2020-07-12T13:24:59
https://dev.to/aryclenio/imperative-and-declarative-programming-2b2a
productivity, javascript, codequality, declarative
Nowadays, programming has become the main routine for people inserted in the technology market. Whether in front-end, back-end programming, data science, microcontrollers, among others. Many of us view programming as a kind of order, where you tell the computer what you want, using codes, and it will return it to you in the right way. From this thinking, programming languages ​​as we know them today with structures of repetition and condition arose. Based on that we know today the **Imperative Programming**. ###What is imperative programming Most programming languages ​​are based on procedures, and try to address real situations and workings. Since programming is a *way* and not an *end*, the programmer's natural process is to focus on how to solve a certain problem, without often verifying and consolidating its solution. ![Man pointing to computer](https://dev-to-uploads.s3.amazonaws.com/i/itarqrje0j13tenwivlu.jpg) Imperative programming arose from the fact that, through codes, the programmer writes situations that indicate something to the computer through the imperative conjugation of verbs, always following a *structured* and sequential method of things. * If this happens > Do it * If A is equal to B > Produce this block * As long as there is C > Make D appear And it is from these situations that many codes of different languages ​​can demonstrate this situation. Let's see some below: If Else em Lua ```lua if op == "+" then r = a + b elseif op == "-" then r = a - b elseif op == "*" then r = a*b elseif op == "/" then r = a/b else error("invalid operation") end ``` For em Python ```python for item in [3,4,5,6,7]: print(item) ``` While em Java ```java public class while { public static void main(String args[]) { int cont = 0; while (cont < 50) { System.out.println("Repeat: " + cont); cont++; } } } ``` #### Benefits Programming imperatively is the **closest model to what we could see in the real world** between the human-computer iteration. **Its understanding is easy** at initial levels and is **efficient** in most cases, becoming the general model of several languages. #### Disadvantages Despite all this, imperative programming in large projects has **difficult legibility and maintainability**, always focusing on **how the task should be done** and not **what should be done**, generating treatments of **confusing data** and programs more susceptible to errors. ### And where does declarative programming come in? Declarative programming is a concept that underpinned many existing languages, becoming popular with Javascript, and some already consolidated as SQL. Declarative programming focuses on **what needs to be solved**, and thus seeks clean codes, free from complexity and structural approaches, where the focus is on logic, maintenance and reduction of side effects. This favors *reusable*, *readable* and *succinct* code. ![Alt Text](https://dev-to-uploads.s3.amazonaws.com/i/uh9b0g4mc1e9l3oqvu6u.png) #### How about an example? Javascript can use both approaches. Below is a code that adds "I Love" to an array of languages. ```javascript let languages = ["python", "java", "go", "ruby"]; // Imperative for(let i = 0; i < languages.length; i++){ languages[i] = "I love "+ languages[i]; } // Return: ["I love python", "I love java", "I love go", "I love ruby"] // Declarative languages.map(language => "I love" + language); // Return: ["I love python", "I love java", "I love go", "I love ruby"] ``` Note that in the declarative code, there was no indication to the computer of how it should do the process, but by reading the code itself, we realized that it will map the array, and return what we wanted. The code became cleaner, less verbose and easily replicable. However, not everything is flowers, using the declarative code requires further study, in addition to a difficult adaptation, which is the result of ancient habits in imperative languages. #### Benefits * Reduce side effects * Readability * Bug reduction #### Disadvantages * Difficult to adapt * High complexity of use ### Final verdict Nowadays, functional, and consequently, declarative programming has become the current code standard. This growth makes it easier for new languages ​​to adapt to this and generate more readable programs with higher performance. **Programming is a way, not an end to solving a problem.** Thanks for reading!
aryclenio
394,638
Jest mocking strategies
This post was last updated on July 12, 2020. Always refer to library documentation for the most updat...
0
2020-07-13T01:14:15
https://www.mercedesbernard.com/blog/jest-mocking-strategies/
javascript, jest, testing, mocking
_This post was last updated on July 12, 2020. Always refer to library documentation for the most updated information._ _Note: this post assumes familiarity with Jest and mocking. If you want to learn more, take a look at [the Jest docs](https://jestjs.io/docs/en/mock-functions) first_ 🙂 ## Table of contents 1. [ES6 Exports](#es6-exports) - [Default export of a vanilla function](#default-export-of-a-vanilla-function) - [Named export of a vanilla function](#named-export-of-a-vanilla-function) - [Default export of an object](#default-export-of-an-object) - [Named export of an object](#named-export-of-an-object) - [Default export of a function that returns an object](#default-export-of-a-function-that-returns-an-object) - [Named export of a function that returns an object](#named-export-of-a-function-that-returns-an-object) 2. [Mock behavior](#mock-behavior) - [Browser functionality](#browser-functionality) - [For the whole test suite](#for-the-whole-test-suite) - [In a single file](#in-a-single-file) - [Node modules](#node-modules) - [For the whole test suite](#for-the-whole-test-suite-2) - [In a single file](#in-a-single-file-2) - [A single function of a node module](#a-single-function-of-a-node-module) - [For the whole test suite](#for-the-whole-test-suite-3) - [In a single file](#in-a-single-file-3) - [In a single test](#in-a-single-test) 3. [Common mocking errors](#common-mocking-errors) - [The module factory of `jest.mock()` is not allowed to reference any out-of-scope variables](#the-module-factory-of-jest.mock()-is-not-allowed-to-reference-any-out-of-scope-variables) - [Cannot spy the default property because it is not a function](#cannot-spy-the-default-property-because-it-is-not-a-function) - [Cannot set property of \#\<Object\> which has only a getter](#cannot-set-property-of-%23%3Cobject%3E-which-has-only-a-getter) - [Warning: An update inside a test was not wrapped in act](#warning%3A-an-update-inside-a-test-was-not-wrapped-in-act) Recently, I've been spending more time wrestling with uncooperative mocks than writing the code or the tests combined. I created this post to serve as an easily navigable guidebook of strategies for the next time `jest.mock('modulename')` won't cut it. This is not an exhaustive list, there are multiple ways to satisfy every use case. When mocking a module or function, there are 2 main things to consider: > 1. How was the module exported? > 2. What do we want the behavior of our mock to be? **All of the following code samples can be [found on my Github](https://github.com/mercedesb/jest-mocking-strategies).** The sample application shows you a random cute image of an animal every 3 seconds. It's a [React](https://reactjs.org/) app with [Jest](https://jestjs.io/) as the test runner and uses [React Testing Library](https://testing-library.com/docs/react-testing-library/intro) to test the component DOM (this is the default configuration with [Create React App](https://github.com/facebook/create-react-app)). Despite being built with React, the mocking examples should be easily portable to any framework. ## ES6 Exports Before we worry about our mock's behavior, it's important to understand how the package we're using is exported. When publishing a package, the maintainer makes decisions such as choosing default or named exports and whether to export a vanilla function, an object, or a function that returns an object of other functions. All of those choices affect how the package needs to be mocked in the tests of our application code. Below, we'll look at some tiny examples to highlight how different exports change our mock strategy. ### Default export of a vanilla function In our first example, the library exports is a single default function. When this function is called, it executes the library's logic. ``` export default function () { return "real value"; } ``` To mock its implementation, we use a default import, [mock the module](https://jestjs.io/docs/en/jest-object#jestmockmodulename-factory-options), and provide a factory (a function which will run when the module is invoked). Because the module is a function, we provide a factory that returns the mock function we want to be invoked instead of the module. In this example, we provided a mock implementation so we could set the return value. ``` import example from "../defaultFunction"; const mockExpected = "mock value"; jest.mock("../defaultFunction", () => jest.fn(() => mockExpected)); it("returns the expected value", () => { const actual = example(); expect(actual).toEqual(mockExpected); }); ``` ### Named export of a vanilla function In our first example, the library exports is a single named function. When this function is called, it executes the library's logic. ``` export const example = () => { return "real value"; }; ``` To mock its implementation, we use a named import, mock the module, and provide a factory that returns an object with the named function and its mock implementation. This is slightly different than the previous example because of the named export. ``` import { example } from "../namedFunction"; const mockExpected = "mock value"; jest.mock("../namedFunction", () => ({ example: jest.fn(() => mockExpected), })); it("returns the expected value", () => { const actual = example(); expect(actual).toEqual(mockExpected); }); ``` ### Default export of an object In this example, the library exports a default object that has a property for the function we want to mock. ``` export default { getValue: () => "real value", }; ``` To mock `getValue`, we use a default import, [spy on](https://jestjs.io/docs/en/jest-object#jestspyonobject-methodname) the imported object's `getValue` property, and then chain a mock implementation to the returned mock function. Because `example` is an object, we can spy on its properties. If we didn't want to mock the implementation, we could leave that part off and still be able to track that the returned mock function was called. \* Note: `jest.spyOn` invokes the function's original implementation which is useful for tracking that something expected happened without changing its behavior. For true mocking, we use `mockImplementation` to provide the mock function to overwrite the original implementation. ``` import example from "../defaultObject"; const mockExpected = "mock value"; jest.spyOn(example, "getValue").mockImplementation(jest.fn(() => mockExpected)); it("returns the expected value", () => { const actual = example.getValue(); expect(actual).toEqual(mockExpected); }); ``` ### Named export of an object In this example, the library exports a named object that has a property for the function we want to mock. ``` export const example = { getValue: () => "real value", }; ``` Mocking `getValue` on the named export is the same as mocking it on the default export 🥳 This is one of the few cases where the export type doesn't matter because it's an object that can be spied on. ``` import { example } from "../namedObject"; const mockExpected = "mock value"; jest.spyOn(example, "getValue").mockImplementation(jest.fn(() => mockExpected)); it("returns the expected value", () => { const actual = example.getValue(); expect(actual).toEqual(mockExpected); }); ``` ### Default export of a function that returns an object This example is a bit more complicated than the previous ones. Here, the library exports a default function that returns an object that has a property for the function that we want to mock. This is a common pattern to allow developers to destructure their desired function off the module function. ``` const { getValue } = example() ``` As a simple example, it looks like this. ``` export default function () { return { getValue: () => "real value", }; } ``` To mock `getValue`, we use a default import to [import the entire module's contents](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/import#Import_an_entire_modules_contents) (the `* as` syntax which allows us to treat the module name as a namespace), spy on the imported module's `default` property, and then chain a mock implementation to the returned mock function. In this case, our mock implementation is a function that returns an object with a `getValue` property. `getValue` is a mock function. ``` import * as exampleModule from "../defaultFunctionReturnObject"; const mockExpected = "mock value"; jest.spyOn(exampleModule, "default").mockImplementation(() => ({ getValue: jest.fn(() => mockExpected), })); it("returns the expected value", () => { const { getValue } = exampleModule.default(); const actual = getValue(); expect(actual).toEqual(mockExpected); }); ``` ### Named export of a function that returns an object Similar to the previous example, the library exports a named function that returns an object that has a property for the function that we want to mock. ``` export function example() { return { getValue: () => "real value", }; } ``` Mocking this use case is very similar to the default export case above except that we need to spy on the named export rather than the default export. To mock `getValue`, we use a default import to import the entire module's contents, spy on the imported module's `example` property (this is the named export), and then chain a mock implementation to the returned mock function. In this case, our mock implementation is a function that returns an object with a `getValue` property, just like in our previous example. ``` import * as exampleModule from "../namedFunctionReturnObject"; const mockExpected = "mock value"; jest.spyOn(exampleModule, "example").mockImplementation(() => ({ getValue: jest.fn(() => mockExpected), })); it("returns the expected value", () => { const { getValue } = exampleModule.example(); const actual = getValue(); expect(actual).toEqual(mockExpected); }); ``` ## Mock behavior We've seen how different export strategies affect how we structure our mocks. Let's look next at how to change our mocks based on the desired behavior we want within our tests. ### Browser functionality #### For the whole test suite If we are using a browser API throughout our application, we may want to mock it for your entire test suite. I reach for this strategy often for localStorage and sessionStorage. For example, here's a mock implementation of `sessionStorage`. ``` export class SessionStorageMock { constructor() { this.store = {}; } clear() { this.store = {}; } getItem(key) { return this.store[key] || null; } setItem(key, value) { this.store[key] = value.toString(); } removeItem(key) { delete this.store[key]; } } ``` And then in the setup file, we'll reset the global `sessionStorage` implementation to our mock implementation for the duration of the test suite. ``` const unmockedSessionStorage = global.sessionStorage; beforeAll(() => { global.sessionStorage = new SessionStorageMock(); }); afterAll(() => { global.sessionStorage = unmockedSessionStorage; }); ``` While the tests run, any code that inserts/removes from `sessionStorage` will use our mock implementation and then we can assert on it in the test files. ``` it("sets sessionStorage isFetching to true", () => { const { getByText } = render(subject); const button = getByText( new RegExp(`please fetch me some cute ${animal}`, "i") ); act(() => { fireEvent.click(button); }); expect(sessionStorage.getItem("isFetching")).toEqual("true"); }); ``` #### In a single file If we're using a browser API, but want different behavior throughout our tests we may choose to mock it in the relevant test files. This is helpful when we're using the browser fetch API and want to mock different responses in our tests. We can use a `beforeEach` block to set our `global.fetch` mock implementation. We set `global.fetch` to a mock function and use Jest's `mockResolvedValue` ([syntactic sugar wrapping `mockImplementation`](https://jestjs.io/docs/en/mock-function-api#mockfnmockresolvedvaluevalue)) to return a mock response in the shape our code expects. ``` beforeEach(() => { jest.resetAllMocks(); global.fetch = jest.fn().mockResolvedValue({ status: 200, ok: true, json: () => Promise.resolve({ media: { poster: "hello" } }), }); }); ``` Then we can assert that `global.fetch` was called the expected number of times. ``` it("fetches an image on initial render", async () => { jest.useFakeTimers(); render(subject); await waitFor(() => expect(global.fetch).toHaveBeenCalledTimes(1)); }); ``` ### Node modules #### For the whole test suite Sometimes we are using a node module throughout our code and we want to mock it for our entire test suite. In this case, we can create a [manual mock](https://jestjs.io/docs/en/manual-mocks) that Jest will automatically use during tests whenever it encounters references to that module. In this little sample application, we're using [Voca](https://vocajs.com/) to capitalize some words in our navigation. To create a manual mock, we create a folder named `__mocks__` inside of our `src` directory and place our mock implementation there. **Note: this is counter to what the documentation says. At the time of writing, there is an [open issue documenting this](https://github.com/facebook/create-react-app/issues/7539). The fix appears to be placing your mocks inside `src` instead of adjacent to `node_modules`.** In our mock, we use [`jest.genMockFromModule` (or `jest.createMockFromModule`)](https://jestjs.io/docs/en/jest-object#jestcreatemockfrommodulemodulename) to create an automock and then extend it with our mock implementation for the relevant function(s). By extending an automock, you limit how often you have to manually update your manual mock when the original module changes. ``` const voca = jest.genMockFromModule("voca"); voca.capitalize = (word) => `${word} capitalize mocked!`; export default voca; ``` Then you can assert on the expected behavior of your mock within your tests. ``` it("capitalizes the current page name", () => { const { getByText } = render(subject); expect(getByText(/capitalize mocked!/i)).toBeInTheDocument(); }); ``` #### In a single file Mocking an entire node module for a single file in our test suite is not that different than what we did to mock it for the whole suite. Instead of placing our code in our setup file, we put it in the test file where we want the mocking to occur. To mock `moment` in one test file, we can do something very similar to what we did for `pluralize`. We use a default import, mock the module, and make sure that the default return shape matches the return shape of the original implementation. Assuming the code we want to test looks like this ``` export const toMoment = (datetime) => { return moment(datetime); }; ``` We would mock `moment` like this ``` import moment from "moment"; jest.mock("moment", () => ({ __esModule: true, default: jest.fn(), })); ``` Then we can assert that our mock moment function was called ``` describe("toMoment", () => { it("calls moment() with the correct params", () => { const dateParam = new Date(); toMoment(dateParam); expect(moment).toHaveBeenCalledWith(dateParam); }); }); ``` If we want to use some of the functions returned from Moment's default function, we need to update our mock to have mock implementations for those as well. ``` let mockFormat = jest.fn(); jest.mock("moment", () => ({ __esModule: true, default: jest.fn(() => ({ format: mockFormat })), })); ``` ### A single function of a node module #### For the whole test suite Just like how we may want to mock browser functionality for our entire test suite, sometimes we may want to mock a node module for our test suite instead of in individual files. In this case, we can mock it in our setup file so that all tests in the suite use that mock. In our sample application, we mock the [Pluralize](https://github.com/blakeembrey/pluralize) module for all of our tests. In our `setupTests.js` file, we mock the default export. ``` jest.mock("pluralize", () => ({ __esModule: true, default: jest.fn((word) => word), })); ``` You'll note that we have `__esModule: true` here. From [Jest's documentation](https://jestjs.io/docs/en/jest-object#jestmockmodulename-factory-options), "When using the factory parameter for an ES6 module with a default export, the \_\_esModule: true property needs to be specified. This property is normally generated by Babel / TypeScript, but here it needs to be set manually." #### In a single file In my experience, the most common mocking use case is to mock the same behavior of one function in a node module for every test in a file. To do this, we declare mock once within the file (remembering what we know about module exports). For example, in our sample application, we use `axios.get` to fetch cute pictures of dogs, cats, and foxes. When we're fetching pictures, we want to make sure our code is correctly calling `axios.get`. And when we're not fetching, we want to make sure we're not making unnecessary requests. To mock `axios.get`, we use a default import, spy on the imported object's `get` property, and then chain a mock implementation to the returned mock function. ``` import axios from "axios"; jest .spyOn(axios, "get") .mockImplementation(() => Promise.resolve({ data: { file: "hello" } })); ``` And then we can assert that `axios.get` was called the expected number of times. ``` it("gets a new image on the configured interval", async () => { jest.useFakeTimers(); render(subject); await waitFor(() => expect(axios.get).toHaveBeenCalledTimes(1)); act(() => jest.advanceTimersByTime(refreshTime)); await waitFor(() => expect(axios.get).toHaveBeenCalledTimes(2)); }); ``` We can also use Jest's syntactic sugar functions to be even terser in our mocking code. The following two examples do the same thing as the mock implementation above. ``` jest .spyOn(axios, "get") .mockReturnValue(Promise.resolve({ data: { file: "hello" } })); ``` And even shorter ``` jest.spyOn(axios, "get").mockResolvedValue({ data: { file: "hello" } }); ``` #### In a single test Finally, sometimes we want to test different behavior within a single test file. We may have error handling or loading states that we want to mock and test that our code behaves appropriately. In this case, we mock the function that we want with Jest's default mock, `jest.fn()`, and then we chain a mock implementation on it inside each of our test cases. I like to put the mock implementation in a `beforeEach` just inside a `describe` labeled with the case I'm testing, but you can also put it inside an individual test. In our sample application code, we mock React Router's `useParams` hook. In our example, we're using Jest's `requireActual` to make sure we're only mocking the `useParams` function and nothing else in the module. ``` import { useParams } from "react-router-dom"; jest.mock("react-router-dom", () => ({ ...jest.requireActual("react-router-dom"), // use actual everything else useParams: jest.fn(), })); ``` And then we can set up our different use cases and assert the expected behavior. ``` describe("with a supported animal type", () => { beforeEach(() => { useParams.mockReturnValue({ animal: mockAnimal, }); }); it("renders the correct animal component(s)", () => { const { getAllByText } = render(subject); expect(getAllByText(new RegExp(mockAnimal, "i")).length).toBeGreaterThan( 0 ); }); }); describe("without a supported animal type", () => { beforeEach(() => { useParams.mockReturnValue({ animal: "hedgehog", }); }); it("does not render an animal component", () => { const { getByText } = render(subject); expect(getByText(/oh no/i)).toBeTruthy(); }); }); ``` ## Common mocking errors I find myself running into similar errors over and over when I'm writing tests. I'm sharing fixes I've found in case it's helpful. ### `The module factory of jest.mock() is not allowed to reference any out-of-scope variables` You'll see this error when you try to use variables that Jest thinks might be uninitialized. The easiest fix is to prefix "mock" to your variable name. Not allowed ``` let format = jest.fn(); jest.mock("moment", () => ({ __esModule: true, default: jest.fn(() => ({ format: format })), })); ``` Allowed ``` let mockFormat = jest.fn(); jest.mock("moment", () => ({ __esModule: true, default: jest.fn(() => ({ format: mockFormat })), })); ``` ### `Cannot spy the default property because it is not a function` You'll see this error if the object does not have a function for the property you are spying. This usually means that you're not structuring your mock properly and the module is exported differently than what you're configuring. Check out the [ES6 Exports](#es6-exports) examples above to see the various ways you may need to change your spy. ### `Cannot set property of #<Object> which has only a getter` This error comes up when trying to mock the implementation for an object which has only getters. Unfortunately, I haven't found a way around this other than completely changing my mocking strategy. I run into this most often with React Router. Spy on default export raises this error ``` import ReactRouterDom from "react-router-dom"; jest.spyOn(ReactRouterDom, "useParams").mockImplementation(jest.fn()); ``` Spy on the module contents raises "property is not a function" error ``` import * as ReactRouterDom from "react-router-dom"; jest.spyOn(ReactRouterDom, "default").mockImplementation(() => ({ useParams: jest.fn(), })); ``` Mocking the module, requiring actual and then overwriting the useParams implementation with a mock function works. ``` jest.mock("react-router-dom", () => ({ ...jest.requireActual("react-router-dom"), // use actual for all non-hook parts useParams: jest.fn(), })); ``` ### `Warning: An update inside a test was not wrapped in act` This is not a mocking error specifically, but one that catches me all the time. If you're seeing this warning but you _know_ that all of your code is wrapped in `act()`, you might be asserting on promises that haven't resolved yet. React Testing Library has a handy little async utility, `waitFor`, for this exact use case. This test raises the "not wrapped in act" warning ``` it("fetches an image on initial render", async () => { jest.useFakeTimers(); render(subject); expect(axios.get).toHaveBeenCalledTimes(1); }); ``` Wrapping the assertion in `waitFor` resolves the warning. ``` it("fetches an image on initial render", async () => { jest.useFakeTimers(); render(subject); await waitFor(() => expect(axios.get).toHaveBeenCalledTimes(1)); }); ```
mercedes
395,649
Váš sken dorazil...
... a je to HTML! Slovo "[EXTERNAL]" do předmětu automaticky vkládá Office 365, aby byl uživatel n...
0
2020-07-13T11:02:50
https://dev.to/rhybnik/vas-sken-dorazil-161a
... a je to HTML! ![Původní e-mail](https://dev-to-uploads.s3.amazonaws.com/i/gc7l3vxyk6vg4b4u5yix.jpg) Slovo "[EXTERNAL]" do předmětu automaticky vkládá Office 365, aby byl uživatel na pozoru. Standardně jej tam ale nenajdete, tak ho budeme ignorovat. V tomto případě je zajímavá hlavně technika zvýšení důvěryhodnosti pomocí "forwardu" z jiné adresy domény microsoft.com. Není ale provedená příliš šikovně. Příloha se bohužel nedochovala, pojďme se tedy alespoň podívat, co je podezřelé v textu. ![Alt Text](https://dev-to-uploads.s3.amazonaws.com/i/k28mqjtvym3jv6tsyr3k.jpg) 1. Adresa odesílatele je zcela jasný signál, že jde o podvod - e-mail se v těle tváří jako Microsoft, ale tady je něco úplně jiného. 1. Ještě nikdy jsem neskenoval přímo do HTML a ani naše tiskárny v kanceláři to v základu nedělají. Je možné, že to umí (nezkoumal jsem), ale šance je malá. 1. Podezřelý účet - rychlé hledání v adresáři prozradí, že takový účet ve firmě není. Kdybychom se zamysleli trochu víc, tak je zvláštní, že "scanner" posílá sken "printeru". 1. Nestandardní formát data. 1. Detail, který ale chytne za oko - "mainPrinter" by mohlo být napsáno alespoň jako "Main printer". 1. Opravdu nemáme jednu "hlavní" tiskárnu.
rhybnik
395,830
Hello World!
A “Hello World!” program is often used as a simplistic introduction to programming languages, as it’s...
0
2020-07-13T14:17:34
https://blog.ganeshagrawal.com/hello-world-ckcex0voq002t9as1cfbpe1vg
A **“Hello World!”** program is often used as a simplistic introduction to programming languages, as it’s generally quite self-explanatory, and simple enough that even those with little or no programming experience can understand its function. However, do not mistake its simplicity for a lack of utility. The program needs a functioning language compiler and run-time to accomplish its task. This makes it ideal for a quick and easy sanity test for new systems. I remember when I started writing codes about a couple of years ago, the very first thing I learned was the famous hello world statement which is sure its the same across all languages. > Despite the myth that “Hello World!” is the first thing to be output by all computers, its prevalence in nearly all facets of technology is undeniable. ![computer programming](https://dev-to-uploads.s3.amazonaws.com/i/oyywbnp6g32mulx904sr.jpg) Getting started in programming is quite fun and the best part is you can write codes at any age! wonderful right? Maybe you can get a little confused at the initial stage regarding what language is the best for you to learn. But believe me, after some time you are going to enjoy typing every single line of code and their outcomes. > Whether you want to uncover the secrets of the universe, or you just want to pursue a career in the 21st century, basic computer programming is an essential skill to learn.” - *Stephen Hawking* As they say, the best time to start is now, don't procrastinate, as long you have the passion and determination their nothing difficult to learn. ```c // "Hello World!" in C int main(){ printf("Hello World!"); return 0; } ``` Language maybe is different but "Hello world!" always be there for showing you the richness of that language. ```javascript // Simple NodeJS Server Application with "Hello World!" const express = require('express') const app = express() const port = process.env.PORT || 3000 app.get('/', (req, res) => res.send('Hello World!')) app.listen(port, () => console.log(`Express app listening on port ${port}!`)) ``` There is no better way to start programming than to start. The most recommended thing is to learn the basics, and for this, the best thing is to rack your brains trying to make a concrete project or an application that you want to create or develop. Having a specific goal helps a lot. > **TL;DR** - It has been a long one and remember to *keep reading code, keep writing code, do not forget to try what it does*. Once comfortable in a language, moving on to the next will be easier and will bring you new skills. `Ufff!` In this "Hello World!" myth I forgot that this is actually my first post here, so I have to introduce myself to you or maybe it's my own "Hello World!". ## About Me Hello! my name is Ganesh Agrawal. If you want to know more about me you can see [here](https://www.linkedin.com/in/iamganeshagrawal/), you must be new here, so I decided to write my first post talking a little about my motivations to have a blog. I intend to share the knowledge that I have been acquiring as a way to validate, memorize, and help other beginners who are going through the same problems and doubts. Also, I am thinking about post web development tips mainly, a little bit of theory about what I've been studied in my academic life, reviews of technology books, events, courses, and whatever else comes to mind. So that's it, feel free, pour yourself a coffee, and wait for new posts to exchange ideas about the world **`dev`**.
ganeshagrawal
396,019
JavaScript: Type Conversion
To Binary JavaScript has two boolean values: true and false. But, it also treats certain v...
7,685
2020-07-13T16:33:41
https://dev.to/bhagatparwinder/javascript-type-conversion-14eg
javascript, codenewbie, tricks
## To Binary JavaScript has two boolean values: `true` and `false`. But, it also treats certain values as `truthy` or `falsy`. All values are `truthy` except `0`, `null`, `undefined`, `""`, `false`, and `NaN`. We can switch values between true and false using the negation operator `!`. This conversion also converts the type to `boolean`. ```javascript const a = null; const b = undefined; const c = ""; const d = 0; console.log(typeof a); // object console.log(typeof b); // undefined console.log(typeof c); // string console.log(typeof d); // number const w = !a; const x = !b; const y = !c; const z = !d; console.log(typeof w); // boolean console.log(typeof x); // boolean console.log(typeof y); // boolean console.log(typeof z); // boolean ``` This did change the type to boolean, but it also switched the value. If you need conversion to boolean but stay on the same `truthy` or `falsy` side, use `!!` 🤯 ```javascript const a = null; const b = undefined; const c = ""; const d = 0; console.log(typeof a); // object console.log(typeof b); // undefined console.log(typeof c); // string console.log(typeof d); // number const w = !!a; const x = !!b; const y = !!c; const z = !!d; console.log(typeof w); // boolean console.log(typeof x); // boolean console.log(typeof y); // boolean console.log(typeof z); // boolean // Let's check if they are all false though and haven't switched to true! console.log(w); // false console.log(x); // false console.log(y); // false console.log(z); // false ``` ## To String Use `toString()` method. ```javascript const num = 7; console.log(typeof num); // number const numString = num.toString(); console.log(typeof numString); // string ``` Or use the shortcut by appending to `""` 🤯 ```javascript const num = 7; console.log(typeof num); // number const numString = num + ""; console.log(typeof numString); // string ``` ## To Number `parseInt()` function parses a string and returns an integer. You pass the string as the first parameter and the second parameter is radix. It specifies which numeral system to use: hexadecimal (16), octal (8), or decimal (10). ```javascript console.log(parseInt("0xF", 16)); // 15 console.log(parseInt("321", 10)); // 321 ``` Or use the shortcut by adding `+` operator in front of the string! 🤯 ```javascript console.log(+"0xF"); // 15 console.log(+"321"); // 321 ``` There are situations where the `+` operator might be used for concatenation. In that case, use the bitwise NOT operator ~ twice. ```javascript console.log(~~"0xF"); // 15 console.log(~~"321"); // 321 ```
bhagatparwinder
396,222
Easy Deployment Setup With Bitbucket and AWS ECS
Deploy to AWS ECS via Bitbucket
0
2020-07-13T17:57:00
https://dev.to/olaoluwa98/easy-deployment-setup-with-bitbucket-and-aws-ecs-46ac
deployment, aws, bitbucket, docker
--- title: "Easy Deployment Setup With Bitbucket and AWS ECS" published: true description: "Deploy to AWS ECS via Bitbucket" tags: [Deployment,AWS,Bitbucket,Docker] --- Deployment is one of the most important parts of product development and launch. The better the deployment process is the faster it is. There are many deployment tools that make things easier today. In this article, I will take you through a deployment setup with Bitbucket and AWS Elastic Container Service (ECS). ## Requirements - Basic knowledge of `git` version control - Basic knowledge of `Docker` - An AWS account - A Bitbucket account [Bitbucket](https://bitbucket.org/) is a web-based version control repository hosting service owned by Atlassian. They have built-in Continuous Integration and Delivery/Deployment (CI/CD). We'll deploy a simple express app. Let's generate an express app ```sh npx express-generator ``` If you don't have npx, you can install `express-generator` globally ```sh npm install -g express-generator express ``` Now we have our express app, let's create a docker file that we would use for deployment ```sh touch Dockerfile ``` Copy this and paste in your `Dockerfile` ```docker FROM node:8-alpine WORKDIR /usr/src/app COPY package*.json ./ RUN npm install COPY . . EXPOSE 3000 CMD [ "npm", "start" ] ``` ## Setup AWS ECS Login to your AWS account and navigate to [ECS](https://console.aws.amazon.com/ecs/home). ![AWS ECS Home page](https://dev-to-uploads.s3.amazonaws.com/i/7mj71cdr0osi57nrjqtc.png) Navigate to **Repositories** under Amazon Elastic Container Registry (ECR). AWS ECR is a container registry for docker. It's similar to Docker Hub. Container registries are used to store and distribute docker images. Create a repository by clicking the 'Create repository' button then give it a name like `my-express-app`. ![AWS ECR](https://dev-to-uploads.s3.amazonaws.com/i/eeigwdzn6vzfwt7r4apd.png) Now we have our repository URI: `XXXXXXXXXXX.region.amazonaws.com/my-express-app` ## Pushing to AWS ECR We will build our docker image and push it to our newly created repository on ECR. For this article, we'll use `docker build`. If you have a more complex project setup, you may want to consider [docker-compose](https://docs.docker.com/compose/) cd into the folder where the `Dockerfile` is and run ```sh docker build -t my-express-app . ``` If the command ran well, you should have this: ![Run docker build](https://dev-to-uploads.s3.amazonaws.com/i/yp3382z0s85dnpx8sd6t.png) To push the image to ECR, you have to first install [aws cli tool](https://docs.aws.amazon.com/cli/latest/userguide/install-cliv2.html). Run `aws2 configure` to enter your AWS access ID and secret access key. Once you're done, run this command: ```sh $(aws2 ecr get-login --no-include-email --region us-east-1) ``` Then push the docker image. For the `--region` option, put your own region. ```sh docker tag my-express-app:latest XXXXXXXXXXX.region.amazonaws.com/my-express-app:latest docker push XXXXXXXXXXX.region.amazonaws.com/my-express-app:latest ``` ## Setup ECS Cluster Navigate to the Clusters page. Click Create Cluster. ![Creating a cluster](https://dev-to-uploads.s3.amazonaws.com/i/6j1xqf8k8xee9efxu3fj.png) We will use EC2 Linux + Networking. You can use the following configuration to create the cluster: - Give your cluster a name. - Create an empty cluster: Unchecked - Provisioning Model: On-Demand Instance - EC2 instance type: t2.nano (You can use whatever will fit your application needs) - Number of instances: 1 - EC2 Ami Id: Amazon Linux 2 AMI [ami-08b26b905b0d17561] - Root EBS Volume Size (GiB): 30 - Key pair: You can create anyone and attach it. This is the key you can use to ssh into the ec2 instance. - Networking: You can create a new VPC or use an existing one. - Auto-assign public IP: Use subnet settings - Security group: Create a one that opens up port 80 - CloudWatch Container Insights: Unchecked ## Create an Application Load Balancer An Application Load Balancer allows us to dynamically assign applications to routes using pattern matching. This will be used in the ECS Service To create one, navigate to the load balancers tab on [EC2](console.aws.amazon.com/ec2) and click on Create Load Balancer ![Create Load Balancer](https://dev-to-uploads.s3.amazonaws.com/i/dku843c8ejl9czfpnjd0.png) Give it a name, fill the Availability Zones, and add a security group that exposes port 80 and 443 (if you want to enable SSL). In Step 4: Configure Routing, you'd create a target group. You can skip Step 5. ## Setup ECS Task Definition & Service A task definition specifies the container information for our application. Navigate to Task Definitions and click on Create new Task Definition. Select EC2 as launch type compatibility ![Task definition](https://dev-to-uploads.s3.amazonaws.com/i/19n9gzhbfe5n8zfsobqy.png) You can use the following configuration to create the task definition: - Task Definition Name: my-express-app - Task Role: Leave empty - Network Mode: default - Task memory (MiB): 128 (You can use whatever size that fits your application needs) - Task CPU (unit): 128 (You can use whatever size that fits your application needs) - Container: Click on Add container - Container name: my-express-app - Image: XXXXXXXXXXX.region.amazonaws.com/my-express-app:latest - Port mappings: Host - 0, Container port: 3000 - Configure the remaining to fit your application needs - You can enable Log configuration so you can view the application logs on [CloudWatch](https://console.aws.amazon.com/cloudwatch/home). Once you're done, click on Create. Next, we'll create a Service. A service lets you specify how many copies of your task definition to run and maintain in a cluster. Click the `Actions` dropdown and select Create Service ![Creating an ecs service](https://dev-to-uploads.s3.amazonaws.com/i/fjt0agb2fh04wpuqksxa.png) You can use the following configuration to create the service: - Launch type: EC2 - Task Definition: my-express-app - Cluster: my-express-app (or whatever cluster you created) - Service name: MyExpressAppService - Service type: Replica - Number of tasks: 1 (Or whatever number fits your application needs). - Minimum healthy percent: 100 - Maximum percent: 200 - Deployment type: Rolling update - Placement Templates: AZ Balanced Spread - Load balancing: Application Load Balancer - Load balancer name: Select the load balancer we created earlier - Container to load balance: Click on Add to load balancer - Select the target group we created earlier or create a new one here - Use default in the remaining steps or configure to your application needs Once the service is created, it'll run the task in the cluster. ## Setup CD with Bitbucket We are going to create a new repository on Bitbucket. You can name it anything. I named mine `my-express-app`. ![Creating bitbucket repository](https://dev-to-uploads.s3.amazonaws.com/i/zca6vlqcalj5310emq24.png) Automated CI/CD comes built-in with Bitbucket. To enable it, navigate to Repository Settings > Pipelines > Settings and switch it on. ## Bitbucket pipeline file Bitbucket uses a file named: bitbucket-pipelines.yml for automating CI/CD. Create the file. ```yml definitions: services: push-image: &push-image name: Build and Push Docker Image image: atlassian/pipelines-awscli caches: - docker services: - docker script: - export BUILD_ID=$BITBUCKET_BRANCH_$BITBUCKET_COMMIT_$BITBUCKET_BUILD_NUMBER - export DOCKER_URI=$DOCKER_IMAGE_URL:latest # Login to docker registry on AWS - eval $(aws ecr get-login --no-include-email) # Build image - docker build -t $DOCKER_URI . # Push image to private registry - docker push $DOCKER_URI deploy-to-ecs: &deploy-to-ecs name: Deploy to ECS image: atlassian/pipelines-awscli script: - pipe: atlassian/aws-ecs-deploy:1.1.0 variables: AWS_ACCESS_KEY_ID: $AWS_ACCESS_KEY_ID AWS_SECRET_ACCESS_KEY: $AWS_SECRET_ACCESS_KEY AWS_DEFAULT_REGION: $AWS_DEFAULT_REGION CLUSTER_NAME: 'my-express-app' SERVICE_NAME: 'MyExpressAppService' TASK_DEFINITION: "task-definition.json" pipelines: branches: master: - step: *push-image - step: *deploy-to-ecs ``` You'd notice `TASK_DEFINITION`. This is needed to update the ECS service for deployment. So let's create one: ```sh touch task-definition.json ``` Paste this in the task definition file ```json { "containerDefinitions": [ { "logConfiguration": { "logDriver": "awslogs", "options": { "awslogs-group": "/ecs/my-express-app", "awslogs-region": "us-east-1", // use your own region "awslogs-stream-prefix": "ecs" } }, "portMappings": [ { "hostPort": 0, "protocol": "tcp", "containerPort": 3000 } ], "cpu": 0, "image": "XXXXXXXXXXX.region.amazonaws.com/my-express-app:latest", "essential": true, "name": "my-express-app" } ], "memory": "128", "family": "my-express-app", "requiresCompatibilities": ["EC2"], "cpu": "128" } ``` Now we need to put the following environment variables on our bitbucket repository: - DOCKER_IMAGE_URL - AWS_DEFAULT_REGION - AWS_ACCESS_KEY_ID - AWS_SECRET_ACCESS_KEY Navigate to Repository Settings > Repository variables > ![Bitbucket repository variables](https://dev-to-uploads.s3.amazonaws.com/i/5k9kb0946m1fn0jt3b0m.png) Once you add them, commit and push to bitbucket to trigger the pipeline and the deployment process is run. The following things occur: - The docker image is built and pushed to the AWS ECR repository you created - The task definition is updated with the `task-definition.json` file - The service (MyExpressAppService) is updated - The service automatically registers a new instance of the task and begins draining the old task running - The new task is dynamically registered on the Application Load Balancer You can check the full bitbucket repository [here](https://bitbucket.org/olaoluwa-98/my-express-app)
olaoluwa98
396,223
The 7 Most Popular DEV Posts from the Past Week
A round up of the most-read and most-loved contributions from the community this past week.
0
2020-07-14T15:48:52
https://dev.to/devteam/the-7-most-popular-dev-posts-from-the-past-week-3m5
top7
--- title: The 7 Most Popular DEV Posts from the Past Week published: true description: A round up of the most-read and most-loved contributions from the community this past week. tags: icymi cover_image: https://thepracticaldev.s3.amazonaws.com/i/sfwcvweirpf2qka2lg2b.png --- _Every Tuesday we round up the previous week's top posts based on traffic, engagement, and a hint of editorial curation. The typical week starts on Monday and ends on Sunday, but don't worry, we take into account posts that are published later in the week. ❤️_ ### One dev's SCSS "Northstar" tips Annie shares eight of SCSS best practices from the guideline that made them rethink the way they structure their CSS code (— tips are geared towards SCSS vs pure CSS). {% link https://dev.to/liaowow/8-css-best-practices-to-keep-in-mind-4n5h %} ### 👀 💡 ⚛️ 🙌🏽 Three cheers for Naya, who created Gomojii, an emoji themed application that will contain multiple emoji-themed widgets using React + Redux. {% link https://dev.to/greedybrain/react-redux-project-gomojii-5d6i %} ### On the flip side... Gabriel calls for an embrace of the "separation of backend from frontend instead of remaining in [an] ambiguous in-between state." {% link https://dev.to/g_abud/why-i-quit-redux-1knl %} ### "Did someone say GIFs!?" Monica walks us through the new GitHub profile-level README feature in all its glory, which includes utilization of more fun visual components like gifs! {% link https://dev.to/m0nica/how-to-create-a-github-profile-readme-1paj %} ### According to our calculations, dark mode looks really good This simple tutorial (using HTML, CSS, and JavaScript) will get you a slick calculator with dark mode. Thanks, Mohammad! {% link https://dev.to/mohammadfarmaan/simple-calculator-with-dark-mode-545c %} ### Investing your luck in an independent future Ilona explains that developers are lucky in having found a growing, lucrative career path. But they also believe that without a sound investing and saving practice, you'll be left spinning your wheels financially. Ilona to the rescue! {% link https://dev.to/ilonacodes/the-importance-of-financial-independence-for-software-developers-98m#chapter-4 %} ### "Find flaws and fix them!" Emmanuel shares an awesome generalization of the flaws and fixes for front-end frameworks for Web Apps in Rust, complete with pros, cons, and actionable takeaways {% link https://dev.to/emmanuelantony2000/valerie-rethinking-web-apps-in-rust-4cl3 %} _That's it for our weekly wrap up! Keep an eye on dev.to this week for daily content and discussions...and if you miss anything, we'll be sure to recap it next Monday!_
jess
396,395
Javascript way to go / Guide / Something
Heeeey, this is the first time Im writting here. Sorry for my broken english. My name is Ernesto, I...
0
2020-07-13T20:06:47
https://dev.to/skullflowerss/javascript-way-to-go-guide-something-465j
javascript, beginners, tutorial
![Alt Text](https://dev-to-uploads.s3.amazonaws.com/i/gx8jori20nuocw5g0s5n.jpg) Heeeey, this is the first time Im writting here. Sorry for my broken english. My name is Ernesto, I am from Mexico City and I started coding few years ago. When I was in college I started learning Java and C++, only the basic things. Data types, loops, if/else, arrays, functions, etc. It was like an intro. In those days I stopped, because I didn't had an idea where to start to do something more complicated and the aplications of it. After I finished college, I wonder what to do, find something to do with my life. I always had an inclination for art, in that moment I found text's about glitchart from Rosa Menkman and Iman Moradi. Something... exploded inside. It was a whole new world about the guts of the computer and the meaning of an error being show and how the different programs show that. ![Alt Text](https://dev-to-uploads.s3.amazonaws.com/i/5rp3xutl6mor0ql31l3j.jpg) In the glitch sources/texts in glitchet.com, there was some sketches and scripts about pixel sorting and I was thrilled, they were made with "Processing". Surfing in youtube I found Coding Train channel. There was a lot of explanations about code, about this program thing called "Processing" that was used to learn to code and do art things realeted. So then... here we go. My first "language", if you want to call it like that, was processing. My source to understand was the processing book "Learning Processing: A Beginner's Guide to Programming Images, Animation, and Interaction" by Daniel Shiffman. I passed 6 months studying, understanding, making a lot of sketches and owning those. Making my variations. There was a lot of stuff in there. It was cool. Now I can proudly say that I know how to program with Processing, most of the art I make is with. But as everything, theres still a long long way to go. I'm better than few years ago, but well, I need to keep improving. ![Alt Text](https://dev-to-uploads.s3.amazonaws.com/i/7i3wyr9laqmsdk9wlxy1.jpg) ![Alt Text](https://dev-to-uploads.s3.amazonaws.com/i/axk81z5se8mdzipb13u6.jpg) All of this was the intro to understand the slippery slope that is learning to code, not get discouraged and fail. Processing was a cool way to start because I had a visual representation about what I was doing. If I write "line(100,100,200,200)" and execute the code, yes, you can see it in the screen a 100px line from point A (100,100) to point B (200,200). This year my challenge was p5js ergo Javascript. Plus I want to learn web development and do some art projects with it. Processing has a version for JS that is p5.js. You can see that they are similar, they have few things that are the same as the "java" version, but the way p5js behave is much MUCH different than processing. The example is the data types. In Processing when you declare a variable, you need to specify is an "int", a "float", a "String", etc. int a = 2; float speed = 0.48293; In p5js you can leave "let" or "var" or "const" and assign the value "slkasd" - string, 039.984 - float, 1 - int without having to specify since the beginning of the declaration of the variable and it will know without those terms in the beginning. let a = 2; const a = 'this is a string and js knows it because this is a string you know???" The journey then beginns, again. All over again. The idea in general of the post and the following is to try to explain what im doing. Explain some concepts in my way and try to make an archive. I just want to say thanks to Tae'lur Alexis // @taeluralexis // I was reading some of the post about JS that she made and that gave me the courage to do this and keep working in this. Thank you so much, really ;___; ![Alt Text](https://dev-to-uploads.s3.amazonaws.com/i/6mjr6uwvgc3ylg3b0ex5.jpg) ## Sourcessssss ### Books **Head First Javascript Programming by Eric Freeman & Elisabeth Robson** This works for the basics, but is way way before es6 and you can see it because they are still using 'var' but is a good book. **Eloquent JavaScript by Marjin Haverbeke** The first 4 chapters work if you have a little bit of understanding of JS, the next are like trying to understand how to turn a fish into a dog. I mean is not difficult but most of the examples take a little bit of time. The site of the book is pretty good and even you can se the output of the code that is being show as an example https://eloquentjavascript.net/ **Make: Getting Started with P5js by Lauren McCarty, Casey Reas & Ben Fry** This goes align with the p5js library. Is really good if you want to start learning, but if your main goal is JS as a primary language it can be a start. ### Internet **MDN - Javascript** https://developer.mozilla.org/en-US/docs/Web/JavaScript If you want a bible, here is your bible. You want to find documentation about JS, here is your main source. array.reduce(), filter(),reverse(),regex,etc........ DESTRUCTING and the array with three dots in the beginning. **W3schools - Javascript** https://www.w3schools.com/js/default.asp Is the same as MDN but some general explantions, they can give you a quick answer if you want. ### Videos **Coding Train** https://www.youtube.com/watch?v=q8SHaDQdul0&list=PLRqwX-V7Uu6YgpA3Oht-7B4NBQwFVe3pr Dan Shiffman have this beautiful channel and sometimes or pretty much all the time he makes livestreams with coding challenges or explaining how to do certain things or concepts. Is pretty good and dude, was my first entry to do all of this. **Coding Garden** https://www.youtube.com/channel/UCLNgu_OupwoeESgtab33CCw CJ is really cool. Thats the statement. The channel is more related to web development, but theres some playlist with topics about JS and he makes livestreams too. Even he builds projects with JS and you can see how it works, the reason of some stuff that is in the code. Pretty good. **Fun Fun Function** https://www.youtube.com/channel/UCO1cgjhGzsSYb1rsB4bFe4Q Mattias is another cool dude that make me try this. He has content related with js and more like managment in a way "the way to do some projects is with this aproach or doing this", etc. It was my spirit guide all the time. **Dev.to** The cool thing is you can filter post and find JS related things or even guides. Thats all. If in the future theres more links or stuff im reading, I will update this post. ### EXERCISE **Edabit** https://edabit.com/ okey, we need practice and theres no better way than learning with problems and understanding some things and getting resources to solve that. Edabit is pretty good, the problems have levels, theres a kind of index thing where they lead you to a way to solve the problem. I want to add codewars but I havent really try yet. ## The difference between pay and free Some of the source to learn JS can be udemy, freecode, codeacademy. I mean you can choose the option you want if you have the bucks to pay it, but in the end you can find some stuff free in the internet with enough research. ## JS and the infinte problem So much of the sources here are going to show you the basics. The books will lead you to go in different directions and maybe, MAYBE you will end in a horrible loop of doing things and feel chronostacis in real life. My answer to all of that, dont rush. Take your time. This is about being constant than being a fast learner. Sucks, but is the truth. One of my main problems is... okey I have this book, they show me some concepts, then what? this is it? An object and how to access the object???? eh??? But the situation is that. So pretty much try to exange, build projects, try to write what you do. Before trying JS hard as I could one of my projects was a tile thing. Tile art is pretty neat and I wanted to make like an api (i wanst aware of the in the first moment), but i tried to make something with p5js. https://skullflowerss.github.io/tilesproject/ The other one is like the first but with domino tiles and trying to go negative??? https://skullflowerss.github.io/Domino-project/ All of them are my babies and my first steps. So... thats it. I hope you like it. I will keep writting, not a regular as I want to believe but I want to try.
skullflowerss
396,673
Day 43 : #100DaysofCode - The Amazing Faker Gem
If you are relatively new to code and learning all about Ruby and Ruby on Rails, then you most likely...
7,070
2020-07-14T02:45:09
https://dev.to/sincerelybrittany/day-43-100daysofcode-the-amazing-faker-gem-2d28
100daysofcode, codenewbie
If you are relatively new to code and learning all about Ruby and Ruby on Rails, then you most likely have experience or heard of the ``seed.rb`` file. The file allows us to create objects/ data and add it to our database. In general, you would run ``rails db:seed`` or ``rake db:seed`` AFTER running your migration. Today, I wanted to add information to my seeds file so that I could manipulate and interact with the data in my console to confirm that everything was working properly. My schema was simple, it looked like this: ``` create_table "patients", force: :cascade do |t| t.string "name" t.integer "age" t.datetime "created_at", null: false t.datetime "updated_at", null: false end ``` In order to generate information in my database, I was going into my console or manually creating the information by manually creating objects and filling them in like so: ``` homer = Patient.create({name: "Homer Simpson", age: 38}) bart = Patient.create({name: "Bart Simpson", age: 10}) marge = Patient.create({name: "Marge Simpson", age: 36}) ``` But then I was introduced to the <a href="https://github.com/faker-ruby/faker"> Faker Gem </a> that changed my life. First, I added the faker gem to my Gemfile ``gem 'faker'`` then I added this simple iteration to my ``seeds.rb`` file: ``` 5.times do |t| name = Faker::Name.name age = Faker::Number.between(from: 15, to: 90 ) Patient.create(name: name, age: age) end ``` Lastly, I ran ``rails db:seed`` and TADA, my database was filled with five patients. The <a href="https://github.com/faker-ruby/faker"> Faker Gem </a> has tons of information available for times when you need to generate information quickly for your database. I recommend checking out the documentation and adding it when necessary to save you the time. I hope this helps another code newbie like myself. Thanks for reading! Sincerely, Brittany
sincerelybrittany
399,730
Java OOP Cheatsheet
I will be exploring Java OOP concepts with relevant real-life examples as well as the coding...
0
2020-07-16T06:58:50
https://dev.to/sivantha96/java-oop-cheatsheet-3ph1
java, jvm
I will be exploring Java OOP concepts with relevant real-life examples as well as the coding examples. So let us get started. Here is the order that I am going to discuss each OOP concept. [1. Encapsulation](#encapsulation) [2. Inheritance](#inheritance) [3. Polumorphism](#polymorphism) [2. Abstraction](#abstraction) #Encapsulation #### What is encapsulation? Wrapping the fields (state) and methods (behaviors) together as a single unit in a way that sensitive data are hidden from the users. #### What is an example of encapsulation in the real word? With an ATM, we can perform operations like cash withdrawal, money transfer, balance checks. But only the account owner can perform those operations. So, all the operations are encapsulated inside an object for that particular account owner. And the only way to access data like the balance is by using the predefined operations such as balance checks. #### How to achieve encapsulation in Java? Using access modifiers like `private` and `protected` for class variables (fields) and providing getters and setters to access them if necessary. ````java public class Person { private String name; // using private access modifier // Getter public String getName() { return name; } // Setter public void setName(String newName) { this.name = newName; } } ``` #### Why use encapsulation? 1. **Data Hiding** - Data inside an encapsulated class can only be accessible inside the class or through a getter or a setter method. 2. **Flexibility** - We can make variables read-only or write-only by omitting the getter or setter of that variable 3. **Reusability** 4. **Easy to perform unit testing** #Inheritance #### What is inheritance? A mechanism where an object of the subclass (child class), acquires all the properties (fields) and behaviors (methods) of an object of the superclass (parent class) #### How to achieve inheritance in Java? By extending the child class to parent classes using `extends` or `implements` keywords. ````java // parent class class Employee { float salary = 100; // property of the parent class } // child class class Programmer extends Employee { float bonus = 30; } // My main class class MyMainClass { public static void main(String[] args) { Programmer myVariable = new Programmer() System.out.println("My salary is " + myVariable.salary ); System.out.println("My bonus is " + myVariable.bonus ); } } ``` The result will be ```bash My salary is 100 My bonus is 30 ``` Here, `myVariable` object has access to the `salary` which belongs to the parent class even though `myVariable` is an object of the child class. #### Why use inheritance * For code reusability * To take advantage of polymorphism #Polymorphism #### What is polymorphism? Perform a single action in different ways #### What is an example of compile-polymorphism in the real word? A man can be a father, a husband, and an employee according to the situation he is in. #### How to achieve polymorphism in Java? There are two types of polymorphism in java 1) Compile-time polymorphism (Static polymorphism) 2) Run-time polymorphism (Dynamic polymorphism) #### What is Compile-time polymorphism When **method overloading** is used, which method to call is resolved during the compile time by looking at the signature of the method invoke statement. #### What is method overloading? A feature that allows a class to have more than one method having the **same name** but with different signatures. #### What is the signature of a method? The signature of a method is determined by the **number of arguments**, **types of each argument**, and the **order of the arguments**. The return type of the method does not affect the signature. ````java // A class with multiple methods with the same name public class Adder { // method 1 public void add(int a, int b) { System.out.println(a + b); } // method 2 public void add(int a, int b, int c) { System.out.println(a + b + c); } // method 3 public void add(String a, String b) { System.out.println(a + " + " + b); } } // My main class class MyMainClass { public static void main(String[] args) { Adder adder = new Adder(); // create a Adder object adder.add(5, 4); // invoke method 1 adder.add(5, 4, 3); // invoke method 2 adder.add("5", "4"); // invoke method 3 } } ``` The result will be ```bash 9 12 5 + 4 ``` #### What is Run-time polymorphism When **method overriding** and **upcasting** is used, which class's method to call is resolved during the run-time. #### What is method overriding? Providing a specific implementation in the child class (subclass) of a method that already provided by one of its parent classes (super-classes). And also, the method in the subclass should have the **same signature** and the **same return type** for it to override the superclass method. #### What is upcasting? When the reference variable of the parent class is referring to an object of the child class, it is upcasting. In other words, casting an object of an individual type to one common type. #### What is downcasting? When the reference variable of the child class is referring to an object of the parent class, it is downcasting. In other words, casting an object of a common type to a narrower (special) type. #### Real-life example of Upcasting & Downcasting Assume there are classes named, `Fruits` and `Apple`. And the `Apple` class is the child class of the `Fruits` class. If we cast an object of the `Apple` class to `Fruits` type, it is Upcasting. If we cast an object of the `Fruits` class to `Apple` type, it is Downcasting #### Remarks * Upcasting can be done directly in Java. But Downcasting cannot. We have to do the casting **explicitly**. * But we have to be careful not to downcast incompatible types. Unless it will throw an error. ````java class Fruits {} // parent class class Apple extends Fruits {} // child class // My main class class MyMainClass { public static void main(String[] args) { Fruits upcastedVariable = new Apple() // upcasting (implicit casting) Apple downcastedVariable = (Apple) upcastedVariable // downcasting (explicit casting) } } ``` Here `upcastedVariable` can be downcasted into `Apple` because, even though `upcastedVariable` is `Fruit` type, it refers to an object of the `Apple` class. ````java class Fruits {} // parent class class Apple extends Fruits {} // child class // My main class class MyMainClass { public static void main(String[] args) { Fruits myVariable = new Fruits() Apple downcastedVariable = (Apple) myVariable // throws an error } } ``` But in the above example, `myVariable` is `Fruit` type as well as it refers to a `Fruit` object. Therefore when we downcast into the `Apple` type it will throw an error. ````java // parent class class Bank { public float getInterestRate() { return 0 } } // child class - 1 class AwesomeBank extends Bank { public float getInterestRate() { // superclass's method is overridden return 8.4; } } // child class - 2 class SuperBank extends Bank { public float getInterestRate() { // superclass's method is overridden return 9.6; } } // child class - 3 class GovernmentBank extends Bank {} // superclass's method is not overridden // My main class class MyMainClass { public static void main(String[] args) { Bank b = new Bank() System.out.println(b.getInterestRate()); b = new AwesomeBank() // upcasting System.out.println(b.getInterestRate()); b = new SuperBank() // upcasting System.out.println(b.getInterestRate()); b = new GovernmentBank() // upcasting System.out.println(b.getInterestRate()); } } ``` The result will be ```bash 0 8.4 9.6 0 ``` Since in `AwesomeBank` class the `getInterestRate()` method is not overridden, the method in the parent class will be called in the run-time. #Abstraction #### What is abstraction? Hiding certain details and showing only the essential information to the user. In other words, identifying only the required characteristics of an object ignoring the irrelevant details. #### What is an example of abstraction in the real word? With an ATM, we can perform operations like cash withdrawal, money transfer, balance checks, etc. But we can't know the internal details about those operations, how they operate or likewise. #### How to achieve abstraction in Java? Using either an `abstract class` or an `interface` ### Abstract class #### What is an abstract class? A class contains both abstract and regular methods. #### What is an abstract method? A method without a body (i.e. no implementation). The implementation is provided by the subclass that inherits the abstract class ````java // abstract class abstract class Animal { public abstract void animalSound(); // abstract method public void sleep() { System.out.println("Zzzzzz!") } } ``` #### Remarks * `abstract` keyword is a non-access modifier, used for classes and methods. * You don't have to implement (override) all methods of an abstract class. But you **must implement all the abstract methods** in it. * You cannot create objects from an abstract class * To access an abstract class you have to inherit (`extend`) it from another class * Fields in an abstract class should **not have to be** `public`, `static`, and `final` * You can have `public`, `private` or `protected` methods ````java // abstract class abstract class Animal { public abstract void animalSound(); // abstract method public void sleep() { System.out.println("Zzzzzz!") } } // subclass (inherits the abstract class) class Pig extends Animal { public void AnimalSound() { // body of the abstract method is provided here System.out.println("Wee Wee!"); } } // My main class class MyMainClass { public static void main(String[] args) { Pig myPig = new Pig(); // create a Pig object myPig.animalSound(); myPig.sleep(); } } ``` The results will be ```bash Wee Wee! Zzzzzz! ``` #### Why use Abstract classes? To have some methods to implement later. If you don't use an abstract class, you have to implement the `AnimalSound()` method in the `Animal` class even if you inherit it from another class. ### Interface #### What is an interface? A completely abstract class. In other words, all the methods in an interface should not have a body. ````java // interface interface Animal { public void animalSound(); // interface method public void sleep(); // interface method } ``` #### Remarks * You cannot create objects from an interface. * To access an interface you have to `implement` (kinda like inherit) it from another class. * You must override all the methods in an interface from a subclass. * All the fields in an interface are `public`, `static`, and `final`. * All the methods are `public` ````java // interface interface Animal { public void animalSound(); // interface method public void sleep(); // interface method } // subclass (implemets the abstract class) class Cat implements Animal { public void AnimalSound() { // body of the interface method is provided here System.out.println("Meow!"); } public void sleep() { // body of the interface method is provided here System.out.println("Purrrrr!"); } } // My main class class MyMainClass { public static void main(String[] args) { Cat myCat = new Cat(); // create a Cat object myCat.animalSound(); myCat.sleep(); } } ``` The results will be ```bash Meow! Purrrrr! ``` #### Why use Interfaces? * To specify the behavior of a particular data * To achieve **multiple inheritance**. > Java doesn't support multiple inheritances. ( You can only inherit from a single superclass.) However, it can be achieved using interfaces.
sivantha96
396,822
Hi ! Help Needed to remove custom Domain on GitHub pages
Hi!, someone who are familiar with GitHub. Please help me. I added a custom domain to use GitHub page...
0
2020-07-14T06:23:29
https://dev.to/ajaydaram/hi-help-needed-to-remove-custom-domain-on-github-pages-ai8
Hi!, someone who are familiar with GitHub. Please help me. I added a custom domain to use GitHub pages. Now I decided to remove but I don't know how to do it. The problem is this: when i created dummysite.github.io to publish, it is always pointing to www.dummysitesz.com. How to remove the custom domain?
ajaydaram
396,959
Testing a Nuxt.js application using WebdriverIO
Recently WebdriverIO has been added in Nuxt.js create-nuxt-app scaffolding tool as a test framework o...
0
2020-07-14T16:11:31
https://dev.to/astagi/testing-a-nuxt-js-application-using-webdriverio-1215
vue, javascript, nuxt, tutorial
Recently [WebdriverIO](https://webdriver.io/) has been added in [Nuxt.js create-nuxt-app scaffolding tool](https://github.com/nuxt/create-nuxt-app) as a test framework option to provide end to end browser and mobile automation testing. In this tutorial you'll learn how to test a Nuxt.js app with WebdriverIO following the [Page Object pattern](https://martinfowler.com/bliki/PageObject.html) and set up Continuous Integration with [TravisCI](https://travis-ci.org/) using WebdriverIO hooks. ## Create a simple to-do list application In this section we're going to create a very simple to-do list app: when users write inside the text field and press the "enter" key, a new item will be added to the list, then they can click on items to mark them as completed. You can play with the app [here ✅](https://affectionate-benz-1fb9fd.netlify.app/). <img alt="Final result" src="https://github.com/astagi/wdio-nuxt-e2e/blob/master/static/sampleapp.png?raw=true" width="650"> 👉🏻 Some parts of code are omitted for the sake of simplicity, [check the complete code on Github](https://github.com/astagi/wdio-nuxt-e2e). Let's start! Create the app using [create-nuxt-app](https://github.com/nuxt/create-nuxt-app) scaffolding tool ```bash npx create-nuxt-app todolist ``` And select `WebdriverIO` testing framework ```bash ? Testing framework: None Jest AVA ❯ WebdriverIO ``` Then create the store files inside `store/todos` folder `getters.js` ```js export default { todos (state) { return state.list } } ``` `state.js` ```js export default () => ({ list: [] }) ``` `mutations.js` ```js export default { add (state, { text }) { state.list.push({ text, done: false }) }, toggle (state, todo) { todo.done = !todo.done } } ``` And the `TodoList` component under `components/TodoList.vue` ```vue <template> <ul class="todolist list-group"> <li v-for="(todo, index) in todos" :key="index" class="todolist__item list-group-item" :class="{ done: todo.done }" @click="toggle(todo)"> {{ todo.text }} </li> <li class="list-group-item"> <input type="text" class="form-control" placeholder="What needs to be done?" @keydown.enter="addTodo"> </li> </ul> </template> <script> import { mapMutations, mapGetters } from 'vuex' export default { computed: mapGetters({ todos: 'todos/todos' }), methods: { addTodo (e) { const text = e.target.value if (text.trim()) { this.$store.commit('todos/add', { text }) } e.target.value = '' }, ...mapMutations({ toggle: 'todos/toggle' }) } } </script> ``` Render it inside `pages/index.vue` and your TodoList app is ready ✌🏻 ```vue <template> <div class="container-md"> <h1 class="title">My List</h1> <todo-list /> </div> </template> <script> import TodoList from '~/components/TodoList.vue' export default { components: { TodoList } } </script> ``` ## Write your tests using Page Object pattern The goal of using [Page Object pattern](https://martinfowler.com/bliki/PageObject.html) is to provide an additional layer of abstraction of any page information and use it in tests to refer to page elements. You should store all selectors and action methods that are unique for a certain page in a page object, so that you still can run your test after changes to the markup. Using WebdriverIO our initial project structure comes with `wdio.conf.js` configuration file containing all the required info on how to execute WebdriverIO, such as test specs to run and capabilities (Chrome by default), and a `test/e2e` folder containing a test example (`index.spec.js` file under `test/e2e/specs`) and a page object (`main.page.js` file under `test/e2e/pageObjects`). Inside `index.spec.js` you can find a simple test implemented using a page object. Edit this test to make it passes! ```js const TodoListPage = require('../pageObjects/main.page') describe('Todolist', () => { it('should open correct app', () => { TodoListPage.open() expect(browser).toHaveTitle('todolist') }) }) ``` 👉🏻 To speed up tests execution during development run the dev server in another terminal executing `yarn dev`, we'll see later how to programmatically build and serve your Nuxt app for Continuous Integration. To execute tests run ```bash yarn test:e2e ``` Your application will be executed inside a new Chrome instance and your first test passes 🎉 You'll get a report like this ```bash [Chrome 83.0.4103.116 darwin #0-0] Running: Chrome (v83.0.4103.116) on darwin [Chrome 83.0.4103.116 darwin #0-0] Session ID: 03399e35-a11d-4305-87bc-3cea66ce42de [Chrome 83.0.4103.116 darwin #0-0] [Chrome 83.0.4103.116 darwin #0-0] Todolist [Chrome 83.0.4103.116 darwin #0-0] ✓ should open correct app [Chrome 83.0.4103.116 darwin #0-0] [Chrome 83.0.4103.116 darwin #0-0] 1 passing (1.7s) Spec Files: 1 passed, 1 total (100% completed) in 00:00:03 ``` Now it's time to get our hands dirty and test if our application really works as expected. To keep things simple I haven't created a new TodoListPage object inheriting from Page, but remember that you can do anything you want with page objects, they're normal classes. The first step is to write all important selectors that are required in our TodoListPage object as getter functions: - `itemInput`: input text field to insert items (use `$(selector)` for single element) - `listItems`: items inserted in the list (use `$$(selector)` for multiple elements). ```js class TodoListPage { get itemInput () { return $('input[type=text]') } get listItems () { return $$('.todolist__item') } open (path = '/') { browser.url(path) } } module.exports = new TodoListPage() ``` Then you can define further getters and action methods: `listSize` to retrieve the current list size and `addListItem` / `addListItems` methods to add one or more elements to the list ```js class TodoListPage { // ... get listSize () { return this.listItems.length } addListItem (item) { this.itemInput.setValue(`${item}\n`) } addListItems (items) { items.map((item) => { this.addListItem(item) }) } // ... } ``` Write another test that adds items to the list and checks if they're inserted correctly ```js describe('Todolist', () => { // ... it('should add items to the list correctly', () => { TodoListPage.open() TodoListPage.addListItems(['Milk', 'Apples', '1 Banana']) expect(TodoListPage.listSize).toEqual(3) }) // ... } ``` As you can see tests don't contain any CSS selector, everything is clean and easier to modify even in a rapidly developing web application context where page markup and design may change often. Following this pattern you can continue writing tests adding methods to the page object if needed: for example to test if an item is marked as completed when users click on it, you can inflate your page object with a method to check if an item at a specific position is completed (`isItemCompletedAt`) and another method to mark a specific item as completed (`completeItemAt`) ```js class TodoListPage { // ... isItemCompletedAt (position) { return this.listItems[position].getAttribute('class').includes('done') } completeItemAt (position) { this.listItems[position].click() } // ... } ``` and then write the test ```js describe('Todolist', () => { // ... it('should complete items correctly', () => { TodoListPage.open() TodoListPage.addListItems(['Milk', 'Apples', '1 Banana', 'Meat']) expect(TodoListPage.isItemCompletedAt(2)).toBeFalsy() TodoListPage.completeItemAt(2) expect(TodoListPage.isItemCompletedAt(2)).toBeTruthy() }) // ... } ``` ## Build and serve your app for Continuous Integration WebdriverIO provides several hooks to interfere with the test process in order to enhance it and to build services around it. To programmatically build and serve your Nuxt application in a Continuous Integration process you need to override `onPrepare` and `onComplete` hooks inside `wdio.conf.js` configuration file. Using `Nuxt Builder` you need to `build and serve your app` inside `onPrepare` hook and `shut down the server` inside `onComplete` hook. In the following code there's also a `NUXT_ENV_CI` environment variable to skip this process outside the Continuous Integration environment, keeping tests under development fast. ```js const path = require('path') const nuxt = require('nuxt') exports.config = { // ... async onPrepare (config, capabilities) { if (process.env.NUXT_ENV_CI !== 'true') { return } console.log('⛰ Setting up...') const rootDir = path.resolve(__dirname, '.') const nuxtConfig = { head: { title: 'todolist' }, dev: false, rootDir, modules: ['bootstrap-vue/nuxt'] } this.nuxtInstance = new nuxt.Nuxt(nuxtConfig) console.log('📦 Building your Nuxt.js project...') await new nuxt.Builder(this.nuxtInstance).build() await this.nuxtInstance.server.listen(3000, 'localhost') console.log('✨ Done!') }, onComplete (exitCode, config, capabilities, results) { if (process.env.NUXT_ENV_CI !== 'true') { return } console.log('👋 Shutting down server...') this.nuxtInstance.close() } } ``` To configure TravisCI for Continuous Integration you need to create `.travis.yml` configuration file, containing `chrome` addon, `xvfb` service and some scripts to make UI tests working. ```yaml dist: bionic addons: chrome: stable services: - xvfb language: node_js node_js: '12' before_script: - fluxbox >/dev/null 2>&1 & - sleep 3 script: - NUXT_ENV_CI=$CI yarn test:e2e ``` In the `script` section `yarn test:e2e` is executed with `NUXT_ENV_CI` set to `CI` env variable value (`CI` is one of the [default environment variables available to all builds](https://docs.travis-ci.com/user/environment-variables/#default-environment-variables) and is set to `true` by default inside TravisCI). 👉🏻 If you need Continuous Deployment for your app see [how to setup TravisCI to test, build and deploy your app on Netlify in 5 minutes](https://dev.to/astagi/setup-travisci-to-test-build-and-deploy-your-app-on-netlify-in-5-minutes-khn).
astagi
396,981
Developers From India
Do you want to extend your team of developers? Just drop a line of your requirements and we will give...
0
2020-07-14T09:24:24
https://dev.to/bijinazeez/developers-from-india-2bmp
Do you want to extend your team of developers? Just drop a line of your requirements and we will give you an opportunity to hire web developers or app developers that are the best fit for your needs. Our only goal is to establish an engagement model that takes care of all your development needs, while you concentrate on your core business. Whether you want to hire a mobile app developer or a web developer for your own project or client’s project, Your Team in India is a one-stop-solution. Our offshore development services help you leverage our industry expertise and technical capabilities to boost your business growth. When you hire offshore developers from India, you get access to the largest pool of top developers in the world. Here are a few more benefits: Cost-Effective Models Hire dedicated developers in India and save 60% capital on designing and developing a professional application. Hiring dedicated web developers for projects can reflect significant savings on operating costs without cutting corners. Extensive Expertise More than 95% of the developers are aged 18-35, and every year more than 200,000 software developers are hired by the IT industry. Because of this number, any development challenges thrown across becomes easy. Quality Work The top software outsourcing companies in India consistently provide top quality software solutions. This is because of the talented software programmers in India that have an ever-increasing thirst for learning and experimenting. High-end Infrastructure India has state-of-the-art infrastructure, fiber optic networks, cellular networks, telecom, as well as satellite connectivity. Especially, Your Team in India keeps itself abreast with the latest technology and tools needed to outperform in software development. Timely Delivery Your Team in India is a top offshore development company in India that can develop a mobile app or a website for you within the required timeframe. So that you can launch your product before your competitors do. This is a major factor why companies are outsourcing IT services to India. End-to-end Services To keep you updated with each and every phase of the development, you are provided access to all your work documents, to-do lists, and project delivery dates. Helping you keep track of your application development phase so that nothing goes wrong during the development and deployment. Being one of the top offshore development companies in India, YTII offers reliable, faster, and better development services. As a certified, awarded and well recognized Indian IT outsourcing company, we deliver innovative and best in class software solutions.Your Team in India is a global offshore development company, that gives you instant access to hire software developers. Do you want to extend your team of developers? Just drop a line of your <a href=https://www.ateamindia.com/hire-senior-angular-developer-3x-the-development-resource-for-the-price-of-1/ > requirements </a> and we will give you an opportunity to hire web developers or app developers that are the best fit for your needs. Our only goal is to establish an engagement model that takes care of all your development <a href=https://www.ateamindia.com/hire-software-developers-from-india-3x-the-development-resource-for-the-price-of-1/ > needs </a> , while you concentrate on your core business.
bijinazeez
397,123
How do you identify "over-engineering"?
How do you spot over-engineering as it is happening, how do you communicate around this issue?
0
2020-07-14T12:12:39
https://dev.to/ben/how-do-you-identify-over-engineering-1oad
discuss, codequality
How do you spot over-engineering as it is happening, how do you communicate around this issue?
ben
397,124
TOP 2 New APIs in Chromium
1- Screen Wake Lock API Supported in Chrome 83+ This API helps to prevent de...
0
2020-07-14T12:14:08
https://dev.to/sharadcodes/top-2-new-apis-in-browsers-4eog
webdev
## 1- Screen Wake Lock API ### Supported in * **Chrome 83+** This API helps to prevent devices from dimming, locking or turning off the screen when your web application needs to keep running. ## 2- Web NFC ### Supported in * **Chrome 79+** * **Chrome for Android 80+** * **Edge 79+** * **Opera 66+** Can only be enabled in Chromium based browsers using the `enable-experimental-web-platform-features` flag It allows a website to communicate with NFC tags through device's NFC reader.
sharadcodes
397,258
What is Dev Community business model?
I did't find anything through that a revenue can be generated. But still servers need money to keep r...
0
2020-07-14T13:50:10
https://dev.to/milindsingh/what-is-dev-community-business-model-2dmg
I did't find anything through that a revenue can be generated. But still servers need money to keep running. How it happens here?
milindsingh
397,288
Using CSS Modules with create-react-app
Starting a new React project used to be a complicated process that involved setting up a build system...
0
2020-07-14T14:22:46
https://dev.to/0x96f/using-css-modules-with-create-react-app-22hd
react, css, beginners, javascript
Starting a new React project used to be a complicated process that involved setting up a build system, a code transpiler to convert modern JS code to code that is readable by all browsers, and a base directory structure. Create-react-app offers a modern build setup that comes pre-configured with everything we need to start building our React app. One feature is CSS Modules that is available in `create-react-app` from version 2 and later. ## What are CSS Modules ? Stylesheets in large apps can get quite messy and coming up with new class names for slightly different components can get hard really quick. A CSS module is a CSS file, but with a key difference: by default, when it is imported in a component every class name and animation inside that module is scoped locally to that component. This allows us to use any valid name for our classes, without worrying about conflicts with other class names in our application. In this post I will show you how to get started with CSS Modules and explain what happens when you use them. ## How to use CSS Modules in CRA ? To get started you will need an app generated with the `create-react-app` package (version 2 or later, but it is recommended to use the latest). To generate a project you can use: ```bash $ npm i create-react-app -g $ create-react-app my-app ``` or if you have `npx` installed: ```bash $ npx create-react-app my-app ``` The way that CRA is set up is that to use CSS Modules first we have to rename all the CSS files from `[name].css` to `[name].module.css` . In the css file any valid class name is acceptable, but it’s recommend to use `camelCase` for classes with more than one word. The reason for this is that we will access these classes later as properties of a JS object (e.g. `styles.someProperty`), but it is not enforced (you can access with `styles['some-property']`). Next we can look at how to use them in the components. First we need to change the import: ```js // From import "./App.css"; // To import styles from "./App.module.css"; ``` Note that we are importing something from the CSS file the same way we do from a JS file. This is because during our build step, the compiler would search through the `App.module.css` file that we’ve imported, then look through the JavaScript we’ve written and make the `.customClass` class accessible via `styles.customClass`. Now we can use the classes as properties from the object that we imported: ```jsx import React from "react"; import styles from "./App.module.css"; function App() { return ( <div className={styles.customClass}> Hello React! </div> ); } export default App; ``` And that is it, you are ready to use CSS Modules... ## But why do we need CSS Modules ? Well as I mentioned in large project coming up with unique class names can be hard. CSS Modules enable you to use the same class wherever you want. Since the compiler handles the CSS it changes all the class names with different unique names in order make them locally available for that component. For example: ```html <!-- Normal class --> <div class="customClass"></div> <!-- Module class --> <div class="App_customClass__28RXF"></div> ``` This means that we can have the `customClass` in multiple CSS files without worrying about conflicts between them. ## Conclusion This is not the only benefit of CSS Modules. You can find more about them [in this great article](https://glenmaddern.com/articles/css-modules). Hope this is helpful and as always - Happy coding.
0x96f
397,298
NextJS + TypeScript + TailwindCSS + Storybook project setup
TUTORIAL BASED ON STORYBOOK v5, ON v6 EVERYTHING STORYBOOK-RELATED WORKS OUT OF THE BOX! Following...
0
2020-07-14T15:15:04
https://stackrant.com/posts/nextjs-typescript-tailwindcss-storybook-project-setup
nextjs, typescript, tailwindcss, storybook
> TUTORIAL BASED ON STORYBOOK v5, ON v6 EVERYTHING STORYBOOK-RELATED WORKS OUT OF THE BOX! Following is a simple guide to get up and running with the NextJS+TypeScript+TailwindCSS+Storybook combination, a task which took me a lot more time than I originally estimated, due to the unexpected lack of specific guides on how to deal with this particular scenario plus the sparse nature of the information I had to look up to set everything up as desired. ### NEXTJS SETUP `yarn create next-app` That's it. Done. A fully-functional NextJS app will be created using the official starter kit. --- ### TAILWINDCSS SETUP 1. `yarn add -D tailwindcss postcss-preset-env` to install the TailwindCSS library and some useful PostCSS polyfills 2. `npx tailwind init` to generate a `tailwind.config.js` file. 3. Edit the TailwindCSS configuration file we just created to enable and configure the built-in CSS purging process. (Notice how I'm using the ".tsx'" extension here, since I already know I'm going to use TypeScript for this project) ```js module.exports = { purge: ['./components/**/*.tsx', './pages/**/*.tsx'], theme: { extend: {}, }, variants: {}, plugins: [], } ``` 4. Create `postcss.config.js` to configure PostCSS in a minimal way, like the following ```js module.exports = { plugins: [ "tailwindcss", "postcss-preset-env" ] }; ``` 5. Create `/styles/index.css` and populate it using the `postcss-import`-friendly `@import` directives (instead of using `@tailwind`) ```css @import "tailwindcss/base"; @import "tailwindcss/components"; @import "tailwindcss/utilities"; ``` --- ### TYPESCRIPT SETUP 1. `yarn add --dev typescript @types/react @types/node` 2. `touch tsconfig.json` 3. `yarn next` to start NextJS, which will automagically recognize our newly created `tsconfig.json` and inject a valid configuration json into it 4. Create a `/pages/_app.tsx` file ```jsx import React from "react"; import "../styles/index.css"; // <- applied everywhere in the NextJS application scope const MyApp = ({ Component, pageProps }) => { return <Component {...pageProps} />; }; export default MyApp; ``` --- ### STORYBOOK SETUP 1. `yarn add @storybook/react babel-loader @babel/core awesome-typescript-loader react-docgen-typescript-loader -D` 2. `mkdir .storybook` 3. `cp ./tsconfig.json ./.storybook/` 4. Edit `/.storybook/tsconfig.json` to suit your Storybook-TypeScript integration ```json { "compilerOptions": { "target": "es5", "lib": ["dom", "dom.iterable", "esnext"], "allowJs": true, "skipLibCheck": true, "strict": false, "forceConsistentCasingInFileNames": true, "noEmit": true, "esModuleInterop": true, "module": "esnext", "moduleResolution": "node", "resolveJsonModule": true, "isolatedModules": true, "jsx": "react" // <- important! }, "exclude": ["node_modules"], "include": [ // <- important! "../types.d.ts", "../next-env.d.ts", "../**/*.stories.ts", "../**/*.stories.tsx" ] } ``` 6. Create `/.storybook/main.js` and feel free to copy the following configuration ```js const path = require("path"); module.exports = { stories: ["../components/**/**/*.stories.tsx"], webpackFinal: async (config) => { config.module.rules.push({ test: /\.(ts|tsx)$/, use: [ { loader: require.resolve("awesome-typescript-loader"), options: { configFileName: path.resolve(__dirname, "./tsconfig.json"), }, }, /* ** OPTIONAL ** Basically a webpack loader used to generate docgen information from TypeScript React components. The primary use case is to get the prop types table populated in the Storybook Info Addon. */ { loader: require.resolve("react-docgen-typescript-loader"), options: { tsconfigPath: path.resolve(__dirname, "./tsconfig.json"), }, }, ], }); config.resolve.extensions.push(".ts", ".tsx"); return config; }, }; ``` 7. create `/.storybook/preview.js` and use it to import our stylesheet as follows ```js // The preview application is essentially just your stories with // a framework-agnostic 'router'. // It renders whichever story the manager application tells it to render. // In this case we just use it to import the stylesheet and inject it // in the context of our stories import "../styles/index.css"; ``` 8. Update `postcss.config.js` to use an object-based format. This is super important in order to solve any issues Storybook's webpack process may encounter while resolving the dependencies! ```js module.exports = { plugins: { tailwindcss: {}, "postcss-preset-env": {} } }; ``` --- # DONE Now you will be able to create your component stories in your own component's folders (ex.: `/components/button/1-button.stories.tsx`) using this powerful toolset. > P.S.: If you wish to organize your Storybook stories using a different folder structure, you'll need to do no more than editing the `stories` property inside the exported configuration in `/.storybook/main.js` using your desired glob patterns
hood
397,652
Beautiful World of Monads
Practical Introduction to Monads for Java Developers
0
2020-07-14T17:43:09
https://dev.to/siy/beautiful-world-of-mondas-2cd6
java, beginners, tutorial
--- title: Beautiful World of Monads published: true description: Practical Introduction to Monads for Java Developers tags: #java #beginners #tutorial //cover_image: https://direct_url_to_image.jpg --- Let me start with disclaimer. Explanation below in no way pretends to be precise or absolutely accurate from the point of view of Functional Programming. Instead I’m focusing on clarity and simplicity of the explanation to let as many Java developers get into this beautiful world. When I started digging into Functional Programming few years ago, I’ve quickly discovered that there are an overwhelming amount of information, but very little of it is understandable to average Java developer with almost exclusively imperative background. These days situation is slowly changing. There are a lot of articles which explain, for example, basic FP concepts and how they are applicable to Java. Or articles explaining how to use Java streams properly. But Monads still remain out of the focus of these articles. I don’t know why this happens, but I’ll try to fill this gap. ## What Is Monad, Anyway? The Monad is … a design pattern. As simple as that. This design pattern consists of two parts: - Monad is a container for some value. For every Monad there are methods which allow wrap value into Monad. - Monad implements “Inversion of Control” for value contained inside. To achieve this Monad provides methods which accept functions. These functions take value of the same type as stored in Monad and return transformed value. The transformed value is wrapped into the same kind of Monad as source one. To understand second part of the pattern it will be convenient to look at the imaginable Monad interface: ```java interface Monad<T> { <R> Monad<R> map(Function<T, R> mapper); <R> Monad<R> flatMap(Function<T, Monad<R>> mapper); } ``` Of course particular Monad usually has far more rich interface, but these two methods definitely should be present. At first look accepting functions instead of giving access to value is not a big difference. In fact this enables Monad to retain full control on how and when to apply the transformation function. When you call getter you expect to get value immediately. In case of Monad transformation can be applied immediately or not applied at all or it’s application can be delayed. Lack of direct access to value inside enables monad to represent value which is even not yet available! Below I’ll show some examples of Monads and which problems they can address. ## The Story of The Missing Value or Option/Maybe Monad This Monad has many names — Maybe, Option, Optional. Last one sounds familiar, isn’t it? Well, since Java 8 Optional is a part of the Java Platform. >Unfortunately Java Optional implementation makes too much reverences to traditional imperative approaches and this makes it less useful than it can be. In particular Optional allows application to get value using .get() method. And even throw NPE if value is missing. As a consequence Optional usage is often limited to represent return potentially missing value, although this is only small part of the potential usages. The purpose of the Maybe Monad is to represent value which potentially can be missing. Traditionally this role in Java is reserved for null. Unfortunately this causes a lot of various issues, including famous _NullPointerException_. If you expect that, for example, some parameter or some return value can be null, you ought to check it before use: ```java public UserProfileResponse getUserProfileHandler(final User.Id userId) { final User user = userService.findById(userId); if (user == null) { return UserProfileResponse.error(USER_NOT_FOUND); } final UserProfileDetails details = userProfileService.findById(userId); if (details == null) { return UserProfileResponse.of(user, UserProfileDetails.defaultDetails()); } return UserProfileResponse.of(user, details); } ``` Looks familiar? Sure it does. Lets take a look how Option Monad changes this (with one static import for brevity): ```java public UserProfileResponse getUserProfileHandler(final User.Id userId) { return ofNullable(userService.findById(userId)) .map(user -> UserProfileResponse.of(user, ofNullable(userProfileService.findById(userId)) .orElseGet(UserProfileDetails::defaultDetails))) .orElseGet(() -> UserProfileResponse.error(USER_NOT_FOUND)); } ``` Note that code is much more concise and contains much less “distraction” from business logic. This example shows how convenient monadic “inversion of control”: transformations don’t need to check for null, they will be called only when value is actually available. >The “do something if/when value is available” is a key mindset to start conveniently using Monads. Note that example above retains original API’s intact. But it makes sense to use the approach wider and change API’s so they will return _Optional_ instead of _null_: ```java public Optional<UserProfileResponse> getUserProfileHandler4(final User.Id userId) { return optionalUserService.findById(userId) .flatMap(user -> userProfileService.findById(userId) .map(profile -> UserProfileResponse.of(user, profile))); } ``` Few observations: - The code even more concise and contains nearly zero boilerplate - All types are automatically derived. This is not always so, but in vast majority of cases types are derived by compiler despite weaker type inference in Java comparing to, for example, Scala - There are no explicit error processing, instead we can focus on “happy day scenario”. - All transformations are composing and chaining conveniently, no breaks or distractions from main business logic. In fact properties above are common for all Monads. ## To Throw Or Not To Throw That Is The Question Things not always going as we would like and our applications living in real world, full of suffering, errors and mistakes. Sometimes we can something with them, sometimes not. If we can’t do anything we would like at least notify caller that things went not as we anticipated. In Java we traditionally have two mechanisms to notify caller about a problem: - Return special value (usually null) - Throw an exception Instead of returning null we can also return Option Monad (see above), but often this is not enough as more detailed information about error is necessary. Usually we throw an exception in this case. There is a problem with this approach though. Actually even few problems. - Exceptions break execution flow - Exceptions add a lot of mental overhead Mental overhead caused by exceptions depends on types of exceptions: - Checked exceptions forcing you either to take care of them right here or declare them in signature and shift headache to the caller - Unchecked exceptions cause the same level of issues but you don’t have support from compiler Don’t know which one is worse. ##Here Comes Either Monad Let’s analyse issue for the moment. What we want to return is a some special value which can be exactly one of two possible things: result value (in case of success) or error (in case of failure). Note that these things are mutually exclusive — if we return value there is no need to carry error and vice versa. Above is almost exact description of Either Monad: any given instance contains exactly one value and this value has one of two possible types. The interface of Either Monad can be described like this: ```java interface Either<L, R> { <T> Either<T, R> mapLeft(Function<L, T> mapper); <T> Either<T, R> flatMapLeft(Function<L, Either<T, R>> mapper); <T> Either<L, T> mapLeft(Function<T, R> mapper); <T> Either<L, T> flatMapLeft(Function<R, Either<L, T>> mapper); } ``` The interface is rather verbose as it’s symmetric in regard to left and right values. For the narrower use case when we need to deliver success or error it means that we need to agree on some convention — which type (first or second) will hold error and which will hold value. Symmetric nature of Either makes it more error prone in this case as it’s easy to unintentionally swap error and success values in code. While most likely this problem will be caught by compiler, it’s better to tailor Either for this particular use case. This can be done if we fix one of the types. Obviously it’s more convenient to fix error type as Java programmers are already used to having all errors and exceptions derived from single Throwable type. ##Result Monad — Either Monad Specialized for Error Handling & Propagation So, let’s assume that all errors implement same interface and let’s call it Failure. Now we can simplify and reduce interface: ```java interface Result<T> { <R> Result<R> map(Function<T, R> mapper); <R> Result<R> flatMap(Function<T, Result<R>> mapper); } ``` The Result Monad API looks very similar to API of Maybe Monad. Using this Monad we can rewrite previous example: ```java public Result<UserProfileResponse> getUserProfileHandler(final User.Id userId) { return resultUserService.findById(userId) .flatMap(user -> resultUserProfileService.findById(userId) .map(profile -> UserProfileResponse.of(user, profile))); } ``` Well, it’s basically identical to example above, the only change is kind of Monad — Result instead of Optional. Unlike previous example here we have full information about error, so we can do something with that at upper level. But still, despite full error handling code remains simple and focused on the business logic. ##“Promise is a big word. It either makes something or breaks something.” Next Monad I’d like to show will be the Promise Monad. >Must admit that I’ve not found authoritative answer if Promise is a monad or not. Different authors have different opinion in regard to it. I’m looking at it from purely pragmatic point of view: it looks and behaves a lot like other monads, so I consider them a monad. The Promise Monad represents a (potentially not yet available) value. In some sense it’s very similar to Maybe Monad. The Promise Monad can be used to represent, for example, result of request to external service or database, file read or write, etc. Basically it can represent anything which requires I/O and time to perform it. The Promise supports the same mindset as we’ve observed with other Monads — “do something if/when value is available”. Note that since it’s impossible to predict if operation will be successful or not, it’s convenient to make Promise represent not value itself but Result with value inside. To see how it works, lets take a look example below: ```java ... public interface ArticleService { // Returns list of articles for specified topics posted by specified users Promise<Collection<Article>> userFeed(final Collection<Topic.Id> topics, final Collection<User.Id> users); } ... public interface TopicService { // Returns list of topics created by user Promise<Collection<Topic>> topicsByUser(final User.Id userId, final Order order); } ... public class UserTopicHandler { private final ArticleService articleService; private final TopicService topicService; public UserTopicHandler(final ArticleService articleService, final TopicService topicService) { this.articleService = articleService; this.topicService = topicService; } public Promise<Collection<Article>> userTopicHandler(final User.Id userId) { return topicService.topicsByUser(userId, Order.ANY) .flatMap(topicsList -> articleService.articlesByUserTopics(userId, topicsList.map(Topic::id))); } } ``` To bring whole context I’ve included both necessary interfaces, but actually interesting part is the userTopicHandler() method. Despite suspicious simplicity this method does following: - Calls TopicService and retrieve list of topics created by provided user - When list of topics is successfully obtained, the method extracts topic ID’s and then calls ArticleService and retrieves list of articles created by user for specified topics - Performs end-to-end error handling ##Afterword The Monads are extremely powerful and convenient tool. Writing code using “do when value is available” mindset requires some time to get used to, but once you start getting it, it will allow you to simplify your life a lot. It allows to offload a lot of mental overhead to compiler and make many errors impossible or detectable at compile time rather than at run time.
siy
398,213
What does the terms front-end and back-end cover? (opinions)
For example, whenever I hear the term front-end I think about sketching, design, color theory, UI/UX,...
0
2020-07-15T01:32:45
https://dev.to/jouo/what-does-the-terms-front-end-and-back-end-cover-opinions-3ja7
discuss
For example, whenever I hear the term **front-end** I think about sketching, design, color theory, UI/UX, coding... For **back-end**: databases, coding, algorithms, devops, systems... My definitions could be completely wrong, but that's just how I personally perceive them. How do **you** perceive those two terms? :)
jouo
426,642
The story of how I got into web dev...
Hey everyone, my name is Nazanin but my online friends call me Zani lol I saw people sharing their st...
0
2020-08-13T17:00:52
https://dev.to/nazanin_ashrafi/the-story-of-how-i-got-into-web-dev-3ff1
webdev, watercooler, codenewbie
Hey everyone, my name is Nazanin but my online friends call me Zani lol I saw people sharing their stories and how they got into coding so i thought I'd do the same Here we go : Coding was never my passion, hell i didn't even know what it is. I never knew what I liked or what I wanna do, The only thing I knew was that I wanna be a barista but couldn't make that happen (still can't btw), Other than that I didn't know anything. I've always had a habit of dropping things off and never finished what I'd started. I tried fashion design but dropped it. I tried drawing but dropped it. I even dropped coding the first time I tried it lol So after quite sometimes I started coding again for the second time and only because I was so bored and was like let's try coding one more time. The first week of learning was just for fun BUT somehow things changed after that. Suddenly I was so into this and kept googling.the more time passed the more I took it seriously. It took me a while to decide which direction to go. I couldn't choose between web dev and app but somehow I ended up choosing web dev. As I said I started it just for fun but now I'm really talking it seriously and wanna build a career in this field. Getting into web dev really has changed me in every way. I literally went from " being a lazy person who has no goals" to having so many goals and trying so hard to achieve them ^^ A big shout out to mimo app for teaching me the basic in the best way possible, and to my amazing supportive friend, Discors and to Dain Miller's awesome podcast for being a huge help. Okay that's it. Thank you all for reading my journey ^^
nazanin_ashrafi
398,282
ES6 Modules: How to use import and export in JavaScript
ES6 provides the ability to split JavaScript into multiple files (modules). Modules can then be expo...
0
2020-07-15T03:32:42
https://dev.to/michaelburrows/es6-modules-how-to-use-import-and-export-in-javascript-1op5
javascript, tutorial
ES6 provides the ability to split JavaScript into multiple files (modules). Modules can then be exported and imported as required into other files. The biggest benefit of modules is they help keep large amounts of JavaScript organised. To better understand how modules work let’s create a simple project with following files and folder structure. ``` |- index.html |- app.js |- /src |- location.js |- weather.js ``` First add the following markup to the index.html file: ```html <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8" /> <title>Our Application</title> </head> <body> <div id="app"></div> <script type="module" src="app.js"></script> </body> </html> ``` Notice the `type="module"` so that the browser treats the script as a module, it wont work without it. ##Exporting Before we can import we must first export the code from the weather.js and location.js files. In weather.js let’s create a `weather()` function with an `export` directive. ```javascript export function weather() { const temperature = "15c"; const conditions = "Sunny" return temperature + " " + conditions; } ``` And in location.js we’ll export multiple variables by adding the desired members to the `export` directive. ```javascript const country = "Australia"; const state = "Victoria"; const city = "Melbourne"; export { country, state, city }; ``` ##Importing Now in the app.js file we can import the external JavaScript. ```javascript import { country, state, city } from "./src/location.js"; import { weather } from "./src/weather.js"; ``` Once imported it can be used just as it would if it existed in the same JavaScript file. To complete the project we’ll output the imported modules into the index.html. ```javascript const getWeather = weather(); const currentWeather = "<h2>Weather " + getWeather + "</h2>"; const currentLocation = "<h1>" + country + " | " + state + " | " + city + "</h1>"; document.getElementById("app").innerHTML = currentLocation + currentWeather; ``` If everything is correct you should see the following when index.html is viewed in a browser. ![Alt Text](https://dev-to-uploads.s3.amazonaws.com/i/urldng179k9t522d71ut.png) Note: Modules will only work in files served via http(s) not in the local file system (file:///).
michaelburrows
398,408
Instagram Data Scraper
Wrote and program that allows you to see the total likes and comments of a public user, plus the numb...
0
2020-07-15T06:28:53
https://dev.to/nenwam/instagram-data-scraper-4b2b
webdev, database, entertainment
Wrote and program that allows you to see the total likes and comments of a public user, plus the number of likes on each post https://cranky-yonath-059111.netlify.app/
nenwam
398,542
Effective Object Usage Examples in JavaScript
In this article, I try to suggest effective solutions with objects in JavaScript for common use cases...
0
2020-07-15T10:18:00
https://dev.to/halilcanozcelik/javascript-objects-in-use-1e12
javascript, computerscience, webdev, tutorial
In this article, I try to suggest effective solutions with objects in JavaScript for common use cases in the real world. ### Objects instead of array search Using objects in an array search decreases the time complexity of your solution in quite a lot of cases. Let’s continue explaining with examples: ```js function findMaxOccured() { const list = [12, 3, 55, 2, 7, 9, 2, 4, 2, 3]; let maxOcc = { value: '', times: 0 }; for (let i of list) { // this filter is a nested loop actually! const occ = list.filter(el => el === i).length; if (occ > maxOcc.times) { maxOcc = { value: i, times: occ }; } } return maxOcc; } ``` In the example above, we find the max occurred element in the list. There is a nested loop in here (filter method) because we are searching the whole list to find the occurrence times for each element of the list. So, the time complexity is O(n²) for this solution which is not good enough! The possible object-related approach can be below: ```js function findMaxOccured() { const list = [12, 3, 55, 2, 7, 9, 2, 4, 2, 3]; const occMap = {}; let maxOcc = { value: '', times: 0 }; for (let i of list) { occMap[i] = (occMap[i] || 0) + 1; } for (let i of Object.keys(occMap)) { if (occMap[i] > maxOcc.times) { maxOcc = { value: i, times: occMap[i] }; } } return maxOcc; } ``` First, we generate an occurrence map for the list. Then find the max occurred element in the map by iterating through it. Here there is no nested loop so time complexity is O(n) which is better! ### Objects instead of conditions In some cases, we need to call different functions or assign different values according to the value of a variable. For these cases, using a matching object instead of several condition blocks can be more effective solutions. Let’s give an example: The following code block is the first thing that comes to mind mostly. ```js function conditional(param) { if (param === 'a') { return 1; } else if (param === 'b' || param === 'c') { return 2; } else { return 3; } } ``` This can be refactored like below: ```js function objectMatch(param) { const match = { a: 1, b: 2, c: 2, default: 3 }; return match[param] || match.default; } ``` This alternative also is conceivable for switch cases: ```js function conditional(param) { switch (param) { case 'a': func1(); break; case 'b': case 'c': func2(); break; default: func3(); break; } } ``` In addition to the first one, we need to call the function `()` after getting from the mapping object. Again my suggestion: ```js function objectMatch(param) { const match = { a: func1, b: func2, c: func2, default: func3 }; const correspondingFunc = match[param] || match.default; correspondingFunc(); } ``` Additionally, this mapping objects can be moved to a higher scope if it doesn’t need to change in function just like our examples. Of course, for more complex conditions this approach couldn’t be the best fit but for simple cases like my examples, you can consider using objects. The examples can be increased but I hope these explain the main idea.
halilcanozcelik
398,845
Next.js - the future of React?
A short overview of probably most versatile framework for React
0
2020-07-24T11:50:48
https://dev.to/dotintegral/next-js-the-future-of-react-21nb
nextjs, react, javascript, typescript
--- title: Next.js - the future of React? published: true description: A short overview of probably most versatile framework for React tags: nextjs, react, javascript, typescript cover_image: https://dev-to-uploads.s3.amazonaws.com/i/kh3ntlg6dnemjeaz531z.png --- React and Angular are probably the most popular, competing frameworks right now. They are being used in thousands of commercial and non-commercial projects around the globe. If you ever googled for differences between both of them, you would learn that despite React being a wonderful framework, it's not entirely ready out-of-the-box experience. Angular still has a couple of aces in sleeves. But with [Next.js](https://nextjs.org/) React can overcame its shortcomings and perhaps end the old dispute "React vs Angular" in it's favour. # Why React is not complete The quick answer: It was never designed to be a complete, big framework for all our developer needs. It started as just a view library - so just the V of the MVC approach. It quickly revolutionised web, gaining more popularity with new and fresh concepts like Flux, and then the Redux itself. More and more developers got excited about it and started releasing hundreds upon hundreds of middlewares and utilities to turn this primarily View framework into something more complete. Now, with its rich ecosystem of libraries, we can use it to create basically any app we can think of. The problem is, that with all of the support from its community, it is tedious to start a new React project. Even with the usage of [Create React App](https://github.com/facebook/create-react-app), you still need to think about and integrate: * state management, * middlewares to handle sideeffect if you happen to pick Redux, * routing solution * and many, many more... It takes time and experience to set-up everything in an optimal way. No wonder that some developers prefer Angular. Once you install it, you're ready to start developing. Angular comes with a bunch of useful utils. Notably: Built-in router, state management, and basically convention-over-configuration approach. It just works. We can't blame React for not having everything out-of-the-box, as it was never its intent. Luckly, there is Next.js to fill in the gaps and help us getting up and running in no time! # Discovering Next.js So what is Next.js? It is basically a framework for React. If you consider React to be a framework (I do!), then it's a framework for a framework. It tries to address the issues that I mentioned before and deliver a ready-to-go platform. We can just install it and we have (almost) everything we need to start our project. It doesn't matter if it's a passion project done after hours, or a commercial project for a big client. Next.js got us covered. Let's take a look at its features. ## Simple Setup All we have to do in order to get a new app is simply typing the following in our terminal: ``` yarn create next-app ``` The creator will ask us two questions: Whats the name of your app and do you want to use a template. I suggest going with the default option for the latter one, although you can check existing templates if you're feeling adventurous. After everything is done, we end up with the following structure ``` node_modules/ pages/ api/ hello.js index.js public/ favicon.ico vercel.svg .gitignore package.json README.md yarn.lock ``` If we type the following, our app will start in development mode with hot reloading enabled! So cool! Type in the following to see your page live over `http://localhost:3000`: ``` yarn dev ``` Tip: I suggest moving the `pages/` folder into `src/pages/` so we can keep all of our source files into the `src` folder. Next.js will use `src/pages` as well. ## Routing As mentioned before, Next.js has a pretty powerful routing included. What can be a bit inconvenient for newcomers is that it relies heavily on conventions rather than configuration. All JavaScript files placed in our `pages/` or `src/pages` will be mapped to an URL that user can access from the browser. `pages/index.js` will be accessible at the page root, `pages/users.js` can be seen at `mypage.com/users` etc... For deeper nesting you need to utilize directories, meaning that `pages/a/b/c.js` will turn into `mypage.com/a/b/c`. Simple as that. Obviously, without support for dynamic arguments in URLs, we could not go very far. Fortunately, Next.js utilizes the file naming convention to help us with that. Simply, to handle `users/edit/{user-id}` URL, just create the file `pages/users/edit/[userId].js`. We can access the `userId` value by using the provided `useRouter` hook: ```javascript import { useRouter } from 'next/router' const Users = () => { const router = useRouter() const userId = router.query.userId // rest of your logic } export default Users ``` ## Linking As a small bonus to the routing, Next.js comes with built in linking solution. Available in the `next/link` package, the component will help us link to our pages in more optimised way. ```jsx <Link href="/users/[userId]" as="/users/1"> <a>See the first user</a> </Link> ``` By using the provided `Link` in addition to the good old `a`, we can make use of enabled by default prefetching, making our pages load faster. Moreover, even when working in Server Side Rendered mode, the `Link` will allow us to actually render the page on the client side, making it kind of a smart SSR/SPA hybrid. There is a number of options for the `Link`, so we can very easily change its behaviour to use `history.replace` instead of calling `history.push` or just perform a shallow rendering (updating the URL without updating the page contents). ## API support This is where we dive into more advanced features. Next.js is more than purely Frontend framework. With it, we can develop also Backend endpoints very easily. Following the convention of routing, every file placed inside the `pages/api` directory will turn into an endpoint that we can call from the browser. The default file `api/hello.js` shows us how simple it is to create working endpoints returning JSON data: ```javascript export default (req, res) => { res.statusCode = 200 res.json({ name: 'John Doe' }) } ``` From here, nothing stops us from doing our backend logic, like querying a database. We need just to install our favourite ORM and we're ready to go. ## Server Side Rendering This was one of the features that blown my mind. Next.js comes with an excellent support for SSR! I was actually in a project, where client decided, that they want to have SSR enabled. But we developed everything as client side rendered page. Luckly, Next.js was here to help us making the switch quite quickly. As an example, let us consider this very simple, completely client rendered page: ```jsx // pages/todo/[id].js import React, { useState, useEffect } from 'react'; import { useRouter } from 'next/router' const Todo = () => { const [data, setData] = useState(null); const router = useRouter() const id = router.query.id useEffect(() => { fetch('https://jsonplaceholder.typicode.com/todos/' + id) .then(response => response.json()) .then(json => setData(json)) }, [id]) return <div>Todo - {data ? data.title : 'loading...'}</div> } export default Todo ``` In oder to convert it into a fully server side rendered page, we need only to export additional async function named `getStaticProps` and move our data fetching logic there. ```jsx // pages/todo/[id].js import React from 'react'; const Todo = ({ data }) => { return <div>Todo - {data.title}</div> } export const getStaticProps = async (ctx) => { const id = ctx.params.id; const data = await fetch('https://jsonplaceholder.typicode.com/todos/' + id) .then(response => response.json()); return { props: { data } } } export default Todo; ``` We have just turned our CSR page into a fully SSR page. That's incredible simple! ## Static Pages Generator Sometimes we need just a simple, static pages generated with no need for node.js server. In a very similar manner to the SSR, Next.js allows us to quickly create statically generated pages. Let's consider the SSR example - we need only to export additional method called `getStaticPaths` that will tell Next.js what IDs are available. Obviously, if we're generating site based on DB or some CMS, we need to retrieve all of the valid IDs here. At the end, simply return the object with all IDs. The whole code for a statically generated page is as follows: ```jsx // pages/todo/[id].js import React from 'react'; const Todo = ({ data }) => { return <div>Todo - {data.title}</div> } export const getStaticProps = async (ctx) => { const id = ctx.params.id; const data = await fetch('https://jsonplaceholder.typicode.com/todos/' + id) .then(response => response.json()); return { props: { data } } } export const getStaticPaths = async () => { return { paths: [ { params: { id: '1' } }, { params: { id: '2' } }, { params: { id: '3' } } ], fallback: false }; } export default Todo; ``` Once we have all of the pages prepared this way, we can simply call the `next build` and `next export` commands. Lo and behold, our static pages are generated! What I find even more impressive, is that almost all of our routing features (like prefetching) will work in static pages as well. ## TypeScript support If you, just like me, prefer to have types in your project, then Next.js is perfect. Though it does not get generated as a TypeScript project, it can be easily converted to one. All we have to do is create an empty `tsconfig.json` file in the root directory and run our app. Next.js will fill the config with its initial configuration and will be ready to work with our TypeScript code. As simple as that! Alas, There are small caveats. Firstly, it is better to not change the existing properties in `tsconfig.json`. For example, in one project I tried to disable the flag `skipLibCheck`, but that caused the compiler to rise an error in one of the Next.js dependencies. So I strongly advice not to change the existing config. Adding new properties is cool, though! Secondly, the documentation is mostly written for good ol' JS. That means it might be sometimes problematic to find the type of a param for function. For instance, let's take a look again on the example from API support: ```javascript export default (req, res) => { res.statusCode = 200 res.json({ name: 'John Doe' }) } ``` We need to dig around in the docs, to figure out that the `req` object is actually of `NextApiRequest` type while `res` uses `NextApiResponse`. Not a deal breaker, but it's a bit annoying to look for the types. ## Downsides Next.js, as everything in life, is definitely not perfect and has its own shortcomings. Have you noticed already that I haven't mentioned anything about state management? It's because Next.js, as packed with features as it is, does not provide us a built-in state manager. It is a kind of a bummer, that in all it's glory, with ready-to-go attitude, there is no state management. But I guess it makes sense. Lately state management in React apps became a bit of a controversial topic. There are a lot of people saying Redux is great (including me, but I also acknowledge its flaws). On the other side, there are people saying MobX is the way to go. Finally, there are devs who would argue, that Context API is all we need, or something exotic like `unstated-next` can be used (I don't recommend that one). With all those divisive opinions, it's no surprise that Next's devs haven't just picked one solution. Additionally, to be honest, with such a versatile tool, it would be probably hard to find an optimal solution. But if we really need a state manager in our app, there are a lot tutorials on the web showing how we can quickly add Redux or MobX. Another (albeit small) downside of Next.js is lack of out-of-the-box support for any of CSS-in-JS technologies. We can use CSS and SCSS right from the get-go. But when it comes to more modern styling approaches, we need to add some code. It's not a lot, though, and there examples linked in the official docs ([here](https://nextjs.org/docs/basic-features/built-in-css-support#css-in-js)). # Summary As we can see, Next.js is a great and really versatile framework for React. It provides a well configured, working out-of-the-box environment for creating basically ANY web app. Basically, Next is perfect for Single Page Apps, Server Side Rendered pages, Statically Generated pages or anything in between. With API support we can use it to create a complete pages with Backend logic. The only really big downside, is that there is no built-in state manager. Apart from that, it's got everything we need to create new web apps in no time. In conclusion, I believe it's the most complete React experience out there. Next.js provides all features that just pure React is lacking of, making it feature-ready setup to face Angular in the "React vs Angular" debate. If React is ever to win said dispute, it will need a solid framework to do so. In my opinion, Next.js is exactly that, an incredible environment for modern web app development.
dotintegral
398,974
.NET CIL interpreter in F#
I've prepared compact .NET CIL interpreter called Fint in pure F# for NskDotNet Meetup #6. It can ru...
0
2020-07-15T15:30:42
https://dev.to/sergeyt/net-cil-interpreter-in-f-31fl
dotnet, functional
I've prepared compact [.NET CIL](https://en.wikipedia.org/wiki/Common_Intermediate_Language) interpreter called [Fint](https://github.com/sergeyt/fint) in pure F# for [NskDotNet Meetup #6](https://www.meetup.com/NskDotNet/events/265652338/). It can run C# programs with the following features at this point: - all control flow statements (if, for, switch, etc) - arithmetic operations including bitwise one - boolean algebra operators - string concatenation - static function calls - Console.WriteLine calls It can be easily extended with other features. Some code in this project is just ported from [PageFX project](https://github.com/GrapeCity/pagefx) I wrote about [recently](/flash-viewer-story). It would be nice to try porting Fint to JavaScript using [Fable](https://fable.io/) and run .NET binary code right in a browser. Later we can try to port [Roslyn C# compiler](https://github.com/dotnet/roslyn) to [WASM](https://webassembly.org/) with [Blazor compiler](https://dotnet.microsoft.com/apps/aspnet/web-apps/blazor) and build online tutorial that: - compiles small C# program to .NET PE file in browser - runs .NET PE file in browser - shows CIL code for given method - provides debugging experience of CIL instruction set This could be a great web resource to help learning .NET code at low-level. If you like Fint repo please stargaze it on github. Here is [a recording](https://www.youtube.com/watch?time_continue=4&v=d-NbhhxRRW4&feature=emb_logo) of my presentation. Sorry for speaking so boring :smile: Enjoy! EOF :smile:
sergeyt
427,123
16 Underused Web Platform Features
What follows is a list of APIs and features that are uncommon to see in the wild, but have use cases...
0
2020-08-14T00:56:22
https://dev.to/robbiegm/16-underused-web-platform-features-3k90
webdev, javascript
What follows is a list of APIs and features that are uncommon to see in the wild, but have use cases nonetheless and the potential to greatly improve the experience your users have while visiting your website. Each feature below has a link to a demo so you can try it out in your browser. Without further ado... [**App shortcuts**](https://web.dev/app-shortcuts/) This feature allows your PWA, when installed on the home screen, to show shortcut options when the app icon is long-pressed by the user. It is often used by messaging apps to provide shortcuts to frequently messaged users, though dynamically updating the shortcuts in your app manifest for a use case like that is [not easy](https://stackoverflow.com/questions/47762022/apply-changes-to-web-app-manifest-on-an-installed-pwa). [**Web Share API**](https://web-share.glitch.me/) Alright, this one is more well known but I feel like it is important enough that it should be included anyway. This API allows web apps on mobile devices to use the native share dialog. [**Web Push API**](https://gauntface.github.io/simple-push-demo/) This is different from the notifications API. It's used to send notifications, but the important addition here is that the website does not need to be open in the browser in order for notifications to come through. [**Credentials Management API**](https://whatwebcando.today/credentials.html) This API allows web applications to store and retrieve credentials such as username/password pairs or federated login data. This could be used to provide a quick way to use saved logins without visiting a login page and clicking the log in button with autofilled credentials. [**Web OTP API** (aka SMS Receiver API)](https://web.dev/web-otp/) The Web OTP API provides a simple way to use SMS for two-factor authentication. It lets the web application intercept certain text messages (ones which contain its origin) and use them to authorize the user if given permission. Definitely simpler for the user than having to type in a code! [**`content-visibility` CSS Property**](https://web.dev/content-visibility/) The `content-visibility` property allows browser engines to render content much quicker by only rendering what is above the fold and waiting to render other content. This property has three possible values: - `visible` - no effect - `hidden` - similar to `display: none` but the browser does not discard the previous rendering state, so changing from `content-visibility: hidden` to `visible` is more performant than changing from `display: none` to `block`. - `auto` - turns on "containment" - a way for the browser to estimate the size of an element in various ways without rendering descendants (for performance). More information is available in the link above or in [the spec](https://drafts.csswg.org/css-contain-2/#content-visibility). [**Keyboard Lock API**](https://x9011.csb.app/) Allows web apps in fullscreen mode, such as games or remote desktop applications, to listen to the activation of certain key combinations which would otherwise be trapped by the browser or OS (such as `Alt` + `Tab` or `Ctrl` + `W`). [**Native Filesystem API**](https://googlechromelabs.github.io/text-editor/) Provides a way for web apps to open files and save them directly to the user's file system. This kind of thing is very useful for file editors. If you want to try the demo above, make sure to use Chrome and enable the experimental web platform feature [chrome://flags/#native-file-system-api](chrome://flags/#native-file-system-api). [**Wake Lock API**](https://wake-lock-demo.glitch.me/) Wish the screen wouldn't go to sleep while your web app is being used, even if not actively in a way which would normally keep the screen on? The Wake Lock API can be used to keep the user's device from going to sleep while they are, say, reading a recipe. This API helped [Betty Crocker achieve a 300% increase in purchase intent indicators](https://web.dev/betty-crocker/) on their website. **Periodic Background Sync API** Sorry I couldn't find a demo for this one. The background sync API is similar to the Push API in that it requires a service worker and receives information in the background. The app will periodically receive a `periodicsync` event on the service worker which allows it an opportunity to fetch data. This API is most useful when you want to save content for offline use, but could be used to keep content cached and fresh so it is loaded instantly when the site is opened. More information can be found on the [web.dev blog post about this feature](https://web.dev/periodic-background-sync/). [**Web Share Target API**](https://web-share.glitch.me) The flip side of the Web Share coin is that not only can you share content to other apps, your app can be a target to receive shared content. First, however, the PWA must be installed. The demo above, as well as the API itself, only work in Chrome for Android at the time of this writing. [**Contact Picker API**](https://contact-picker.glitch.me/) This API lets users select contacts to upload to a website through a contact picker widget. Names, emails, telephone numbers, addresses, and icons can all be requested. [**Image lazy loading**](https://mathiasbynens.be/demo/image-loading-lazy) The `loading` attribute on an HTML `img` element, when set to `"lazy"`, instructs the browser not to load the image until it is in view or about to be scrolled into view. This results in bandwidth savings for users. [**Payment Request API**](https://paymentrequest.show/demo/) The payment request API is undoubtedly the most streamlined method to integrate payments into your website. It can show the user what they are buying, show how much it will cost, and even ask for shipping information. The user can pay with their saved credit card information or third party payment processor. [**App Badging API**](https://badging-api.glitch.me/) As a less intrusive (and permissionless) alternative to showing notifications is app badging. This API allows your app to set a badge number, such as a number of new unread notifications, on its icon. [**Vibration API**](https://googlechrome.github.io/samples/vibration/) Activates vibration hardware in the user's device, but must be in response to a click. (Vibration for notifications can be done through the notifications API.) Use sparingly--vibration is often more annoying than helpful, which may explain the API's absence in iOS Safari.
robbiegm
399,030
A quick start base for python developers looking to build AI based chat apps
Today, We will learn how to set up a base for a Python based AI chatbot using the MACHAAO + RASA Samp...
0
2020-07-15T16:02:04
https://dev.to/unixguru2k/a-quick-start-base-for-python-developers-looking-to-build-ai-based-chat-apps-1n7h
machinelearning, python, tutorial
Today, We will learn how to set up a base for a Python based AI chatbot using the MACHAAO + RASA Sample Chatbot Template. So, I have chosen the above mentioned chatbot template because it is easy to learn, build, deploy, monetise, integrate and manage. We will require ngrok (optional) secure introspect-able tunnels to localhost / your laptop. Rasa: Open source conversational Machaao Chatbot template MessengerX.io API Token / Key So, assuming we have all the above covered - Let’s get started! Courtesy: @Abhishek Raj Follow the complete FREE tutorial -> https://www.linkedin.com/pulse/create-deploy-python-chatbot-within-minutes-abhishek-raj/
unixguru2k
399,162
Jersey Configuration with Spring
Hey All!... This is my first post in this platform ,So be soft in the comment section. In this post...
0
2020-07-15T17:49:14
https://dev.to/vinayhegde2013/jersey-configuration-with-spring-4514
java, spring, jersey
Hey All!... This is my first post in this platform ,So be soft in the comment section. In this post I am going to tell how to configure Jersey with Spring. Have you ever wondered how to configure Jersey in the Spring project?. Didn’t find the exact solution for that?. If Yes, you are in the right place. I assume you are comfortable with Spring and REST APIs. In this article, I am going to tell how to set up the jersey in your project. Create a Spring Boot project with **https://start.spring.io/**. Don't forget to add the **spring-boot-starter-jersey** dependency in your `pom.xml`. ``` <dependency> <groupId> org.springframework.boot</groupId> <artifactId>spring-boot-starter-jersey</artifactId> </dependency> ``` After the successful creation of the Spring Boot project Now its time to create resources ( i.e. Resources means you can relate it to Controller what we used to call in SpringMVC). Create each resource as an Interface and implement it. like below. Let POJO class `PublicationResource.java` be : ``` public class PublicationResource { private int publicationId; private String publicationTitle; private String publicationAuthor; // Getters and setters & Constructors } ``` Create a Resource Interface `InformationResource.java` : ``` @Path("information") @Consumes(MediaType.APPLICATION_JSON) @Produces(MediaType.APPLICATION_JSON) public interface InformationResource{ @GET List<PublicationResource> getPublications(); } ``` Now create a class `InformationResourceImpl.java` by implementing a `InformationResource.java` Interface. ``` @Named public class InformationResourceImpl implements InformationResource{ @Override public List<PublicationResource> getPublications() { return Arrays.asList(new PublicationResource(1, “Title1”, “Vinay”), new PublicationResource(2, “Title2”, “Hegde”)); } ``` Here I have hardcoded the PublicationResource values. Real time it should come from database, In that case create a Business Service and call that service from `InformationResourceImpl.java` by using Inject. Now the main Configuration part came into play. How you will configure your Resources into jersey. To do that create a one class `JerseyConfig.java` by extending a ResourceConfig (`import org.glassfish.jersey.server.ResourceConfig`)where we need to register our resources. There are two ways you can register your resource. 1. Register a entire base package in `JerseyConfig.java` : ``` @Configuration @ApplicationPath(“/resource”) public class JerseyConfig extends ResourceConfig { public JerseyConfig() { packages(“your.base.package”); } } ``` This will register all your resources , though I faced issue while starting a embedded tomcat server with this, So I wont recommend this way , Instead of this we can register all resources explicitly. ( Ahh... Bit hectic ? ). 2.Register a resources Explicitly : ``` @Configuration @ApplicationPath(“/resource”) public class JerseyConfig extends ResourceConfig { public JerseyConfig() { register(InformationResource.class); } } ``` Here **@ApplicationPath** will allow us to define a base path for all our resources. Example Once application starts it will running on port number 8080.We can make a GET request by hitting https://localhost:8080/resource/information. Here you can observe after 8080 , `/resource` has been added that is coming from **@ApplicationPath**. All our APIs will have `/resources` before the endpoint you have defined. After making HTTP GET - https://localhost:8080/resource/information result would be : ``` [ { “publicationId”: 1, “publicationTitle”: “Title1”, “publicationAuthor”: “Vinay” }, { “publicationId”: 2, “publicationTitle”: “Title2”, “publicationAuthor”: “Hegde” } ] ``` Cheers!. You have created your first Jersey API. Simple Isn’t it ?:). Please provide your comments or feedback. Happy coding!.
vinayhegde2013
399,180
CS50 Week 2 - Arrays in C
This post is edited from my original blog post. Find it, and other posts by me on kewbish.github.io/b...
7,459
2020-07-16T18:48:18
https://kewbish.github.io/blog/posts/200709/
This post is edited from my [original blog post](https://kewbish.github.io/blog/posts/200709/). Find it, and other posts by me on [kewbish.github.io/blog](https://kewbish.github.io/blog/). # Introduction And now, our *third* week of CS50! This week, we went over arrays, but also spent a lot of time on CLI / terminal tooling, and the various debugging tools used by CS50. I'm starting to get more familiar with the CS50 system, and how I can do problem sets and debug on my *local* system, instead of *the cloud IDE*, which I don't really like. This was our introduction to proper command line arguments, and how to use function arguments in `main` too. [Skip to my thoughts](#problem-sets). # Notes - The lecture itself spends a bunch of time going through CLI information - check50, debug50, style50 - the whole CS50 family - set up check50 and style50 on my local system already through pip, easy install - don't think I've ever used help50. Stack Overflow is more useful, I find. - How does C work? Four-step process - first, preprocessed to pull in headers - compiled to assembly code - then assembly transformed to binary - linked to final executable file - all happens when you run `clang` or the processor - data fits into types - each has a finite set amount of memory, except strings - bool -> 1 byte - char -> 1 - int or float -> 4 - double or long -> 8 - string -> ?, because the number of chars in the string varies, and therefore can change the amount of memory assigned - each variable is labelled in memory with an address - when you define with a const, its value never changes - string -> represented as an array of characters - ends with a null term byte -> `\0` - escaped with the `\` - is this why you use `< strlen` instead of `<= strlen`, so you don't catch the ending byte? - string memory used = (# of char) * 1 byte + 1 byte for null terminating byte - ASCII chars can be subtracted and added from each other - their # code and their character equivalent can be used interchangeably - kind of unintuitive to subtract chars, I prefer numbers - `ctype.h` has useful functions - checks for alphabetic, digits, and most other useful types - equivalent of `typeof` in Python, helps verify what form the data is in - Use `*argv` when using `strlen` to make the actual 'string' array - Otherwise, can't use strlen, and there's a segfault - For encryption problem sets, I prefer using # codes - unfamiliar but more intuitive to do 'distance-from' work and modulo math - most of the psets involve finding a distance from 'a' or 'A', adding a key in some way, and looping back at times - to loop back from an alphabet, use modmath! (% 26) - try to use pseudocode values in subtraction equation - Return codes exist, why they have `int main` - returns either 0, 1, etc. - 1 -> indicate error - 0 -> everything's fine - argc -> make sure that the array count is greater than a certain amount - if you try to access something that doesn't exist in memory yet, it will throw a dreaded *Segmentation Fault* - generally, structure validation functions above the main function - otherwise, define the prototype function, and put it below the main function # Problem Sets Last week, I mentioned how I prefer doing both of the 'more and less' problems in the problem set for a week, noting that the 'more' usually builds off the 'less'. This week was a great example of that. Readability is required for both variations, but Caesar and Substitution were both super fun. Caesar is, what you might think, a caesar cipher implementation. As well, Substitution implements a simple substitution cipher. While working through Caesar, I researched and found a bunch of information about character codes and validating command line arguments, as well as working with aforementioned character codes and CLI arguments. For example, I was super confused about a Segmentation Fault that was thrown while attempting Caesar (because I'd forgotten to check that the argument actually existed), and didn't run into the same issue with Substitution. As well, I learned that you could :gasp: subtract characters, instead of just using the character code. These two morsels of information were super helpful in solving Substitution. Both ciphers deal with some sort of 'distance from `a` and then add key' algorithm, and I found that figuring Caesar out let me work through Substitution so much more quickly. # Setting up CS50 locally I've finally finished setting up CS50's development tools on my own system with WSL - since last week, I've been trying to tweak a couple commands and things to make everything *just work*. Here's a small checklist of things that I'd recommend setting up, and some caveats. - install CS50.h from [their site](https://cs50.readthedocs.io/libraries/cs50/c/). I wouldn't recommend trying to curl things, just install from source. It's easier, especially if you're on WSL. - No need to set up environment variables - more on that later in the bash bit. - if you don't want to bother adding it to your C source folder, you can just put it somewhere convenient to relative path, and use `#include "../cs50.h"`, for example - set up check50 through pip - It's literally just `pip install check50`. - do the same with submit50 and style50. - their installations are equally simple - `pip install submit50` and `pip install style50`. - As they remind, do this through WSL. Having to switch between WSL and non-WSL command prompts is annoying, even in VSCode. - in the WSL `.bashrc`, add a function that has the following command: ```bash cs50make() { clang -ggdb3 -O0 -std=c11 -Wall -Werror -Wextra -Wno-sign-compare -Wno-unused-parameter -Wno-unused-variable -Wshadow "$1".c -lcrypt -lcs50 -lm -o "$1" } export -f cs50make ``` which will let you run `cs50make` in terminal and run the equivalent `make` command, after you've `sourced` the file See - it's not *that* hard. Even easier on Linux, probably. And now, you can CS50 in VSCode, and have beautiful syntax highlighting and snippets. # Conclusion This week was a very nice introduction to more data types, and I'm starting to sense it getting a little more challenging. Hopefully, next week will be as interesting! What are your thoughts on CS50 and C in general?
kewbish
399,324
Melhores Alternativas Gratuitas para o Photoshop – 2020
O Adobe Photoshop é um dos melhores programas disponíveis para design, seu preço porém pode ser desan...
0
2020-07-16T04:28:09
https://marquesfernandes.com/melhores-alternativas-gratuitas-para-o-photoshop-2020/
design, gimp, inkscape, photoshop
--- title: Melhores Alternativas Gratuitas para o Photoshop – 2020 published: true date: 2020-07-14 19:27:26 UTC tags: Design,gimp,inkscape,photoshop canonical_url: https://marquesfernandes.com/melhores-alternativas-gratuitas-para-o-photoshop-2020/ --- O Adobe Photoshop é um dos melhores programas disponíveis para design, seu preço porém pode ser desanimador para usuários ou freelances. Existem diversas ferramentas gratuitas que podem substituir o Photoshop, embora elas não tenham exatamente as mesmas funcionalidades, elas dão conta do recado. 1. [Gimp](#gimp) – Disponível para Windows, Linux e Mac 2. [Inkscape](#inkscape) – Disponível para Windows, Linux e Mac 3. [Krita](#krita) – Windows, Linux e Mac 4. [Pixlr x](#pixlr) – Versão Web 5. [Sumopaint](#sumopaint)– Versão Web, Windows, Linux e Mac ## 1. [Gimp](https://www.gimp.org/downloads/) [![Gimp](https://marquesfernandes.com/wp-content/uploads/2020/07/2.10-update-ui.jpg)](https://www.gimp.org/downloads/) [GIMP](https://www.gimp.org/downloads/), (abreviação de GNU Image Manipulation Program), é uma excelente alternativa para o Photoshop para quem precisam de recursos avançados de edição de imagens mas está com o orçamento apertado. Ele pode ser usado desde um programa básico de pintura até um editor de fotos profissional. Ganhou popularidade por ser uma das primeiras alternativas para o photoshop no Linux, hoje ele está disponível também para Mac e Windows. Como o GIMP também é possível conseguir suporte para importar PSD, embora nem todas as camadas e funcionalidades possam funcionar como esperado. ## 2. [Inkscape](https://inkscape.org/release/inkscape-1.0/) [![Inkscape](https://marquesfernandes.com/wp-content/uploads/2020/07/Voronoi-and-dulaney-1024x693.png)](https://inkscape.org/release/inkscape-1.0/) O [InkScape](https://inkscape.org/release/inkscape-1.0/) seria mais um substituto para o Illustrator do que para o Photoshop, ele é mais voltado para designers gráficos que queiram trabalhar com vetores. Mesmo assim, você pode usá-lo para fazer ajustes básicos de imagens igual faria no Photoshop, como recortar, colar, redimensionar e editar. Também é uma ótima ferramenta para converter fotografias em imagens vetoriais! ## 3. [Krita](https://krita.org/en/download/krita-desktop/) [![](https://marquesfernandes.com/wp-content/uploads/2020/07/krita-ui-40-2.png)](https://krita.org/en/download/krita-desktop/) O Krita é uma alternativa gratuita perfeita do Photoshop, especialmente para fotógrafos que precisam de um pouco mais de flexibilidade em suas edições. O projeto veio de artistas que buscam oferecer ferramentas de edição acessíveis para todos, por isso desenvolveram o [Krita](https://krita.org/en/download/krita-desktop/), focado em artistas conceituais, pintores de texturas e foscos, ilustradores e até criadores de histórias em quadrinhos. Quando se trata de colorir suas fotos, você pode usar a paleta de cores pop-up exclusiva. Além disso, aproveite o sistema de marcação exclusivo da Krita para trocar os pincéis que estão sendo exibidos. Além disso, acesse as cores mais usadas e defina todas as configurações de cores com apenas alguns cliques. Ele é altamente extensível, você pode importar facilmente pacotes de pincéis e texturas de outros artistas, existe uma comunidade muito ativa por trás do projeto. Se você precisar de qualquer ajuda, poderá recorrer ao fórum do Krita, onde outros artistas estão sempre dispostos em compartilhar seus melhores trabalhos, idéias e ajuda. ## 4. [Pixlr x](https://pixlr.com/br/x/) [![](https://marquesfernandes.com/wp-content/uploads/2020/07/image-29.png)](https://pixlr.com/br/x/) [Pixlr x](https://pixlr.com/x/) é a versão mais recente do editor Pixlr. Ele vem com recursos e melhorias muito mais avançadas e busca se tornar uma das melhores alternativas gratuitas do Photoshop do mercado. Desenvolvido em HTML5, o Pixlr x funciona bem em qualquer navegador moderno (incluindo dispositivos mobile). O Pixlr x é um editor de fotos totalmente on-line, o que significa que você pode usá-lo com qualquer sistema operacional. Ele vem com todos os ajustes básicos que você precisa para criar imagens bem editadas e alguns extras também, como as ferramentas de descongelamento e curvas. ## 5. [Sumopaint](https://www.sumopaint.com/) ![Sumopaint](https://marquesfernandes.com/wp-content/uploads/2020/07/sumopaint.jpg) O [Sumopaint](https://www.sumopaint.com/home/) é uma excelente alternativa gratuita para o Photoshop, tanto em design (muito parecido) quando em funcionalidade. Você pode abrir arquivos com extensões como GIF, JPEG e PNG e salvar projetos usando os mesmos formatos, bem como o formato SUMO nativo. O post [Melhores Alternativas Gratuitas para o Photoshop – 2020](https://marquesfernandes.com/melhores-alternativas-gratuitas-para-o-photoshop-2020/) apareceu primeiro em [Henrique Marques Fernandes](https://marquesfernandes.com).
shadowlik
399,396
Have you ever felt that multiple screens do more harm than good sometimes?
Common sense says that more screens equals more productivity but I've just realized that on low focus...
0
2020-07-15T22:04:53
https://dev.to/vtrpldn/have-you-ever-felt-that-multiple-screens-do-more-harm-than-good-sometimes-4hnl
watercooler
Common sense says that more screens equals more productivity but I've just realized that on low focus days like today, having a spare screen actually makes me less productive. What do you think about it?
vtrpldn
399,876
Free Product-Market Fit consultancy (30 mins)
Are you having problems finding a product-market fit for your app or have questions about fundraising...
0
2020-07-16T09:01:22
https://dev.to/gdi3d/free-product-market-fit-consultancy-30-mins-40mf
startup, tips, developer
Are you having problems finding a product-market fit for your app or have questions about fundraising or how to do customer discovery? You can have a free one-to-one consultancy session call with one of the volunteers of GetAdvice https://getadvice.github.io/warren.fauvel.html Disclaimer: I'm the guy behind GetAdvice (volunteers are needed!!). This is a way to promote getadvice.github.io and get more volunteers and users into the site too.
gdi3d
399,903
Send data between tabs with JavaScript
Did you know you can send information between open browser tabs using JavaScript? Let's say your...
0
2020-07-16T10:13:47
https://dev.to/dcodeyt/send-data-between-tabs-with-javascript-2oa
javascript, webdev, tutorial
Did you know you can send information between open browser tabs using JavaScript? Let's say your user is viewing your site with multiple tabs and something happens one tab which you want to react to on the other tabs - you can do this using the [Broadcast Channel API](https://developer.mozilla.org/en-US/docs/Web/API/Broadcast_Channel_API). Before we start, I want to mention that this only works between browsing contexts on the [same origin](https://developer.mozilla.org/en-US/docs/Glossary/origin). #### Browser Support Please also check browser support before using this API. As of July 2020, it doesn't appear to be supported by Safari. Please see the Can I Use... link [here](https://caniuse.com/#search=broadcast%20channel) ### Sending Data To send something to another tab, we need to first create a new `BroadcastChannel` instance. This is super easy, and looks like this: ```js const channel = new BroadcastChannel("my-channel"); ``` Notice how we passed in `my-channel` - this is the **name** of the channel which we are *subscribing* to. When subscribing to a channel, you're then able to post and receive messages from it. Speaking of posting messages, let's do that right now: ```js channel.postMessage("Hey, how's it going mate? I'm from a different tab!"); ``` We can send multiple different kinds of objects with the `postMessage` method, for example: ```js // array channel.postMessage([5, 10, 15, 20]); // object channel.postMessage({ name: "Dom", age: 30 }); // blob channel.postMessage(new Blob(["sample text"], { type: "text/plain" })); ``` ### Receiving messages Now, on the second tab, we can listen for and receive those messages. Open up a new tab (on the same origin, i.e. `localhost`) and include this code: ```js // subscribe to the same channel, "my-channel" const channel = new BroadcastChannel("my-channel"); channel.addEventListener("message", e => { console.log(e.data); }); ``` Once this code is included, open up both the tabs, then refresh the original one (the one doing the posting), and you should see the data appearing in the console. It's that easy! You simply listen for the `message` event and once you have it, access the data with the `data` property. ### Video Tutorial If you prefer a video version of the above tutorial, you can view it on my YouTube channel, **dcode**: {% youtube wYcvzLFHFN0 %} ## [Enrol Now 👉 JavaScript DOM Crash Course](https://www.udemy.com/course/the-ultimate-javascript-dom-crash-course/?referralCode=DC343E5C8ED163F337E1) If you're learning web development, you can find a complete course on the JavaScript DOM at the link below 👇 [https://www.udemy.com/course/the-ultimate-javascript-dom-crash-course/?referralCode=DC343E5C8ED163F337E1](https://www.udemy.com/course/the-ultimate-javascript-dom-crash-course/?referralCode=DC343E5C8ED163F337E1) ![Course Thumbnail](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/nurocyfs69g4yk02uq43.jpg)
dcodeyt
399,998
Let’s Write an IPython Extension the Hard Way
I love IPython. I love using it, I love writing about it, I love taking pictures with its core contri...
0
2020-07-16T17:19:39
https://switowski.com/blog/lets-write-ipython-extension
python, ipython
--- title: Let’s Write an IPython Extension the Hard Way date: 2020-07-16 00:00:00 UTC tags: Python, IPython canonical_url: https://switowski.com/blog/lets-write-ipython-extension cover_image: https://dev-to-uploads.s3.amazonaws.com/i/izf3dv9dp6qee4eorj20.jpg published: true --- I love IPython. I love using it, I love writing about it, I love taking pictures with its core contributors (Hi Paul!). If I ever get invited to the [“Talk Python To Me”](https://talkpython.fm/) podcast (not that I have anything interesting to talk about), and Michael Kennedy is going to ask me what my favorite Python package is, you know what I’m going to say? Yep, IPython. So, when a friend of mine asked me what kind of lightning talk I want to prepare for one of the upcoming micro-conferences, my first thought was: _“Let’s try to make something cool with IPython”_. Maybe I can improve the %rerun magic function? ## What’s wrong with the `%rerun` function? You can use `%rerun` to run commands from this or previous sessions of IPython. The most common use case for me is to get my IPython session to the same state when I left it last time. It usually happens when I close it because I think I’m done, and then I realize that I actually want to check one more thing **with all the previous data that I had**. Well, in standard Python REPL, to rerun all the previous commands, I would have to press “arrow up” + “enter” a lot. With IPython, I can just run this one command: `%rerun ~1/`, and it will execute all the commands from the previous session: ```python In [1]: a = 5 In [2]: b = 10 # Close IPython and open a new session In [1]: %rerun ~1/ === Executing: === a = 5 b = 10 === Output: === In [2]: a Out[2]: 5 In [3]: b Out[3]: 10 ``` But, there is one problem. If one of the past commands throws an exception, IPython will stop. It executes all the commands up to the exception, fails on the exception, and that’s it: ```python In [1]: a = 5 In [2]: b = 1/0 ----------------- ZeroDivisionError ----> 1 b = 1/0 ZeroDivisionError: division by zero In [3]: c = 10 # Close IPython and open a new session In [1]: %rerun ~1/ === Executing: === a = 5 b = 1/0 c = 10 === Output: === ----------------- ZeroDivisionError 1 a = 5 ----> 2 b = 1/0 3 c = 10 ZeroDivisionError: division by zero In [2]: a Out[2]: 5 In [3]: c -------------- NameError ----> 1 c NameError: name 'c' is not defined ``` So if I want to execute the code after the exception, I have to figure out which command fails and rerun all commands after that line. For example, I can call: `%rerun ~1/5-66`, and this will run all commands from 5th until 66th command. This has some limitations. First of all, you need to say which commands you want to run explicitly. And for that, you need to know the total number of commands for a given session. It’s no longer as convenient as just writing `%rerun ~1/` and letting IPython figure out the rest. Second of all - I don’t know about you, but I have plenty of exceptions in my IPython sessions. After all, that’s why IPython is for - experimenting with the code to find out what works and then copying that. So for each of the failed commands, I would have to exclude this line from the `%rerun`. This can quickly turn into a monstrosity like this: `%rerun ~1/1-2 ~1/4-6 ~1/8-12 ~1/15-23 ...` It would be much better to temporarily ignore all the exceptions. > _“Let’s write an extension that does that!”_ - I thought. _“It probably won’t take longer than 5 minutes to explain everything, so it’s a perfect material for a lightning talk”._ It took longer than 5 minutes. Much longer. But it was an exciting journey! ## Is there a plugin for that? The first step was to check if someone already asked about this feature in the past. “Ignore exceptions” setting would be useful, so clearly someone must have thought about that before me. And someone did - already in 2012: [Add an ‘ignore exceptions’ mode to run commands in notebook](https://github.com/ipython/ipython/issues/1977). Starting from version 5.1, you can tag a cell in IPython notebooks with “raises-exception” to indicate that an exception is expected. IPython will ignore it and continue the execution. Unfortunately, it works only for the notebooks (so Jupyter Notebook), not for IPython REPL. ## _“Fine, I will do it myself.”_ Let’s look inside the `%rerun` function and see how it works: ```python # IPython/core/magics/history.py def rerun(self, parameter_s=''): opts, args = self.parse_options(parameter_s, 'l:g:', mode='string') if "l" in opts: # Last n lines n = int(opts['l']) hist = self.shell.history_manager.get_tail(n) elif "g" in opts: # Search p = "*"+opts['g']+"*" hist = list(self.shell.history_manager.search(p)) for l in reversed(hist): if "rerun" not in l[2]: hist = [l] # The last match which isn't a %rerun break else: hist = [] # No matches except %rerun elif args: # Specify history ranges hist = self.shell.history_manager.get_range_by_str(args) else: # Last line hist = self.shell.history_manager.get_tail(1) hist = [x[2] for x in hist] if not hist: print("No lines in history match specification") return histlines = "\n".join(hist) print("=== Executing: ===") print(histlines) print("=== Output: ===") self.shell.run_cell("\n".join(hist), store_history=False) ``` Basically, it reuses the `%history` magic command to grab a list of commands from history and executes them. I could monkey-patch this function and check if a given command is successful before adding it to the `hist` list. But monkey-patching external libraries is a bad idea. I would have to fork IPython and take care of upgrading it, or I would be stuck on the current version. So I needed a better way. My first idea was to use one of [IPython’s events](https://ipython.readthedocs.io/en/stable/config/callbacks.html). You can register a callback function when a specific event happens, for example, before or after you run a cell. When this event happens, IPython calls your callback function. That looked like a perfect solution! I could check if a given cell throws an exception and, if it does, skip it. ## Writing a callback for IPython events To register my custom callback, I needed to create an IPython extension (I wrote an article explaining [how extensions work and how to create one](https://dev.to/switowski/ipython-extensions-guide-35cn)): ```python # ~/.ipython/extensions/ignore_exceptions.py def clean_input(info): try: exec(info.raw_cell) except Exception: info.raw_cell = '' def load_ipython_extension(ipython): ipython.events.register('pre_run_cell', clean_input) ``` The `load_ipython_extension` registers `clean_input` callback that will be run before executing every cell. And `clean_input` does the following steps: - Takes an argument (`info`) containing various information about the cell we are about to run. This parameter is mandatory, and IPython will complain if we forget it. - Extracts the content of the cell (`raw_cell`). - Tries to run it. - And if it raises an exception, replaces that cell with an empty string. We save that file in the `~/.ipython/extensions/ignore_exceptions.py` directory and enable our extension with: ``` %load_ext ignore_exceptions ``` If we try it: ``` In [1]: %load_ext ignore_exceptions In [2]: 1/0 ZeroDivisionError ----> 1 1/0 ZeroDivisionError: division by zero ``` …it doesn’t really work. There are multiple problems with this code: 1. First of all - we are using `exec`, which is not the best practice. But since the code we want to run is the same code we wrote before, I’m fine with that. 2. The `info` parameter can contain multiple commands. If we call `%rerun 1-10`, `info` will contain the first ten commands from the current session. If the exception happens, let’s say in the 5th command, our current implementation will ignore all the commands. But we want to ignore only that 5th one and still execute the other nine commands. So that’s not going to work. 3. And even if we didn’t have all those problems, **overwriting the `info.raw_cell` doesn’t actually change the code that will be executed**. We need something better. ## Input transformation If we want to modify the input cells before they get executed, there is a feature exactly for that called [“input transformation”](https://ipython.readthedocs.io/en/stable/config/inputtransforms.html). You write a function that takes the input, modifies it, and returns it. And you can register your input transformation as an extension, exactly as we did before. There are two types of input transformers: - `input_transformers_cleanup` - they run first. At this point, the cell is not guaranteed to contain valid Python code (e.g., IPython-specific syntax, like the magic functions). - `input_transformers_post` - they run last, and here the cell contains only the Python code. In most cases, you want to use this one. Input transformation solves all our problems (except for using the `exec`, but I will stick with it for simplicity). First of all, it’s an _“input”_ transformation, so we can use it to change the input cell’s content. And since each line of the input is a separate element in a list, we can just execute them one by one and discard those that raise an exception. So this is what we are going to do: ``` def clean_input(lines): new_lines = [] for line in lines: try: exec(line) new_lines.append(line) except Exception: pass return new_lines def load_ipython_extension(ipython): ipython.input_transformers_post.append(clean_input) ``` Let’s load it and run it: ``` In [1]: %load_ext ignore_exceptions In [2]: 1/0 In [3]: 1+2 Out[3]: 3 In [4]: my_number = 10 In [5]: my_number + 5 # Nothing is returned! ``` It’s working, but partially. If we assign a variable (`In [4]`) and then reference it (`In [5]`), you will notice that nothing is returned! That’s because `my_number` variable was saved in the **local namespace** of IPython, and the `exec` function call is running without access to those variables. Our extension tries to reference variable `my_number`, gets a `NameError`, and since our code is supposed to ignore errors, it ignores that line. Thus - nothing is printed! We need to tell `exec` about all the variables that have been defined so far. If you check the [signature of the exec() function](https://docs.python.org/3.8/library/functions.html#exec), you will see that apart from the code to execute, we can also pass global and local variables. Bingo! Let’s grab the `user_ns` from the `ipython` object and pass it to the `exec` function. `user_ns` contains all the variables that were defined so far, but also all the imported modules, classes, etc. We need to change this line: ``` exec(line) ``` into this: ``` exec(line, None, ipython.user_ns) ``` But the `clean_input` function doesn’t have access to the `ipython` object! And we can’t pass it as a parameter: ``` def clean_input(lines, ipython): ``` because input transformer functions need to have a specific signature and they can accept only one parameter - the list of lines. We could solve this problem using a class, but I prefer to use a technique called [currying](https://en.wikipedia.org/wiki/Currying): ``` def curry_clean(ipython): def clean_input(lines): new_lines = [] for line in lines: try: exec(line, None, ipython.user_ns) new_lines.append(line) except Exception: pass return new_lines return clean_input def load_ipython_extension(ipython): ipython.input_transformers_post.append(curry_clean(ipython)) ``` Let’s try again: ``` In [1]: %load_ext ignore_exceptions In [2]: 1/0 In [4]: my_number = 10 In [5]: my_number + 5 Out[5]: 10 ``` It’s working! Kind of…. We can declare a variable and reference it later, so that’s good. If the code throws an exception, it will be suppressed - that’s also what we want. But if we call a `print()` function, we get the output three times! ``` In [6]: print('hello world') hello world hello world hello world ``` That’s because our input transformation function is actually called twice! Once in the `should_run_async()` function and then in the `run_cell()` function. That’s the behavior of version 7.15 of IPython - the latest one when I write this. And there is nothing you can do about it. If you ever decide to write some input transformations, keep in mind that **they can run multiple times**. And when we actually execute the code, that’s the third `print()`. This “triple printing” can be mildly annoying, but maybe it’s not that bad? All we want to do is to rerun previous commands in one go, so we can live with duplicated output that happens only once. But if printing happens multiple times, then every other command happens multiple times. And if we run a command that is not idempotent: ``` In [7]: my_number = 10 In [8]: my_number += 1 In [9]: my_number Out[9]: 13 ``` We get a bug. 10 incremented by 1 should give us 11, but instead, we get 13. Modifications that we do in `try/except` block get propagated back to our IPython session because we are accessing variables from that namespace. Remember the `ipython.user_ns`? It works both ways - for accessing and **assigning** variables. If we don’t want to modify the original namespace, let’s make a copy and execute our code there! Except that we would need to do a [deep copy](https://docs.python.org/3.8/library/copy.html?#copy.deepcopy). Why a deep copy? Because if we have mutable variables (like a list) and do a shallow copy, modifying the mutable variable in the copied namespace will still affect the original namespace. We need to cut the connections between both namespaces completely, so we use the deep copy. Deep copy basically pickles and un-pickles every object. Do you know what can’t be pickled? Modules. And do you know what IPython’s (or Python’s) namespace contains, except for functions and variables? Modules! So deep copy is going to crash. Unless we filter the namespace and only pickle things that can be pickled! In the end, I only need to copy variables. I won’t be able to modify modules anyway, so it’s fine to leave them in the namespace as they are. Let’s add a new function for this: ``` from copy import deepcopy def copy_namespace(local_ns): copy_ns = {} for key, value in local_ns.items(): try: copy_ns[key] = deepcopy(value) except TypeError: # TypeError is raised when an object can't be pickled copy_ns[key] = value return copy_ns ``` And here are two changes that we need to make in the `curry_clean` function: ``` def curry_clean(ipython): def clean_input(lines): new_lines = [] + local_ns = copy_namespace(ipython.user_ns) for line in lines: try: - exec(line, None, ipython.user_ns) + exec(line, None, local_ns) new_lines.append(line) except Exception: pass return new_lines return clean_input ``` We are almost there, but there are two problems left: - We still get a lot of duplicated output for `print` and similar commands. - Our function doesn’t work for multiline strings (so all `for-loops`, function definitions, and similar multiline statements will crash it). Let’s solve them now. First, the duplicated output. We can suppress it by redirecting the standard output to `/dev/null`: ``` import os import sys sys.stdout = open(os.devnull, 'w') print("I'm invisible") ``` If we run the above code, the output of a print statement won’t be displayed. Actually, no other output will be displayed afterward, so we need to set the `stdout` back to the original value after the `try/except` check. If we want to execute some code, run a function, and then execute more code, the best tool to use is a context manager. Let’s write one: ``` import os import sys from contextlib import contextmanager @contextmanager def no_output(): original_stdout = sys.stdout sys.stdout = open(os.devnull, 'w') yield sys.stdout = original_stdout ``` I’m using the `contextmanager` decorator to turn my function into a context manager (it saves me from writing boilerplate code). Here is what my function does: - Store the original stdout in a variable. - Replace the `stdout` with `/dev/null` (whatever you write to `dev/null` is gone). - Yield - so run the code inside the context manager. - And, finally, restore stdout to the initial value. Now, we wrap our `exec` function with this context manager: ``` for line in lines: + with no_output(): try: exec(line, None, local_ns) new_lines.append(line) except Exception: pass return new_lines ``` Uff, almost there! The last part is to enable running multiline code. For that, we just need to check if the line starts with a whitespace character. If it does, combine it with the previous line. Let’s write a helper to transform multiline strings into one-line strings: ``` def combine_multiline(lines): new_lines = [] for line in lines: if line.startswith(' ') and new_lines: new_lines[-1] += line else: new_lines.append(line) return new_lines ``` The second part of the `if line.startswith('') and new_lines` is just a sanity check to make sure that `new_lines` already contains items. Normally, we wouldn’t bother with checking for this. If the first line starts with spaces, there is something wrong with it, and it will fail during the execution anyway. Let’s call our function in the correct place: ``` def clean_input(lines): new_lines = [] + lines = combine_multiline(lines) ``` And finally, our hackish input transformation _seems to_ be working! _Seems to_, because there is an interesting bug. If we try to rerun a command that reloads our extension (`%reload ignore_exceptions`), IPython will get into an infinite loop. It will try to add `clean_input` callback again. This will run the callback itself. The callback will try to execute `%reload ignore_exceptions` that will register `clean_input` that will call the callback, and so on. Until it crashes. We can solve this problem by adding the **“unload”** function that lets you disable an extension. In our case, we want to remove `clean_input` from the list of `input_transformers_post`: ``` def unload_ipython_extension(ipython): ipython.input_transformers_post = [ f for f in ipython.input_transformers_post if f. __name__!= 'clean_input' ] ``` The above code goes through the list of all input transformers and removes the one called “clean\_input”. We can’t replace the `if f. __name__!= 'clean_input'` with `if f == curry_clean(ipython)` because each time we call `curry_clean(ipython)` it creates a different object. So the `curry_clean` function added to the input transformers list has a different id than `curry_clean` called in the comparison. We could use a singleton design pattern if we want, but we might just compare functions’ names, which will work just fine. With unload in place, our extension is finally ready. You can activate it, run some code, and notice that no exceptions are raised. You can also deactivate it with: ``` %unload_ext ignore_exceptions ``` ## Meet %rerunplus: %rerun that ignores exceptions But how can we use it in combination with `%rerun`? The simplest way is to create a new magic function that wraps a call to `%rerun` in load/unload functions. Let’s make a new file inside `~/.ipython/profile_default/startup/` directory and define our magic function there. During startup, IPython automatically executes files defined in this directory. It’s a good place to put magic functions that we want to enable in each IPython session. ``` from IPython.core.magic import register_line_magic @register_line_magic def rerunplus(line): get_ipython().run_line_magic('load_ext', 'ignore_exceptions') get_ipython().run_line_magic('rerun', line) get_ipython().run_line_magic('unload_ext', 'ignore_exceptions') def load_ipython_extension(ipython): ipython.register_magics(rerunplus) ``` Your code editor will complain that the `get_ipython()` is not defined, but actually, that’s a global function in IPython, so it’s fine. If you restart IPython, you will now have access to a `%rerunplus` magic function. Let’s give it a try. First, run some code with exceptions: ``` a = 1 b = 2 1/0 c = 3 myfile = open('beep') d = 4 ``` Next, close and reopen IPython. If you try to rerun all the commands using the standard `%rerun`, it will fail at `1/0` exception. `a` and `b` variables will be set, but `c` and `d` won’t. But if we use our new, cool `%rerunplus`, it will ignore all the exceptions and set all variables correctly: ``` In [1]: %rerunplus ~1/ === Executing: === a = 1 b = 2 1/0 c = 3 myfile = open('beep') d = 4 === Output: === In [2]: a Out[2]: 1 In [3]: b Out[3]: 2 In [4]: c Out[4]: 3 In [5]: d Out[5]: 4 ``` [Here is the complete code](https://gist.github.com/switowski/301320fb6388822a76644461219e4386) from this article. ## Conclusions We have built an improved version of `%rerun` that ignores exceptions. Is it efficient? Nope. It’s a hackish solution that you should use only with your own code, especially since we use `exec`. `exec` should never be used to run some code that you have no control over! But those 60 lines of code are good enough to fix one of the biggest shortcomings of the original `%rerun` command. P.S. What happens if we try to `%rerun` code that contains `%rerun` instruction? We get a `RecursionError`. This is a bug that both standard `%rerun` and my `%rerunplus` share. So if you got curious about digging into IPython, you can take my extension and try to fix it on your own.
switowski
400,147
My First Programming Project
Leading up to my first project, I was feeling anxious, nervous and excited at the same time. It’s cra...
0
2020-07-16T12:00:02
https://dev.to/mindful_developer/my-first-programming-project-2elk
ruby, cli
Leading up to my first project, I was feeling anxious, nervous and excited at the same time. It’s crazy to this that a month ago I had no coding background, and now I’m tasked with creating a project based off the knowledge I’ve learned in the past month. I felt that I could do it and was excited to put my knowledge to the test. I decided to scrape the Formula Drift schedule webpage and give the user the option to select which event they would like to learn more info on. I then created my plan on how I wanted the structure of my program to be based on a user’s point of view. I watched Avi’s CLI walkthrough and liked how he didn’t focus on every issue that he thought he would need to solve, but instead one issue at a time starting from the what he wanted his program to do. Once I decided on how I wanted the CLI to work, I then built the CLI with fake information. This allowed me to establish a functional CLI so I could then worry about the logic the rest of the program. From there I started inspecting the web page to get an understanding of how I would need to go about retrieving the information that I needed. After poking around a bit, I finally discovered the correct css selector that captured the entire table of event information. This was great because it allowed me to only have to scrape the website once for all the attributes of every event. After that I established my scraper class and created a class method that scraped the website and organized the scrape information into a hash of event with attribute keys pointing to the event specific values. I stored this hash in an array to then iterate through and create new instance of the event class for each event with the appropriate attributes. I found that to be difficult, and constantly wonder if there is a simpler way to do it. When an instance of the event class is instantiated, each instance is pushed into the class variable ‘all’ which stores every instance of the event class. I used that to iterate through for the information I need in certain parts of the CLI. Overall I found the project to be challenging and fun at the same time. I particularly had trouble with the actual logic of certain things and constantly found myself not liking my original code and searching for a “dryer” way. However I did really enjoy doing it and find it really satisfying that I completed it. It definitely gave me a confidence boost that I needed!
mindful_developer
400,203
What are your best meeting hacks? 👨🏻‍💼🚀
I've been thinking a lot about meetings recently. So many of us are stuck with unproductive meetings...
0
2020-07-16T13:29:25
https://dev.to/xenoxdev/what-are-your-best-meeting-hacks-5ckl
discuss, watercooler, productivity
I've been thinking a lot about meetings recently. So many of us are stuck with unproductive meetings day in and day out. So I wrote a post about it on Medium today and shared my best tips on how to make meetings productive. You can find the post here! [![Alt Text](https://dev-to-uploads.s3.amazonaws.com/i/6jakb110vdjtvjqo9qr0.jpg)](https://medium.com/skynox/productive-meetings-guide-d3f8b8ebe48d) ## tl;dr 1. A meeting isn't always needed. Asynchronous communication can replace a lot of meetings. 2. Meetings should have a deadman switch and should be short by default. 3. Always have a solid agenda! Don't aimlessly conduct meetings. 4. Fewer people = better meetings! 5. Get team members to engage more. Make sure quieter members also contribute to discussions. 6. Always have someone take meeting notes and share them afterward. People should know what actionable items have been decided! ### Got any hacks of your own? I'm curious and always looking to make communication with my team more productive! Share your best advice with me. You can do it in the comments or on this Twitter thread. {% twitter 1283744732275896321 %} ### [Here's a cheatsheet for better meetings.](https://blog.skynox.tech/how-to-make-meetings-un-suck/) Anyway, share your thoughts! Cheers!
sarthology
400,361
Scrolling to the Top in CSS
This post was inspired by "Stop Using Fixed Headers and Start Using Sticky Ones" by Luis Augusto, whe...
0
2020-08-03T13:40:24
https://dev.to/platformos/scrolling-to-the-top-in-css-28lm
css, webdev
This post was inspired by "[Stop Using Fixed Headers and Start Using Sticky Ones](https://dev.to/luisaugusto/stop-using-fixed-headers-and-start-using-sticky-ones-1k30)" by Luis Augusto, where he explained why `position: fixed` is an inferior way of sticking headers. {% post https://dev.to/luisaugusto/stop-using-fixed-headers-and-start-using-sticky-ones-1k30 %} ## Problem I want to add one tip for anyone doing sticky/fixed headers while keeping internal links working correctly. If you have a long page, you might include a table of contents that links to sections on the page. See this example from [our documentation site](https://documentation.platformos.com/api-reference/liquid/introduction): ![Table of contents](https://dev-to-uploads.s3.amazonaws.com/i/9bq3h2msj0vhzfefj8ju.png ) By default, when you click on an internal link, the browser scrolls the page just below that element, which will cause it to be invisible for the user. This causes confusion. It is even worse if you have a fixed/sticky header on your website like we do because even more content will be covered due to this behavior. See an example from our documentation site after clicking on "Output": ![Before](https://dev-to-uploads.s3.amazonaws.com/i/hx2mkn17hd9wpexq37el.png) This behavior is not user-friendly, so in the old days there were [multiple hacks](https://css-tricks.com/hash-tag-links-padding/) to fix it - I usually resorted to JavaScript because it didn't leave a trace in CSS or HTML. # The modern solution In 2020, there is a better way: use the CSS property called `scroll-margin-top`. Add it to a header that you are linking to, and the browser will subtract this value when scrolling. In our case we added: ```css main h2, main h3 { scroll-margin-top: 95px; } ``` And now, after clicking on "Output": ![After](https://dev-to-uploads.s3.amazonaws.com/i/oe00ibtqslhky57grlmf.png) We get a much better experience with a native-only solution. [See a live demo](https://documentation.platformos.com/api-reference/liquid/introduction). [Read more on scroll-margin on CSS-Tricks](https://css-tricks.com/almanac/properties/s/scroll-margin/). ## Read more If you are interested in more performance oriented content, follow me and I promise to deliver original, or at least effective methods of improving your website. {% link https://dev.to/platformos/using-webp-in-your-existing-webpage-809 %} {% link https://dev.to/platformos/optimizing-images-for-the-web-18gc %} {% link https://dev.to/platformos/3-tips-on-preserving-website-speed-5g0c %}
pavelloz
400,937
Seeing Sound with Amit Nambiar
Sharing a passion project of visualizing audio in 3D, talking through the assumptions, limitations, and challenges.
0
2020-07-23T11:52:46
https://dev.to/amitlzkpa/seeing-sound-with-amit-nambiar-18ik
codeland, audio, visualization
--- title: Seeing Sound with Amit Nambiar published: true description: Sharing a passion project of visualizing audio in 3D, talking through the assumptions, limitations, and challenges. tags: codeland, audio, visualization cover_image: https://dev-to-uploads.s3.amazonaws.com/i/dw8xm7m8ycvafjwfaqtr.png --- Hey, I'm Amit! I'm an architect turned computational designer who now helps architects and engineers make buildings faster and better. In this talk I'm going to talk about a passion project I've been working on where I'm trying to visualise audio in 3D. Sound is an excitation of a medium like air which moves like a wave from the source. While this is well known when it comes to understanding the physics of it we are often introduced to squiggly lines on a paper followed by abstract interpretation of it in math. In this talk I'll be talking about my research project where I parse audio using the WebAudioAPI and visualise it in its complete volumetric glory in the browser. I'll talk about my assumptions, limitations and challenges encountered in the process and attempt to breakdown the physics of some by showing its wavelike behaviour and how I use this information to create a 3D visualization. Check it out at: https://lotusaudio.herokuapp.com/view/5ee4fe4610a0ec114483fd4e Slides: {% slideshare NM9EY9oYslwfE %} **[Here is a download link to the talk slides (PDF)](https://drive.google.com/file/d/1aE_MKYVWXeU2BI3LbpexjSs37vYefRon/view?usp=sharing)** --- _This talk will be presented as part of [CodeLand:Distributed](https://codelandconf.com) on **July 23**. After the talk is streamed as part of the conference, it will be added to this post as a recorded video._
amitlzkpa
401,094
UML: Vantagens e Desvantagens
Estudar UML é sempre um jogo de perguntas e respostas para a profissão de desenvolvedor, por um ponto...
0
2020-07-16T22:16:45
https://dev.to/marcialwushu/uml-vantagens-e-desvantagens-4bnd
uml, braziliandevs
Estudar UML é sempre um jogo de perguntas e respostas para a profissão de desenvolvedor, por um ponto de vista, ela é uma estrutura padrão no ensino acadêmico superior e nos é mostrada como algo essencial e indispensável para a modelagem e arquitetura do software a ser desenhado, por outro ponto de vista, temos opiniões contrárias de alguns profissionais dizendo que não existe tanta importância a sua utilização, a modelagem geralmente é feita DER da estrutura do banco de dados e os requisitos listados, com documentação superficial ou sem documentação, fruto da metodologia ágil, alguns dizem; e talvez o fator que esteja fazendo esse aculturamento de desprezo pela utilização da UML e seus 14 tipos de diagramas Com objetivo de tentar listar as vantagens e desvantagens do uso dessa ferramenta de modelagem, realizei algumas pesquisas, o texto [“A complexibilidade da UML e seus diagramas”](http://revista.faculdadeprojecao.edu.br/index.php/Projecao4/article/view/825) de Bonny Martins, Walisson Diniz e Rogerio da Silva, faz uma introdução da ferramenta, abordando aspectos históricos, técnicos e explicando cada diagrama proposto e sua utilização, mas para entregar esse texto, preciso de opniões práticas de uso, e existe muita discussão sobre o tema em redes sociais e blogs de empresas como a Creately.com e Techwalla usados como referência base desse texto e threads de discussão no Twitter e no site dev.to. Minha humilde experiência e opinião acerca do tema, é o não uso, talvez por que a equipe de desenvolvimento é pequena, demanda exagerada onde a documentação e modelagem está em estrutura de banco de dados e rascunhos com checklists de funcionalidades, sei e tenho consciência que não é uma boa prática, acho importante tentar documentar, listar processos e code review do código fonte, elaborar documentação do código com ferramentas específicas, para retirar a dependência da lógica de negócio de está com uma única pessoa. # Vantagens da UML ### Mais usados ​​e flexíveis UML é uma plataforma altamente reconhecida e compreendida para design de software. É uma notação padrão entre desenvolvedores de software. Você pode assumir com segurança que a maioria dos profissionais de software conhece pelo menos os diagramas UML, se não bem versados, tornando-o a alternativa ideal para explicar os modelos de design de software. ### Representação visual Um diagrama UML é uma representação visual dos relacionamentos entre classes e entidades em um programa de computador. Ao mostrar essas informações em um diagrama, é fácil entender e visualizar os relacionamentos de um programa ### Legibilidade e reutilização Um diagrama UML é benéfico, pois é muito legível. O diagrama deve ser entendido por qualquer tipo de programador e ajuda a explicar os relacionamentos de um programa de maneira direta. Além disso, usando um diagrama para mostrar o código em execução em um programa, um programador pode ver código redundante e reutilizar partes do código que já existem, em vez de reescrever essas funções ### Padrão Por ser usado como padrão, é amplamente entendido e bem conhecido. Isso facilita para um novo programador entrar em um projeto e ser produtivo desde o primeiro dia. ### Ferramenta de Planejamento A UML ajuda a planejar um programa antes que a programação ocorra. Em algumas ferramentas usadas para modelar UML, a ferramenta irá gerar código com base nas classes configuradas no modelo. Isso pode ajudar a reduzir a sobrecarga durante o estágio de implementação de qualquer programa. ### A arquitetura do software deve ser comunicada com eficácia A arquitetura do software é a planta do sistema. É a estrutura da qual depende a eficiência do sistema e de seus processos. Mas, essa estrutura só é eficaz se for comunicada adequadamente a todos que a utilizam e trabalham nela. É aqui que a UML ( Unified Modeling Language ) entra em cena. Devido ao seu amplo alcance, a UML é a linguagem visual perfeita para comunicar informações detalhadas sobre a arquitetura ao maior número de usuários. Você precisa conhecer apenas uma fração da linguagem para usá-lo Embora existam 14 tipos diferentes de diagramas UML para aplicativos de modelagem, os desenvolvedores usam apenas três ou quatro para documentar um sistema de software. Diagramas de classes, diagramas de seqüência e diagramas de casos de uso continuam sendo os mais procurados. ### Abundância de ferramentas UML As ferramentas UML são uma das razões mais importantes pelas quais a UML é tão amplamente usada. As ferramentas UML variam de software de código aberto gratuito até aqueles que custam milhões de dólares. Essas ferramentas cobrem muito território, além de apenas desenhar diagramas. Eles podem gerar código a partir do design, aplicar padrões de design, requisitos de mina, código de engenharia reversa e executar análises de impacto e complexidade. # Desvantagens da UML ### Notação formal não é necessária O argumento mais forte contra a UML é que você realmente não precisa de um diagrama UML para comunicar seus projetos. Você pode ter o mesmo impacto e efeito com diagramas informais de caixa e linha criados no PowerPoint, Visio ou em um quadro branco. Como a codificação é uma linguagem formal por si só, muitos desenvolvedores não preferem a complexidade e a formalidade no nível da arquitetura, o que desencoraja o uso da UML e se tornou uma de suas desvantagens. ### Grau de complexidade crescente Desde o seu início até agora, a UML cresceu em complexidade e tamanho. O tamanho da UML deixa muitas pessoas nervosas logo no início, e elas sentem que não serão capazes de aprender e que estão melhor sem ela. ### Não é necessário em 'design indiferente à arquitetura' Um termo cunhado [por George Fairbanks, 'design indiferente à arquitetura'](https://www.amazon.com/Just-Enough-Software-Architecture-Risk-Driven/dp/0984618104/ref=sr_1_1?s=books&ie=UTF8&qid=1287576926&sr=1-1) é uma situação em que a UML é considerada desnecessária. Na sua essência, um design indiferente à arquitetura refere-se a uma arquitetura de software simples e básica e não precisa de nenhum diagrama complexo para representar ou explicar o design. Se as empresas enfatizarem mais a codificação formal e houver uma cultura predominante de documentação mínima de design, a UML será considerada desnecessária. ### Tempo Uma desvantagem que alguns desenvolvedores podem encontrar ao usar a UML é o tempo necessário para gerenciar e manter os diagramas da UML. Para funcionar corretamente, os diagramas UML devem ser sincronizados com o código do software, o que requer tempo para configurar e manter, além de adicionar trabalho a um projeto de desenvolvimento de software. ### Quem não se beneficia Nem sempre é claro quem se beneficia de um diagrama UML. De acordo com um artigo publicado no site da Eiffel Software, a UML não é vantajosa para os desenvolvedores de software, principalmente porque os desenvolvedores de software trabalham com código, não com figuras ou diagramas. ### Diagramas podem ficar impressionantes Ao criar um diagrama UML em conjunto com o desenvolvimento de software, o diagrama pode se tornar esmagador ou complicado demais, o que pode ser confuso e frustrante para os desenvolvedores. Os desenvolvedores não podem mapear todos os cenários de uma ferramenta de software no diagrama e, mesmo que tentem, o diagrama fica confuso ### Muita ênfase no design A UML coloca muita ênfase no design, o que pode ser problemático para alguns desenvolvedores e empresas. Observar um escopo de software em um diagrama UML pode fazer com que as partes interessadas do projeto de software super examinem os problemas, além de fazer com que as pessoas percam o foco gastando muito tempo e atenção nos recursos de software. As empresas não podem resolver todos os problemas com uma ferramenta de software usando um diagrama UML - eventualmente, elas apenas precisam começar a codificar e testar Todas as opções levantadas tem sua lógica e o uso ou adoção do UML dentro de uma empresa vai depender de uma séries de variáveis, como time de desenvolvimento, tamanho da equipe, necessidade, apesar que necessidade vai ocorrer em algum momento, nem que seja um documentação de processo usando BPMN, ou uma documentação inicial usando UML. Brody Gooch, co-criador da UML, disse que a visão original da UML era uma "linguagem gráfica para ajudar a raciocinar sobre o design de um sistema à medida que ele se desenrola". E as inúmeras discussões e opiniões levantadas e encontradas na pesquisa inicial encontramos outros métodos e direcionamentos de substituição ou complementar. Exemplo: - [modelo C4](https://c4model.com/) (esta é uma abordagem de abstração para diagramação; compatível com UML) criado por [Simon Brown](https://simonbrown.je/) - A pesquisa do Dr. Sebastian Baltes no artigo sobre ["Esboços e diagramas na prática"](https://empirical-software.engineering/assets/pdf/xp16-sketching.pdf) descreve que a maioria dos esboços e diagramas no estudo era bastante informal e apenas 9% deles foram classificados como diagramas UML "puros". - Para sistemas intensivos em banco de dados, o [Crow's foot](http://www2.cs.uregina.ca/~bernatja/crowsfoot.html) - [notação de Chen](https://www.vertabelo.com/blog/chen-erd-notation/) para diagramas de ER são úteis. - O [SysML](https://www.omgsysml.org/what-is-sysml.htm) é um bom elogio à UML para engenharia de sistemas. - [notações de modelagem do IDEF](http://www.sba.oakland.edu/faculty/mathieson/mis524/resources/readings/idef/idef.html#:~:text=The%20Integrated%20Computer%2DAided%20Manufacturing%20Definition%20(IDEF)%20language%20consists,data%22%20associated%20with%20the%20ICOMs.) >Martin Fowler [escreveu cerca de quatro deles - esboço, notas, planta e linguagem de programação](https://martinfowler.com/bliki/UmlMode.html). A UML é uma linguagem rica, mas isso não significa que você precise usar todos os recursos que ela oferece. Escolha e escolha adequadamente e faça seus modelos no nível apropriado para o público-alvo. Mas siga as regras que a linguagem fornece para que as pessoas possam entender facilmente a notação usada Esse foi um comentário de um usuário sobre UML em uma discussão no site [Dev.to](https://dev.to/rafalpienkowski/do-developers-still-need-uml-ajh) acerca de classifcações dada a UML sob a perspectiva de quem está utilizando e usando como exemplo um artigo de Martin Fowler onde ele conclui que quando a visão de alguém da UML parece bastante diferente da sua, talvez seja porque eles usam um modo diferente para você. Além disso, sua percepção da UML pode ser afetada pelo modo em que ela foi introduzida a você. Outra referência que podemos encontrar conectada diretamente a UML são os softwares [MDE - Model Driven Engineering](https://ict.eu/model-driven-engineering/) que hoje em dia estão usando palavras da moda como [Low-Code Platforms](https://modeling-languages.com/low-code-platforms-new-buzzword/) com suas telas de arrastar e soltar já conhecidas do MDE com uma reformulação da marca usando terminologia novas, mas atuando no mesmo segmento de modelagem do sistema e geração automática de código. # REFERÊNCIAS: https://www.techwalla.com/articles/list-of-advantages-of-uml https://www.techwalla.com/articles/the-disadvantages-of-uml https://creately.com/blog/diagrams/advantages-and-disadvantages-of-uml/ https://saturnnetwork.wordpress.com/2010/10/22/five-reasons-developers-dont-use-uml-and-six-reasons-to-use-it/ https://c4model.com/ https://simonbrown.je/ https://empirical-software.engineering/assets/pdf/xp16-sketching.pdf https://empirical-software.engineering/publications/#xp16-sketching-experiment https://dev.to/rafalpienkowski/do-developers-still-need-uml-ajh https://martinfowler.com/bliki/UmlMode.html https://www.amazon.com/Just-Enough-Software-Architecture-Risk-Driven/dp/0984618104/ref=sr_1_1?s=books&ie=UTF8&qid=1287576926&sr=1-1 http://www2.cs.uregina.ca/~bernatja/crowsfoot.html https://www.vertabelo.com/blog/chen-erd-notation/ https://www.omgsysml.org/what-is-sysml.htm http://www.sba.oakland.edu/faculty/mathieson/mis524/resources/readings/idef/idef.html#:~:text=The%20Integrated%20Computer%2DAided%20Manufacturing%20Definition%20(IDEF)%20language%20consists,data%22%20associated%20with%20the%20ICOMs. https://twitter.com/ThePracticalDev/status/932330636291043330 https://ict.eu/model-driven-engineering/ https://modeling-languages.com/low-code-platforms-new-buzzword/ https://www.mendix.com/blog/understand-no-code-vs-low-code-development-tools/
marcialwushu