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
1,876,045
Handling CORS Errors in ReactJS
Cross-Origin Resource Sharing (CORS) is a security feature implemented by browsers to prevent web...
0
2024-06-04T02:22:58
https://dev.to/vyan/handling-cors-errors-in-reactjs-42pl
react, webdev, javascript, beginners
Cross-Origin Resource Sharing (CORS) is a security feature implemented by browsers to prevent web pages from making requests to a different domain than the one that served the web page. While this security measure protects users from malicious websites, it can sometimes cause issues for developers working with APIs in a ReactJS application. This blog will explore what CORS is, why CORS errors occur, and how to handle these errors in your ReactJS projects. ## What is CORS? CORS stands for Cross-Origin Resource Sharing. It allows web applications to make requests to domains other than the one that served the web page. For instance, if your React application is running on `http://localhost:3000`, and it needs to fetch data from an API running on `http://api.example.com`, CORS must be configured correctly on the server to allow this cross-origin request. ## Why CORS Errors Occur CORS errors occur when the server does not include the correct headers in the response to allow the browser to make a request from a different origin. The browser will block the request, and you will see an error in the console similar to: ``` Access to fetch at 'http://api.example.com/data' from origin 'http://localhost:3000' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource. ``` ## How to Handle CORS Errors ### 1. Modify the Server to Allow CORS The most straightforward solution is to configure the server to allow cross-origin requests. Here’s how you can do it in some common server frameworks: #### Express.js (Node.js) ```javascript const express = require('express'); const cors = require('cors'); const app = express(); app.use(cors()); app.get('/data', (req, res) => { res.json({ message: 'Hello from the server!' }); }); app.listen(3001, () => { console.log('Server is running on port 3001'); }); ``` ### 2. Using a Proxy in Development When developing a React application, you can configure a proxy to redirect API calls to the target server. This avoids CORS issues during development. #### Create React App If you are using Create React App, you can set up a proxy in your `package.json` or `vite.config.js` file: ```json { "proxy": "http://api.example.com" } ``` ### 3. Using CORS Anywhere CORS Anywhere is a NodeJS proxy that adds CORS headers to the proxied request. It can be helpful for quick solutions during development. #### Usage ```javascript const fetchData = async () => { const response = await fetch('https://cors-anywhere.herokuapp.com/http://api.example.com/data'); const data = await response.json(); console.log(data); }; fetchData(); ``` ### 4. Manually Adding CORS Headers in the Browser As a last resort, and only for development or testing, you can disable CORS in your browser or use browser extensions that allow you to bypass CORS. However, this is not recommended for production due to security risks. ## Example: Handling CORS in a React App Here's a practical example using an Express.js server and a React frontend. ### Express.js Server Setup ```javascript // server.js const express = require('express'); const cors = require('cors'); const app = express(); app.use(cors()); app.get('/data', (req, res) => { res.json({ message: 'Hello from the server!' }); }); app.listen(3001, () => { console.log('Server is running on port 3001'); }); ``` ### React App Setup #### Fetch Data with Fetch API ```javascript // App.js import React, { useEffect, useState } from 'react'; function App() { const [data, setData] = useState(null); useEffect(() => { fetch('http://localhost:3001/data') .then(response => response.json()) .then(data => setData(data)) .catch(error => console.error('Error:', error)); }, []); return ( <div className="App"> <h1>{data ? data.message : 'Loading...'}</h1> </div> ); } export default App; ``` #### Using a Proxy in Create React App In your `package.json` file, add the proxy configuration: ```json { "proxy": "http://localhost:3001" } ``` With this setup, you can simply fetch the data without worrying about CORS during development: ```javascript // App.js useEffect(() => { fetch('/data') .then(response => response.json()) .then(data => setData(data)) .catch(error => console.error('Error:', error)); }, []); ``` ## Conclusion Handling CORS errors in ReactJS involves understanding why these errors occur and implementing appropriate solutions. Whether you modify the server to allow CORS, use a proxy during development, or employ other techniques, you can ensure smooth communication between your React application and external APIs. Remember to always follow best practices and consider security implications when configuring CORS in your applications.
vyan
1,876,030
Multiple Cloud Build Triggers in One Github Repo
So I recently wrote a post about setting up Cloud Build when using private Github repos and...
0
2024-06-04T02:20:32
https://dev.to/charlottetowell/multiple-cloud-build-triggers-in-one-github-repo-mgf
cloudbuild, github, googlecloud, devops
So I recently wrote [a post](https://dev.to/charlottetowell/cloud-build-setup-with-private-github-repos-and-submodules-k4g) about setting up Cloud Build when using private Github repos and submodules. Since creating this deployment pipeline between Github and Google Cloud Functions, it's been much easier to push updates as well as maintaining an organised coding environment. ![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/oeq9s1bcj1rb14ae4ip3.gif) ^^ me writing code and deploying it really fast A limitiation with the way I set up this pipeline is that it would deploy the entire github repo to the cloud function. Not terrible - encouragement to keep our code base clean and to ensure each repo is being used for its respective purpose. 😅 Or at least that's what I told myself to mark it as an issue for later. Only that later is now. ### But wait, it's easy! Turns out making a small adjustment so that not only can you deploy just the files you want, but that you can have multiple triggers within the same repo is super easy to do! Here's how - ## First - Folderise Did I just invent that word? Yes. First step is to reorganise your github repo hosting the source code for multiple cloud functions into folders for each function. Any common functions or files, keep outside or create a common folder. ![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/9z1fsdd8z9famapa1v8s.png) ## Next - Create Cloud Build Config Files For each subfolder containing source code to deploy, create a separate `cloudbuild.yaml` file in each folder. There are two things to do so the Cloud Build file knows what to deploy: **1. Copy Common Files** If you are using any common folders or files like me, add a step to copy any files/folders from the parent repo into the subfolder. ``` - name: 'gcr.io/google.com/cloudsdktool/cloud-sdk' entrypoint: 'bash' dir: 'subfolder1' args: - -c - | cp -r ../submodule ./ cp ../requirements.txt ./ ``` **2. Set directory** For your deployment step, set the directory to the relevant subfolder so that only files within will be included in the deployment using the `dir` tag. ``` - name: 'gcr.io/google.com/cloudsdktool/cloud-sdk' # Cloud SDK container dir: 'subfolder1' args: - gcloud - functions - deploy etc ``` <br> ## Finally - Create Cloud Build triggers Create a trigger for each subfolder set up within your repo. Key points are: * Choose 'Cloud Build configuration file (YAML or JSON)' as the configuration type and set to the correct file within subfolder * Add in 'subfolder/*' for included files so deployments are only triggered when something in the relevant subfolder is updated ![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/rhobbikp3am98h6snrod.png) ## And done! The end result is being able to use a single github repo to host multiple Cloud Functions with their respective Cloud Build triggers set up for easy deployment.
charlottetowell
1,876,043
Welcome to my Blog
Hey there! I'm excited to kick off this blog and share a bit about myself and my journey so far. My...
27,588
2024-06-04T02:17:32
https://www.jayganatra.com/blog/welcome
beginners, webdev, career, javascript
Hey there! I'm excited to kick off this blog and share a bit about myself and my journey so far. My name is Jay Ganatra, and I recently graduated with a Master’s in Computer Science from Syracuse University. It's been an incredible journey, and now, I’m on the lookout for full-time roles in the tech industry. In the meantime, I thought it would be a great idea to stay active and keep my skills sharp by regularly blogging about what I’ve been up to. Whether it's a new project I’m working on, a fascinating article I’ve read, or just some musings on the latest in tech, you’ll find it all here. I’m really passionate about web development, particularly using React, Next.js and AWS. I’m also currently diving into .NET Core, and I can’t wait to explore these topics more deeply. I hope this blog will be a place for learning, sharing, and maybe even a bit of fun along the way. Feel free to check out [my personal website](https://jayganatra.com) where you can find more about my work, projects, and contact information. This post is also available on my portfolio blog, so be sure to visit there for more updates and insights. Thanks for stopping by, and I look forward to sharing my journey with you! Stay tuned! Photo by <a href="https://unsplash.com/@helloimnik?utm_content=creditCopyText&utm_medium=referral&utm_source=unsplash">Nik</a> on <a href="https://unsplash.com/photos/right-arrow-sign-on-wall-MAgPyHRO0AA?utm_content=creditCopyText&utm_medium=referral&utm_source=unsplash">Unsplash</a>
ganatrajay2000
1,876,027
How to host a Minecraft server for Java on PC
You should totally host your own server, it can save you money and give you more control and options....
0
2024-06-04T02:16:47
https://dev.to/walkera1/how-to-host-a-minecraft-server-for-java-on-pc-4m5j
minecraft, download, papermc
You should totally host your own server, it can save you money and give you more control and options. You could totally buy a realm or pay for a server hosting service but that is like 8 dollars a month and you can only have two people on at the same time for that price. And if you have a nice computer you might as well put it too use. With your own server you can make all the rules. Have things be peaceful and you don't lose your stuff when you die, sure. Or you can make it super hard and have all the nightmare creatures you want. And my personal favorite is only having it open for a limited time. If it is only open on the weekends then it will make to time you do play more fun. - Why Should You Host a Minecraft Server? Hosting a minecraft server is super fun and has a huge payoff. You can have your own world, make your own rules, and do whatever you want. My favorite part is that I can turn on my server and walk away from it for any reason and everyone can still use it while I am away. Hosting your own server is a great way to save money, there are lots of server hosting services with varying quality and versatility, one thing in common is they all require you to pay every month to keep them active. If you already have a machine that can support the server it can basically run for free (minus the electricity and internet costs). You can also have any amount of players and mods on your server. Keep in mind that the more you want to add to the server, the more it will demand of your computer. So make sure your specs are good enough for what you want to do. - Risks of Hosting a Minecraft Server(?) Of course everything you do holds an inherent risk, hosting a Minecraft server is pretty risky though. The biggest risk to hosting your own server is a DDoS attack. In order for others to connect to your server they need your IP address (your computer's address). If the wrong person gets your IP address they can mess up your computer and ruin your server. DDos attack stands for distributed denial of service. When a hacker gets access to a lot of computers they can coordinate an attack. They carry out this attack by having a lot of computers send requests to your server at the same time. This can mean a computer that is only suppose to support 10 people of a server at once is now getting 1,000 requests for others to join. This can slow down your server and make your actual players unable to play. On a less depressing note, someone can also grief your world in game. For whatever reason, someone could totally kill you, steal your stuff, burn your house down. So just make a plan for Griefers ahead of time. There is also the risk of someone physically accessing your computer and inputting commands to give themselves stuff and lock you out. Now that all of the risks are covered, how do you actually host a Minecraft server? - How Do I Host a Minecraft Server? -What do You Need? I will go over some of the bare minimum requirements of hosting a minecraft server. If you have exactly these specifications then you will be able to run a server, mostly. With the bare minimum parts you will be able to support a small server with only a few people online at a time and maybe some lag at times. Now I'm sure your system is at least a little bit better than this and there are endless combinations of parts and specs for PCs out there. But a general rule is the more people and mods you want, the more resources your server will need. You should do your own research but below is the bare minimum requirements to hosting a minecraft server. _A PC Of Course I’m sure there is a way to force a Playstation or an xbox to hosting a minecraft server for you, but I don’t know how to do that. So I recommend getting a computer. You can do way more than just games on it (like host a server for any game) and it can play games really well. PCs are always going to be more expensive and more work than a console. But if you love games and technology I highly recommend getting a Computer (and try building your own). _A PC With: 1. A Fast CPU A CPU with enough cores and fast enough speed is needed for a server. The bare minimum would be something like a Core i5-4590 or an AMD equivalent. That CPU has four cores and a clock speed of 3.5 GHz. That CPU is 10 years old so it might be time for an upgrade soon. 2. Enough RAM (memory DDR3 and above) RAM, or random access memory, determines how much short term memory your computer has access too. The bare minimum is 8GB of RAM with the recommended 16GB of RAM. Without enough memory your server will have lag issues and might forget that you and your friends beat the ender dragon. 3. Enough Storage Space The bare minimum disk space requirement is 20GB. This number will go up depending on how many mods you want to have. And don’t forget to keep server backups just in case something goes wrong. - What You Need to Download 0. Download java for minecraft [Link to download Java ](https://thebreakdown.xyz/how-to-download-install-the-java-se-development-kit/) 1. To download java go to this link and go to the version that is right for you. Currently it is java 21 but this may change with new versions of minecraft and java coming out. Once you go there navigate to the computer system you are using and download the x64 installer 2. [Link to the paperMC download page](https://papermc.io/downloads/paper) 3. Bring that file to your desktop and open it 4. Download paper server and store it in a folder ![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/mdcs20plu96ncbrvi7is.png) 5. Rename the paper file to paper or paper.jar if your file started with a .jar at the end. 6. Make a text file and copy this text into it `@echo off java -Xmx8G -jar paper-1.20.4-393.jar nogui pause` The Xmx8G says that I want to allocate 8 Gigabytes of memory to the server (can be changed as you like). The paper-1.20.4-393.jar is the current version of minecraft we want to run. You will use the original name of your paper file you first downloaded here. And the pause will pause your computer if there is an issue with the server, so you can read what the issue is before closing the tab. ![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/477vm9nc7n8bpd8tim3v.png) Navigate to File then Save as save the type as all files and the name should be start.bat 7. Click on the start.bat file. It will fail. But it will generate some other useful files 8. Open the eula.txt file. Change eula=false to eula=true. That will make you agree to the eula. ![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/f1j869vqh4pktpjvi9by.png) 9. Click the start.bat again In conclusion hosting a Minecraft server does have a high cost of effort and money up front. Also some necessary risk you must take on. But once you get it up and running it can be a great addition to your Minecraft community and that of your friends. Sources: [DDoS attack explained](https://www.youtube.com/watch?v=ilhGh9CEIwM) - [what is needed to host a server](https://hostadvice.com/blog/web-hosting/minecraft/minecraft-server-hosting-requirements/) - [explaining how to install paperMC](https://youtu.be/3zRdrLXFS8o?si=JIQ7WPT1azN7FBs_) - [how to download JAVA](https://youtu.be/syW8hEPQRRg?si=VJPBkxSxOpWsnQue)
walkera1
1,508,381
Getting Started with Wasmer (WebAssembly Runtime) in Python
This tutorial will guide you through the process of getting started with Wasmer, a WebAssembly...
0
2024-06-04T02:16:24
https://dev.to/ajeetraina/getting-started-with-wasmer-webassembly-runtime-in-python-ch1
This tutorial will guide you through the process of getting started with Wasmer, a WebAssembly runtime for Python. Wasmer allows you to run WebAssembly modules securely and efficiently in your Python applications. ## Installation To begin, you need to install the wasmer Python package and the wasmer_compiler_cranelift compiler. Open your terminal and run the following command: ``` pip install wasmer wasmer_compiler_cranelift ``` ## Usage Let's dive into a simple example that demonstrates how to use Wasmer to execute a WebAssembly module in Python: ``` from wasmer import engine, Store, Module, Instance # Create a store to hold our WebAssembly module store = Store() # Compile the WebAssembly module module = Module(store, """ (module (type (func (param i32 i32) (result i32))) (func (export "sum") (type 0) (param i32) (param i32) (result i32) local.get 0 local.get 1 i32.add)) """) # Instantiate the compiled module instance = Instance(module) # Call the exported `sum` function with arguments result = instance.exports.sum(5, 37) # Print the result print(result) # Output: 42 ``` Save the above code in a file (e.g., simple.py) and run it using the following command: ``` python simple.py ``` The example demonstrates how to compile a WebAssembly module and execute a function from it using Wasmer. The sum function takes two integers as parameters and returns their sum. In this case, it adds 5 and 37, resulting in 42. ## Additional Resources To explore more examples and learn about advanced features, refer to the official documentation provided with the Wasmer package. The documentation is packed with detailed explanations and additional code samples to help you understand and utilize Wasmer effectively. You can also join the Wasmer Slack community and participate in the #python channel to connect with other developers, ask questions, and get support. Remember to check PyPI for the latest version of the Wasmer Python package and download statistics. ## Conclusion Congratulations! You have completed the tutorial and learned how to use the Wasmer runtime to execute WebAssembly modules in Python. You can now start exploring more complex WebAssembly applications and use cases. Happy coding with Wasmer and Python!
ajeetraina
1,566,476
Error message “cannot enable hyper-v service" on Windows 10
Docker is a popular tool for building, running, and shipping containerized applications. However,...
0
2024-06-04T02:16:07
https://collabnix.com/error-message-cannot-enable-hyper-v-service-on-windows-10/
[Docker](https://docker.com) is a popular tool for building, running, and shipping containerized applications. However, some users may encounter the error message "cannot enable hyper-v service" when trying to install Docker Desktop on Windows 10. This error message can be caused by a number of factors, but it can usually be fixed by following a few simple steps. ![Image1](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/aldz3ohekxjxqe9q8pp9.png) In this blog post, we will walk you through the steps on how to fix the "cannot enable hyper-v service" error. We will also provide some additional tips that may help you avoid this error in the future. ## Step 1: Enable virtualization in your BIOS The first step is to enable virtualization in your BIOS. This is usually done by pressing a specific key during startup, such as Esc, Delete, or F10. Once you're in the BIOS, look for a setting called "Virtualization" or "VT-x" and enable it. Note that Windows 10 Home users currently need to upgrade to Windows 10 Pro to allow virtualization. ## Step 2: Enable Hyper-V in Windows Features ![Image2](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/37qdbf2p3ty3w2bkytst.png) Once you have enabled virtualization in your BIOS, you need to enable Hyper-V in Windows Features. To do this, open the Control Panel and go to Programs and Features > Turn Windows features on or off. Check the box next to "Hyper-V" and click OK. ## Step 3: Restart your computer Once you have enabled Hyper-V in Windows Features, you need to restart your computer. This will allow the changes to take effect. ## Step 4: Run the command as an administrator The command ```bcdedit /set hypervisorlaunchtype auto``` will set the hypervisor to launch automatically at startup. This can be helpful if you are still getting the error message "cannot enable hyper-v service" after following the previous steps. To run this command, open a Command Prompt window as an administrator. Then, type the following command and press Enter: ``` bcdedit /set hypervisorlaunchtype auto ```` ## Step 5: Make sure that your drivers are up to date Outdated drivers can sometimes cause problems with Hyper-V. You can update your drivers by going to the website of your computer manufacturer and downloading the latest drivers for your motherboard and processor. ## Step 6: Disable any third-party security software Some third-party security software can interfere with Hyper-V. You can temporarily disable your security software to see if that resolves the issue. ## Step 7: Reinstall Docker Desktop If you have tried all of the previous steps and you are still getting the error message "cannot enable hyper-v service", you can try reinstalling Docker Desktop. To do this, uninstall Docker Desktop from your computer and then download and install the latest version from the Docker website. ## Additional tips If you are still having trouble, you can try posting your question on the [Docker forums](https://forums.docker.com) or asking for help on the [Docker community Slack](https://communityinviter.com/apps/dockercommunity/docker-community) channel. You can also try using a different virtualization platform, such as VirtualBox or VMware. If you are using a laptop, make sure that you are not running on battery power. Hyper-V may not be available when running on battery power. Conclusion The error message "cannot enable hyper-v service" can be a frustrating problem, but it is usually easy to fix. By following the steps in this blog post, you should be able to get Docker Desktop up and running on your Windows 10 computer without any problems.
ajeetraina
1,578,279
Install Redis on Windows in 2 Minutes
Redis, a powerful open-source in-memory data store, is widely used for various applications. While...
0
2024-06-04T02:15:41
https://dev.to/ajeetraina/install-redis-on-windows-in-2-minutes-5kc
Redis, a powerful open-source in-memory data store, is widely used for various applications. While Redis is often associated with Linux, you can also run it on Windows 10 using the Windows Subsystem for Linux (WSL2). This compatibility layer allows you to execute Linux commands natively on Windows, providing a seamless environment for running Redis. Here's a step-by-step guide on how to set up and run Redis on Windows 10 using WSL2: ## Step 1: Enable Windows Subsystem for Linux (WSL2) Open PowerShell as Administrator and run the following command to enable WSL2: ``` Enable-WindowsOptionalFeature -Online -FeatureName Microsoft-Windows-Subsystem-Linux ``` Reboot your system (this step is necessary only once). ## Step 2: Install Ubuntu from Microsoft Store Launch the Microsoft Store. Search for "Ubuntu" or your preferred Linux distribution. Download and install the latest version of Ubuntu. ## Step 3: Install and Configure Redis Launch the installed Ubuntu distribution. In the terminal, execute the following commands: ``` sudo apt-add-repository ppa:redislabs/redis sudo apt-get update sudo apt-get upgrade sudo apt-get install redis-server ``` Note: The sudo command might be required based on your system's user configuration. ## Step 4: Restart Redis Server After installation, restart the Redis server using: ``` sudo service redis-server restart ``` ## Step 5: Verify Redis Installation Test the Redis connectivity using the redis-cli command: ``` redis-cli ``` Inside the Redis CLI, execute the following commands: ``` 127.0.0.1:6379> set user:1 "Jane" 127.0.0.1:6379> get user:1 ``` You should see "Jane" as the output. ## Step 6: Stopping the Redis Server To stop the Redis server, use the following command: ``` sudo service redis-server stop ``` Running Redis on Windows 10 through WSL2 provides you with a Linux-like environment where you can harness the full power of Redis for your projects. Remember that while Redis databases by default have indexes from 0 to 15, you can adjust this configuration as needed in the redis.conf file. By following these steps, you can easily set up and run a Redis database on your Windows 10 machine using the Windows Subsystem for Linux. This enables you to leverage Redis for various applications and projects seamlessly.
ajeetraina
1,583,190
Sidecar vs Init Containers: Which One Should You Use?
Sidecar containers and init containers are both used in Kubernetes to extend the functionality of...
0
2024-06-04T02:15:21
https://dev.to/ajeetraina/sidecar-vs-init-containers-which-one-should-you-use-3h9
Sidecar containers and init containers are both used in Kubernetes to extend the functionality of pods. However, they have different purposes and should be used in different situations. Sidecar containers are run alongside the main container in a pod. They share the same network and storage resources, and they can communicate with each other using localhost. Sidecar containers are typically used to provide auxiliary services to the main container, such as logging, monitoring, or load balancing. Init containers run before the main container in a pod. They are used to perform tasks that need to be completed before the main container can start, such as downloading dependencies or setting up environment variables. Init containers do not share the same network and storage resources as the main container, and they cannot communicate with each other using localhost. ## When to use sidecar containers You should use sidecar containers when you need to provide auxiliary services to the main container. For example, you could use a sidecar container to provide logging, monitoring, or load balancing for your application. Sidecar containers are also a good choice when you need to isolate the main container from the rest of the pod. ## When to use init containers You should use init containers when you need to perform tasks that need to be completed before the main container can start. For example, you could use an init container to download dependencies or set up environment variables for your application. Init containers are also a good choice when you need to ensure that the main container starts successfully. ## Which one is better? The best choice for you will depend on your specific needs. If you need to provide auxiliary services to the main container, then you should use sidecar containers. If you need to perform tasks that need to be completed before the main container can start, then you should use init containers. Here is a table that summarizes the key differences between sidecar containers and init containers: ![Image1](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/9ypp6et37xbsthrb70eo.png) Here's an example YAML file that shows how to use sidecar containers and init containers: ``` apiVersion: v1 kind: Pod metadata: name: my-pod spec: containers: - name: main image: nginx - name: sidecar image: busybox command: ["sleep", "3600"] initContainers: - name: init image: busybox command: ["echo", "Hello from init container"] ``` This YAML file defines a pod with two containers: a main container and a sidecar container. The main container is responsible for running the nginx web server. The sidecar container is responsible for sleeping for 3600 seconds. The init container is responsible for printing the message "Hello from init container" to the console. The main container and the sidecar container share the same network and storage resources. However, the init container does not share the same network and storage resources as the main container. The init container runs before the main container. This means that the init container will start first and will print the message "Hello from init container" to the console before the main container starts. I hope this blog post helps you to understand the difference between sidecar containers and init containers. If you have any questions, please feel free to ask me.
ajeetraina
1,597,460
2 Minutes to JupyterLab Notebook on Docker Desktop
JupyterLab is a next-generation web-based user interface for Project Jupyter. Project Jupyter is a...
0
2024-06-04T02:14:13
https://dev.to/ajeetraina/2-minutes-to-jupyterlab-notebook-on-docker-desktop-1b2g
JupyterLab is a next-generation web-based user interface for Project Jupyter. Project Jupyter is a non-profit, open-source project, born out of the IPython Project in 2014 as it evolved to support interactive data science and scientific computing across all programming languages. Jupyter will always be 100% open-source software, free for all to use and released under the liberal terms of the modified BSD license. ## What is Jupyter? Jupyter is a large umbrella project that covers many different software offerings and tools, including the popular Jupyter Notebook and JupyterLab web-based notebook authoring and editing applications. The Jupyter project and its subprojects all center around providing tools (and standards) for interactive computing with computational notebooks. ## What is a Notebook? A notebook is a shareable document that combines computer code, plain language descriptions, data, rich visualizations like 3D models, charts, graphs and figures, and interactive controls. A notebook, along with an editor (like JupyterLab), provides a fast interactive environment for prototyping and explaining code, exploring and visualizing data, and sharing ideas with others. ## What is the difference between Jupyter and Jupyter Notebook? JupyterLab is a flexible, extensible interface for interactive computing. JupyterLabs enables you to work with documents and activities such as Jupyter notebooks, text editors, terminals, and custom components in a flexible, integrated, and extensible manner. Jupyter Notebook offers a simplified, lightweight notebook authoring experience. JupyterLab offers a feature-rich, tabbed multi-notebook editing environment with additional tools like a customizable interface layout and system console ## Notebooks Jupyter notebooks are documents that combine live runnable code with narrative text (Markdown), equations (LaTeX), images, interactive visualizations and other rich output: ## Architecture of Jupyter ![Image1](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/5ub2cqfm81kbzwwdk63d.png) ## The Jupyter Notebook format Jupyter Notebooks are structured data that represent your code, metadata, content, and outputs. When saved to disk, the notebook uses the extension .ipynb, and uses a JSON structure. For more information about the notebook format structure and specification. ## The Jupyter Notebook Interface Jupyter Notebook and its flexible interface extends the notebook beyond code to visualization, multimedia, collaboration, and more. In addition to running your code, it stores code and output, together with markdown notes, in an editable document called a notebook. When you save it, this is sent from your browser to the Jupyter server, which saves it on disk as a JSON file with a .ipynb extension. Jupyter notebooks (.ipynb files) are fully supported in JupyterLab. The notebook document format used in JupyterLab is the same as in the classic Jupyter Notebook. Your existing notebooks should open correctly in JupyterLab. Create a notebook by clicking the + button in the file browser and then selecting a kernel in the new Launcher tab. A new file is created with a default name. Rename a file by right-clicking on its name in the file browser and selecting “Rename” from the context menu. The user interface for notebooks in JupyterLab closely follows that of the classic Jupyter Notebook. The keyboard shortcuts of the classic Notebook continue to work (with command and edit mode). However, a number of new things are possible with notebooks in JupyterLab. Drag and drop cells to rearrange your notebook. You can drag cells between notebooks to quickly copy content. You can create multiple synchronized views of a single notebook. ![Image2](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/2wbei029y1shuimzagk2.png) The Jupyter server is a communication hub. The browser, notebook file on disk, and kernel cannot talk to each other directly. They communicate through the Jupyter server. The Jupyter server, not the kernel, is responsible for saving and loading notebooks, so you can edit notebooks even if you don’t have the kernel for that language—you just won’t be able to run code. The kernel doesn’t know anything about the notebook document: it just gets sent cells of code to execute when the user runs them ## Getting Started - Install Docker Desktop - Ensure that Docker Extensions is enabled - Search for Jupyter Notebook Extension - Install the Extension ![Image4](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/tej18xorwl20uqlucxjm.png) ## Click on "New" > "Notebook" ![Image6](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/p299jafmbrv2g69xxgjb.png) ## Select iPyKernel ![Image7](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/pyxdo6mn8v26ds5albqw.png) ## Visualising data in the Notebook Copy the code into the Launcher ``` from matplotlib import pyplot as plt import numpy as np # Generate 100 random data points along 3 dimensions x, y, scale = np.random.randn(3, 100) fig, ax = plt.subplots() # Map each onto a scatterplot we'll create with Matplotlib ax.scatter(x=x, y=y, c=scale, s=np.abs(scale)*500) ax.set(title="Some random data, created with JupyterLab!") plt.show() ``` Below is an example of a code cell. We'll visualize some simple data using two popular packages in Python. We'll use [NumPy](https://numpy.org/) to create some random data, and [Matplotlib](https://matplotlib.org) to visualize it. Note how the code and the results of running the code are bundled together. ![Image8](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/qwzks42qpte4m81cqlzu.png) Here's some random data generated with JupyterLab! ![Image11](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/bqst7iw750gnkyefillp.png)
ajeetraina
1,876,042
Mi Reloj Digital
Check out this Pen I made!
0
2024-06-04T02:12:18
https://dev.to/bricenojax2012/mi-reloj-digital-3pe7
codepen
Check out this Pen I made! {% codepen https://codepen.io/JESUS-ALEJANDRO-BRICE-O-RANGEL/pen/LYoyLpr %}
bricenojax2012
1,876,037
Embarking on My Coding Journey
Hey Dev.to community and readers, My name is William, and I am excited to share my first post on...
0
2024-06-04T01:42:09
https://dev.to/william_nguyen_88/embarking-on-my-coding-journey-2fl1
beginners, programming, productivity, learning
Hey Dev.to community and readers, My name is William, and I am excited to share my first post on here. I am writing this blog to document my journey to becoming a software engineer. **Background** I am a third-year Computer Science major at York University. This year has been particularly exciting because I finally got accepted into the co-op program. Joining this program is a significant milestone in my academic journey, and my primary goal is to immerse myself in learning various tools, languages, and technologies. By expanding my skill set and gaining practical experience, I aim to secure my first co-op work term and build a strong foundation for my future career in computer science. **Purpose** The purpose of this blog is to: • Share my learning experiences • Document my journey • Hold myself accountable • Connect with fellow students and aspiring software engineers **Why I chose to study computer science** Growing up and see all the technology help us in our day to day lives I knew it was something I want to pursue a career in. The idea of creating something with only line of code and readily accessible to anyone with a computer and an internet connection. In high school, I was first introduced to programming through a course on C#. Learning C# was a transformative experience for me. The structured syntax and logical flow of the language made it an ideal starting point. I had a lot of fun learning and experimenting with different projects. From creating simple applications to developing basic games, each new project was a learning opportunity that deepened my understanding and appreciation for coding. The sense of accomplishment I felt after successfully completing a project was incredibly rewarding and solidified my decision to pursue computer science further. **Current Progress** From the month of May I have coded everyday from learning to building out personal projects which I hope to share in my future posts. So, this month I plan to take it a step further share what I have learned and a reminder for the step I’ve taken for myself. **Goals for This Month** My goals for this month are: • Continue learning Python and SQL • Start developing a portfolio website • Add more project under my belt • Grind leetcode • Refining my use of power bi **Conclusion** Thank you for taking the time to read my first blog post. I’m exciting to start this next chapter in my life. Feel free to connect with me on [Linkedin](https://www.linkedin.com/in/william-nguyen-503683283/), I would love to hear your thoughts.
william_nguyen_88
1,875,957
Evolusi Game Casino Automaten Dari Mekanik Hingga Digital
Perkembangan Awal Game Casino Automaten Mekanik Sejarah Game Casino Automaten...
0
2024-06-03T23:34:36
https://dev.to/vereshatenzov43/evolusi-game-casino-automaten-dari-mekanik-hingga-digital-42ek
# **Perkembangan Awal Game Casino Automaten Mekanik** Sejarah Game Casino Automaten Mekanik Game casino automaten, atau mesin slot, memiliki sejarah yang panjang dan menarik. Perkembangan awal mesin slot dimulai pada akhir abad ke-19, ketika mesin-mesin sederhana pertama kali diperkenalkan. Mesin-mesin ini menggunakan [**daftar dewapoker**](https://194.26.213.65) mekanisme mekanik yang melibatkan gulungan fisik dengan simbol-simbol yang diputar secara manual oleh pemain. Pada saat itu, mesin slot awalnya ditempatkan di bar-bar dan salon-salon kecil, dan hadiahnya berupa rokok, minuman, atau permen. ![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/rumu9du5gmrp984avkp0.jpg) Inovasi Pertama dalam Mekanisme Mesin Slot Pada tahun 1895, seorang mekanik bernama Charles Fey menciptakan mesin slot yang dikenal sebagai "Liberty Bell". Mesin ini merupakan terobosan besar karena menggunakan tiga gulungan dengan simbol-simbol seperti sekop, hati, dan lonceng, serta mekanisme pembayaran otomatis. Liberty Bell menjadi populer di kalangan pemain dan membuka jalan bagi perkembangan lebih lanjut dalam industri mesin slot. Penggunaan Elektronik dalam Mesin Slot Pada tahun 1960-an, industri mesin slot mengalami perubahan signifikan dengan pengenalan teknologi elektronik. Mesin slot mulai menggunakan mikroprosesor dan komponen elektronik lainnya. Perubahan ini memungkinkan pengembangan fitur-fitur baru, seperti pembayaran otomatis yang lebih kompleks, dan memungkinkan pemain untuk bertaruh dengan koin yang lebih kecil denominasinya. Mesin slot elektronik ini menjadi semakin populer dan tersebar luas di berbagai kasino di seluruh dunia. ## **Revolusi Digital dalam Game Casino Automaten** Perkembangan Game Casino Automaten Berbasis Mikroprosesor Pada tahun 1970-an, mesin slot berbasis mikroprosesor semakin umum digunakan. Mikroprosesor memungkinkan mesin slot untuk memperluas fitur-fitur seperti penambahan gulungan, simbol-simbol tambahan, dan pembayaran yang lebih kompleks. Selain itu, mesin slot [**poker 88**](https://185.234.52.32) dapat diprogram ulang dengan mudah untuk mengubah peluang dan pembayaran, memberikan fleksibilitas kepada operator kasino. Pengenalan Mesin Slot Video Pada tahun 1990-an, industri mesin slot mengalami revolusi dengan pengenalan mesin slot video. Mesin slot video menggunakan layar monitor untuk menampilkan gulungan virtual dan simbol-simbol yang beragam. Ini memungkinkan pengembangan tema-tema yang kreatif dan menarik, serta fitur-fitur bonus yang lebih interaktif. Mesin slot video juga memungkinkan penggunaan efek suara dan animasi yang menarik, meningkatkan pengalaman bermain pemain. Perkembangan Game Casino Automaten Online Pada akhir tahun 1990-an, internet membawa perubahan besar dalam industri perjudian, termasuk game casino automaten. Kasino online mulai muncul, dan mesin slot online menjadi sangat populer di kalangan pemain. Mesin slot online menggabungkan elemen-elemen mesin slot tradisional dengan teknologi digital, memungkinkan pemain untuk memainkan game favorit mereka secara online dari kenyamanan rumah mereka. Selain itu, mesin slot online menawarkan berbagai tema, fitur bonus yang menarik, dan pembayaran yang menggiurkan. ### **Era Game Casino Automaten Mobile** Perkembangan Game Casino Automaten Mobile Dengan munculnya smartphone dan tablet, game casino automaten juga merambah ke platform mobile. Operator kasino meluncurkan aplikasi dan situs web yang dioptimalkan untuk perangkat mobile, memungkinkan pemain untuk menikmati mesin slot favorit mereka di mana saja dan kapan saja. Pengalaman bermain game casino automaten mobile menjadi semakin realistis dengan grafik yang menarik dan kontrol sentuh yang responsif. Interaksi Sosial dalamGame Casino Automaten Mobile Selain kemudahan aksesibilitas, game casino automaten mobile juga mengintegrasikan fitur interaksi sosial. Pemain dapat terhubung dengan teman-teman mereka melalui platform game atau media sosial, berbagi hasil permainan, atau bahkan bermain bersama dalam turnamen atau kompetisi. Ini menciptakan pengalaman bermain [**dominobet**](https://185.96.163.180) yang lebih sosial dan meningkatkan aspek komunitas dalam industri game casino automaten. Perkembangan Teknologi Virtual Reality dan Augmented Reality Perkembangan terbaru dalam industri game casino automaten adalah penggunaan teknologi virtual reality (VR) dan augmented reality (AR). Dengan VR, pemain dapat merasakan sensasi bermain di kasino fisik dengan lingkungan yang sepenuhnya imersif. Mereka dapat berinteraksi dengan mesin slot secara virtual dan merasakan atmosfer kasino yang autentik. Sementara itu, AR memungkinkan pemain untuk menggabungkan elemen-elemen game casino automaten dengan lingkungan sekitar mereka dalam kehidupan nyata, menciptakan pengalaman yang menggabungkan dunia virtual dan dunia nyata. #### **Inovasi dalam Algoritma Acak** Penggunaan Teknologi Terbaru Seiring dengan kemajuan teknologi, algoritma acak dalam game casino automaten terus mengalami inovasi. Penggunaan teknologi terbaru, seperti kecerdasan buatan (artificial intelligence/AI) dan pembelajaran mesin (machine learning), telah memungkinks operator kasino untuk mengembangkan algoritma acak yang lebih kompleks dan efisien. Teknologi ini dapat mempelajari pola permainan pemain dan menyediakan pengalaman yang lebih personal dan menarik. Personalisasi Pengalaman Bermain Dengan bantuan algoritma acak yang diperbarui, operator kasino dapat menghadirkan pengalaman bermain yang lebih personal bagi setiap pemain. Algoritma dapat mengidentifikasi preferensi dan gaya permainan individu, dan menghasilkan kombinasi simbol dan fitur bonus yang sesuai dengan preferensi tersebut. Ini meningkatkan kepuasan pemain dan membuat mereka merasa bahwa permainan disesuaikan dengan kebutuhan dan keinginan mereka. ![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/zdyz49ltxij9xkrcuva6.jpg) Pengembangan Fitur Bonus yang Inovatif Inovasi dalam algoritma acak juga memungkinkan pengembangan fitur bonus yang lebih kreatif dan menarik. Operator kasino [**domino88 asia**](https://67.205.148.8) dapat menggunakan algoritma acak untuk menentukan kapan dan bagaimana fitur bonus diaktifkan, serta jenis hadiah yang diberikan. Fitur bonus yang inovatif ini dapat mencakup putaran gratis, permainan bonus interaktif, atau bahkan fitur unik yang belum pernah ada sebelumnya. Hal ini membuat permainan lebih menarik dan menghibur bagi pemain. Kesimpulan Perkembangan game casino automaten dari mekanik hingga digital telah mengubah wajah industri perjudian. Mulai dari mesin slot mekanik sederhana hingga mesin slot digital yang canggih, game casino automaten terus berkembang dengan inovasi teknologi yang terus menerus. Dari penggunaan elektronik hingga revolusi digital, dan sekarang era game casino automaten mobile dengan interaksi sosial dan teknologi VR/AR, pemain dapat menikmati pengalaman bermain yang semakin realistis dan seru. Dengan terus berkembangnya teknologi, dapat dipastikan bahwa game casino automaten akan terus mengalami evolusi yang menarik di masa depan.
vereshatenzov43
1,876,039
Higher Order Components (HOC) React
const UpdatedComponent = (OriginalComponent) =&gt; { class NewComponent extends React.Component...
0
2024-06-04T01:35:28
https://dev.to/alamfatima1999/higher-order-components-hoc-react-hb2
```JS const UpdatedComponent = (OriginalComponent) => { class NewComponent extends React.Component { constructor(){ this.state = { ... } } render(){ return( <OriginalComponent props/> ); } } return NewComponent; }; class OGComponent extends React.Component{ ... //available via (this.props..) } export default UpdatedComponent(OGComponent); ```
alamfatima1999
1,876,036
Simplifying Dependency Management with Spring IoC
Introduction Imagine writing an application where you have to create and manage...
0
2024-06-04T01:30:58
https://springmasteryhub.com/2024/06/03/simplifying-dependency-management-with-spring-ioc/
java, spring, springboot, programming
## Introduction Imagine writing an application where you have to create and manage connections with your database system, use Kafka, set up a web server, configure a cache system, and handle JSON serialization and deserialization, among many other components. The amount of work required just to set up these dependencies before starting to develop features that bring real value can be overwhelming. Moreover, maintaining and setting these dependencies across all components of your code can be cumbersome. In the past, many developers dealt with this by employing various design patterns such as Factories, Builders, Proxies, Service Locators, reflection, and many other methods. While these helped, components often became tightly coupled and overly knowledgeable about their dependencies. ## Traditional Factory Method Here's an example of a factory method to deal with dependency creation without Spring: ```java javaCopy code public class PaymentProcessorFactory { public static PaymentProcessor createService(String type) { if (type.equalsIgnoreCase("paypal")) { return new PayPalPaymentProcessor(); } else if (type.equalsIgnoreCase("stripe")) { return new StripePaymentProcessor(); } else { throw new IllegalArgumentException("Invalid payment processor type: " + type); } } } // Usage PaymentProcessor paypalProcessor = PaymentProcessorFactory.createService("paypal"); PaymentProcessor stripeProcessor = PaymentProcessorFactory.createService("stripe"); ``` While this method works, it has limitations. Adding more methods requires changing the code, which makes it tightly coupled and hard to maintain. ## Introducing Spring IoC To address these issues, Spring introduced the Spring IoC (Inversion of Control) container, which is part of the Spring application context. ```java javaCopy code @Configuration public class PaymentProcessorConfig { @Bean @ConditionalOnProperty(prefix = "payment", name = "processor", havingValue = "stripe") public PaymentProcessor stripePaymentProcessor() { return new StripePaymentProcessor(); } @Bean @ConditionalOnProperty(prefix = "payment", name = "processor", havingValue = "paypal") public PaymentProcessor paypalPaymentProcessor() { return new PayPalPaymentProcessor(); } } ``` ## Understanding IoC Each component is a bean. A bean can be an infrastructure bean (like repositories for interacting with databases, Kafka templates for sending messages) or components created by developers to support business rules. IoC means Inversion of Control. Instead of a component calling a factory for a Kafka template to send messages, Spring handles this and delivers a fully functional bean to the component. The component no longer needs to know where the bean comes from or how it’s created. It follows the pattern of “don’t call me, we’ll call you.” The control of those dependencies is no longer handled by the component but managed by Spring IoC. This approach reduces coupling and makes it easier to connect application components, making the application more reusable. ## Spring IoC in Action Spring IoC reads your components and configurations (which can be in XML or Java annotations) and provides a ready-to-go application so the developer can start right away focusing on features that bring more value. It creates all beans at runtime when the application starts. Spring IoC uses your configurations to set up your beans through properties, providing flexibility over the beans. For example, when setting the payment processor to Stripe: ``` propertiesCopy code payment.processor=stripe ``` This can be easily changed to PayPal without touching a single line of your application component that calls this dependency. ## Simplified Dependency Usage Using these dependencies becomes straightforward: ```java javaCopy code @Component public class CheckoutService { @Autowired private PaymentProcessor paymentProcessor; public void processCheckout(PaymentDetails details) { paymentProcessor.processPayment(details); } } ``` ## Flexibility and Productivity Depending on the changes in your configuration properties (if it does not involve infrastructure changes like changing your database driver), you may not need to recompile and restart your application. Spring can reload the configurations while the application is running. ## Conclusion Spring IoC makes our lives easier, our applications less coupled and more reusable, and enhances productivity by allowing developers to focus on what matters most. If you like Spring make sure to follow me and stay tuned to learn more! Don’t miss out!
tiuwill
1,876,035
Web-based SQL editors
Web-based SQL editors are online tools that allow users to write, execute, and manage SQL queries...
0
2024-06-04T01:28:42
https://dev.to/concerate/web-based-sql-editors-1on4
Web-based SQL editors are online tools that allow users to write, execute, and manage SQL queries directly from their web browsers. These editors provide a user-friendly interface for interacting with databases and can be accessed from any device with an internet connection. Web-based SQL editors typically offer features such as syntax highlighting, auto-completion, query history, and result visualization. They support various database management systems (DBMS) like MySQL, PostgreSQL, SQL Server, Oracle, and more. Users can connect to their databases by providing the necessary connection details such as hostname, port number, username, and password. These editors make it convenient for developers, data analysts, and database administrators to work with databases without the need for installing any software or client-side tools. They can be used for tasks like querying and retrieving data, creating and modifying database structures, and performing database administration tasks. Some popular web-based SQL editors include phpMyAdmin, Adminer, SQL Fiddle, and DBeaver (which also has a web-based version). Additionally, many cloud-based database providers offer their own web-based SQL editors as part of their services. I recommend SQLynx as a reliable and user-friendly web-based SQL editor. SQLynx allows users to write and execute SQL queries directly from a web browser. It offers a clean and intuitive interface with features like syntax highlighting, auto-completion, query history, and result visualization. SQLynx supports various popular databases, including MySQL, PostgreSQL, SQLite, SQL Server, and Oracle. It also provides database connection management and allows users to save and organize their queries for future use. With SQLynx, you can easily connect to your databases, write complex SQL queries, and analyze the query results, all within a web-based environment. It is a great choice for developers, data analysts, and database administrators who prefer a web-based solution for their SQL editing needs. Download:http://www.sqlynx.com/en/#/home/probation/SQLynx
concerate
1,876,034
Common API explanations
Summary When it comes to programming, it must be inseparable from the API. For many...
0
2024-06-04T01:22:19
https://dev.to/fmzquant/common-api-explanations-3104
api, trading, cryptocurrency, fmzquant
## Summary When it comes to programming, it must be inseparable from the API. For many non-programmer people, what is the API? In this section we will use the easiest language to explain what is the API, and introduce the APIs commonly used in the FMZ Quant tools. ## What is API? If you google it, you will get the following results: API (Application Programming Interface) is a predefined function to provide applications and developers with the ability to access a set of routines based on a piece of software or hardware. Without having to access the source code, or understand the details of the internal working mechanism. In fact, in daily life, we have a lot of similar API scenarios, such as: you go to a restaurant to eat, just look at the menu to order, you do not need to know how to make it. The menu name in the menu is the specific API, and the menu is the API document. ## What is the API in the quantitative trading? For example, If you need to get the opening price of the current variety today, you don't need to know exactly how to get it. You only need to write "OPEN" in the code editor, just use it directly, "OPEN" is the API for the opening price in the M language. ## Common Mylanguage API Before we talk about the M language API, let's first look at the common code structure and what features it has. This will help you better understand the API. Please see the following example: ``` AA:=OPEN; //Get the opening price of the latest k line and assign the result to the variable AA BB:=MA(ClOSE,10); //Get the 10-cycle moving average of the latest K line and assign the result to the variable BB ``` The code shown above: - AA is a variable, and the variable is a element that can be changed, just like the algebra of our junior high school. If the opening price is assigned to AA, then AA is the opening price; if the highest price is assigned to AA, then AA is the highest price. AA is just a custom name, you can also define it as BB or something else. - ":=" is the meaning of the assignment, that is, the value on the right side of ":=" is given to the variable on the left. - "OPEN" and "MA" are API of the M language. Note that the OPEN in the first line is the API for obtaining the closing price. It can be used directly. The MA in the second line is the API for getting the moving average. It needs to be passed by 2 parameters, which means you need to tell the FMZ Quant trading tool, what kind of moving average you need: If you want to get the 50-period moving average calculated at the opening price, you can write: MA (OPEN, 50); please make sure there is a comma between the parameters. - The yellow "//" is a comment character, and the English behind it is the comment content. These are all viewed by programmers to indicate what the line of code means. The comment will not processed at all while the program starts to run. Note that before the comment character, each line of code must have an semicolon as the end of the line. With the basic code structure awareness, we will bring you some common grammar of M languages ​​below, and we will use them in the future. - OPEN - Get the opening price of the latest K line Example: AA:=OPEN; Get the opening price of the latest K line and assign the result to AA - HIGH - get the highest price of the latest K line Example: AA:=HIGH; Get the highest price of the latest K line and assign the result to AA - LOW - get the lowest price of the latest K line Example: AA:=LOW; Get the lowest price of the latest K line and assign the result to AA - CLOSE - Get the closing price of the latest K line. When the k line is not finished, get the latest price. Example: AA:=CLOSE; Get the closing price of the latest K line and assign the result to AA - VOL - Get the volume of the latest K line Example: AA:=VOL; Get the volume of the latest K line and assign the result to AA - REF(X,N) - refers to the value of X before N cycles. Example: REF(CLOSE,1); Get the opening price of the pervious K line - MA(X,N) - find the simple moving average of X in N cycles Example: MA(CLOSE, 10); //Get the 10-cycle moving average of the latest K-line - CROSSUP(A,B)——Represents that when A passes B from below, it returns 1 (Yes), otherwise it returns 0 (No) Example: CROSSUP (CLOSE, MA (C, 10)) // closing price up-cross the 10 cycle moving average price - CROSSDOWN(A,B)——Represents that when A passes B from above, it returns 1 (Yes), otherwise it returns 0 (No) Example: CROSSDOWN(CLOSE, MA(C,10)) // closing price down-cross the 10 cycle moving average price - BK - buying long open position Example: CLOSE>MA(CLOSE,5), BK; // Closing price is greater than 5 cycle moving average, open long position - SP - sell to close long position Example: CLOSE<MA(CLOSE,5), SP; // Closing price is less than 5 cycle moving average, sell to close long position - SK - sell short open position Example: CLOSE<MA(CLOSE,5),SK; // Closing price is less than 5 cycle moving average, selling short open position - BP - buy to cover to close short position Example: CLOSE>MA(CLOSE,5), BP; // Closing price is greater than 5 cycle moving average, close short position - BPK - close short position and open long positions (reverse open position) Example: CLOSE>MA(CLOSE,5), BPK; // when the closing price is greater than the 5-period moving average, close the short position and open the long position. - SPK - close long position and open short position (reverse open position) Example: CLOSE<MA(CLOSE,5), SPK; // when the closing price is less than the 5-period moving average, close the long position and open the short position. - CLOSEOUT - close all positions, it is recommended to use in the addition and subtraction position operation Example: CLOSEOUT; close all positions that current holding. ## Commonly used JavaScript language API Before explaining the JavaScript language API, let's take a look at what the common code structure is and what features it has. This will help you better understand the API. Please see the following example: ``` var aa = exchange.GetRecords(); // get the K-line data var bb = exchange.SetContractType("BTC_USDT") // set the trading pair to Bitcoin to USDT ``` The code shown above: - Creating variables in the JavaScript language is often referred to as a "declaration" variable. we use the "var" keyword to declare the variable, the variable name is : "aa". - In the JavaScript language, assign an equal sign, that is, give the value on the right side of "=" to the variable on the left. - The code "exchange" is the exchange object. The exchange here refers to the exchange you set up on platform page. This is a fixed format, that is, you must specify the exchange object when you call the API of the JavaScript language. - The green code is the API of the JavaScript language. When we call it, it is actually calling the function in the exchange object. Note that the point behind the code is also a fixed format. The function here is the same meaning of the function we learned in middle school. If the function does not need to specify a parameter, it is represented by an empty parenthesis; if the function must pass in a parameter, the parameter is written in parentheses. After using the case to understand the basic structure of the code, let's take a look at a few JavaScript language APIs that you will use in the future. - SetContractType ( "variety code" ) - set the trading pair, which is the trading variety that you want to trade Example: exchange.SetContractType("BTC_USDT"); //Set the trading pair to Bitcoin to USDT - GetTicker - Get Tick data Example: exchange.GetTicker(); //Get Tick data - GetRecords - get K line data Example: exchange.GetRecords(); //Get K line data - Buy - buy long Example: exchange.Buy(5000, 1); //Buy one unit at 5,000 - Sell ​​- sell short Example: exchange.Sell (5000, 1); // Sell one unit at 5,000 - GetAccount - get account information Example: exchange.GetAccount(); //Get account information - GetPosition - Get position information Example: exchange.GetPosition(); //Get position information - SetDirection - set to do long or short order type example: exchange.SetDirection("buy"); //Set the order type to open long positions exchange.SetDirection("closebuy"); //Set the order type to sell to close long positions exchange.SetDirection("sell"); //Set the order type to open short positions exchange.SetDirection("closesell"); //Set the order type to buy to cover to close short position - Log - output a message in the log Example: Log( "hello, World" ); //output " hello world " in the log - Sleep - pause the program for a while Example: Sleep (1000); / / make the program pause for 1 second (1000 milliseconds equals 1 second) Some people may have doubts, so many APIs above, how can i memorize it all? actually, you don't need to remember any one of them, FMZ Quant official website has a detailed API documentation. Just like looking up a dictionary, anytime you use it, you only need check it through our documentation. Don't be scared by the coding part. What we want is to organize our own strategies through these languages. Please remember that technology is never a threshold for quantitative trading. The excellent trading strategy is the most important of all. ## To sum up The above is the most commonly used API in quantitative trading, basically including: obtaining data, calculating data, placing orders. These steps should be enough to deal with a simple quantitative trading strategy. futhermore, if you want to write a more complex strategy, you need go to the FMZ Quant website to get it. ## After-school exercises 1. try to write a M language 5 cycle average line up-cross 10 cycle moving average line sentence. 2. try to use the JavaScript language "GetAccount" to get your account information, and use "Log" to print it to the log. ## Next section notice Programming is like assembling LEGO bricks. The API is like the various parts of a building block. The programming process is to make each Lego part a complete toy. In the next section, I will lead you to assemble a complete quantitative trading strategy using the M language API. From: https://blog.mathquant.com/2019/04/16/2-3-common-api-explanations.html
fmzquant
1,876,029
Pact contract testing tutorial using Ruby
This post is intended to give an introduction on how to use Consumer-Driven Contract tests using Pact...
0
2024-06-04T01:07:57
https://dev.to/itamar/pact-contract-testing-tutorial-using-ruby-35d5
pact, ruby, contracttesting
This post is intended to give an introduction on how to use Consumer-Driven Contract tests using Pact and Ruby, as an example. I hope you find this useful, or else please let me know how to improve it. Thanks for reading! [Blog post is here](https://www.in-context.com/pact/ruby/contract%20testing/2024/05/31/pact-ruby.html)
itamar
1,876,022
We're software developers, but are we?
TL;DR As software developers, we must have flexible minds to learn whatever we need to solve the...
0
2024-06-04T01:02:14
https://dev.to/hectorzr/were-software-developers-but-are-we-bd6
softwaredevelopment, frontend, backend, programming
**TL;DR** As software developers, we must have flexible minds to learn whatever we need to solve the problems we face. It’s awesome to be specialized. However, it’s better to go beyond and learn anything else we can to improve our specialty. ### **Disclaimer** This is only my personal opinion, based on my life experience and the folks I’ve met. It’s okay if you don’t agree; in that case, I invite you to comment with your thoughts. I’d love reading them. # Introduction Over the last 6 years of my life, I’ve been interacting with a multitude of software developers. Backend, Frontend, DevOps, FullStack, etc. Even though everyone has a specialty, at the end of the day, we are all just solving **problems**. # Why do I say this? It's simple: every day, we solve some problem. It doesn’t matter if it is a bug, a text, or an endpoint; you get the point, right? This means, for me, that we cannot have square minds and limit ourselves to do a single thing. After all, we all have different points of view on how to solve the same problem. At the beginning of my professional career, I started as a FullStack developer. I worked with Laravel and ReactJS. It was an awesome job; I could learn a lot there as a junior developer. It was a small company, so many things or roles had to be done by the same person across the team. Of course, it was exhausting, but I was thinking of the knowledge I was getting instead of the money I had as income. # Time for specialization The beauty and sweet specialization. After I quit that job, I focused on learning and improved my weakness: frontend development. I really sucked at JavaScript. Thus, I focused on improving it. I had landed my next job as a frontend developer specializing in React. The journey was not easy for different personal reasons. However, I got the job. One month later, I realized how much I had to learn about UX and UI to expand my knowledge and develop very accurate interfaces. Again, it wasn’t an easy task, but I put in all the effort I could to deliver the best quality. # Time for self-realization After a decent time, I moved to a new company. I was hired again as a frontend developer using ReactJS (long-live React 😂). Even though I had landed as a specialized developer in React, I faced many challenges that I never said no to (I like challenges a lot). I had to manipulate server instances in the cloud. Setting up Docker containers for a FTP server. I had to work on the backend side, developing the API for the frontend app I was helping to build. This made me realize how much I love software development, not just the fact that I work on the backend or frontend, but solving problems. Also, I learned I couldn’t be married to a single technology. I had to transform my mind to be abstract to the technology. Nowadays, I don’t mind which language, tool, framework, or library I have to learn to solve the problem. As long as it solves the problem. # Conclusion It’s been a fun journey so far. I don’t know what the future holds for me professionally. However, I hope I can keep my mind sharp and flexible enough to continue my learning path. I will continue working with React. However, my mind is open to any challenge I can face; after all, I’m just a problem solver. Cover Photo by [Luca Bravo](https://unsplash.com/@lucabravo?utm_content=creditCopyText&utm_medium=referral&utm_source=unsplash) on [Unsplash](https://unsplash.com/photos/turned-on-gray-laptop-computer-XJXWbfSo2f0?utm_content=creditCopyText&utm_medium=referral&utm_source=unsplash)
hectorzr
1,876,026
Bug: Docker-compose up?
ERROR I've been using a bash script to do docker operations in past by using...
27,587
2024-06-04T00:56:05
https://dev.to/fabiobazurtobla/bug-docker-compose-up-1coj
docker, dockercompose, bugfix
### ERROR I've been using a bash script to do docker operations in past by using `docker-compose`. So one day, I started to receive this error: `**ERROR: for my_docker_container_1 'ContainerConfig'**` ### CAUSE The statement `docker-compose` is not working anymore for recent versions of Docker Compose. This error is very common when you have updated to the latest version of Docker Compose ( I'm `2.27.0`). Docker Compose syntax changed. `docker-compose up -d my_docker_container` ### SOLUTION In order to start/stop containers you will need to remove "-" and run command like this. `docker compose up -d my_docker_container`
fabiobazurtobla
1,876,025
ReactJS and JavaScript, in Frontend Development
Introduction Frontend development is constantly evolving, bringing new technologies that...
0
2024-06-04T00:54:49
https://dev.to/buildwebcrumbs/reactjs-and-javascript-in-frontend-development-2eek
react, javascript, webdev, frontend
#### Introduction Frontend development is constantly evolving, bringing new technologies that make building web applications more efficient and enjoyable. ReactJS and JavaScript are two essential tools in this space. Let's explore some interesting aspects with code examples. ### ReactJS: Revolutionizing UI Development #### Component-Based Architecture ReactJS uses a component-based architecture that simplifies creating user interfaces. Components are reusable blocks of code that can be combined to build complex UIs. ```js // Example of a React component function Greeting(props) { return <h1>Hello, {props.name}!</h1>; } function App() { return ( <div> <Greeting name="Maria" /> <Greeting name="John" /> </div> ); } ``` #### Hooks Hooks are functions that allow using state and other React features in functional components. ```js import React, { useState } from 'react'; function Counter() { const [count, setCount] = useState(0); return ( <div> <p>You clicked {count} times</p> <button onClick={() => setCount(count + 1)}> Click me </button> </div> ); } ``` ### JavaScript: The Backbone of Web Development #### Asynchronous Functions JavaScript facilitates asynchronous programming with `async` and `await`, making it easier to handle asynchronous operations. ```js // Example of an asynchronous function async function fetchData() { try { let response = await fetch('https://api.example.com/data'); let data = await response.json(); console.log(data); } catch (error) { console.error('Error fetching data:', error); } } fetchData(); ``` #### Destructuring Destructuring simplifies extracting data from arrays and objects. ```js // Example of destructuring const person = { name: 'Ana', age: 25 }; const { name, age } = person; console.log(name); // Ana console.log(age); // 25 ``` ### Frontend Development: Bridging Design and Functionality #### Responsive Design Responsive design ensures that applications work well on various devices and screen sizes. ```css /* Example of responsive CSS */ .container { width: 100%; max-width: 1200px; margin: 0 auto; } @media (max-width: 768px) { .container { padding: 0 20px; } } ``` #### Progressive Web Apps (PWAs) PWAs offer a native app-like experience with features like offline work and push notifications. ```js // Basic example of service worker registration if ('serviceWorker' in navigator) { navigator.serviceWorker.register('/service-worker.js') .then(reg => console.log('Service Worker registered:', reg)) .catch(err => console.error('Service Worker registration error:', err)); } ``` ### Conclusion ReactJS, JavaScript, and frontend development are full of interesting features that make creating modern and efficient web applications easier. Adopting these technologies allows developers to build innovative solutions that meet the needs of today's users. **Thank you, Please Follow:** [Webcrumbs](https://webcrumbs.org) ![Webcrumbs](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/68jt1eo11phux344foqf.png)
m4rcxs
1,876,018
Top 4 Reasons to Hire a Software Development Consultant
It's the 21st century. Internet businesses are making a lot of money. It's only natural that so many...
0
2024-06-04T00:44:47
https://developerpartners.com/blog/f/top-4-reasons-to-hire-a-software-development-consultant
It's the 21st century. Internet businesses are making a lot of money. It's only natural that so many people have so many great ideas for software products. Unfortunately, very few of them actually pursue their dreams, build software solutions, and become successful. The most common reason why so many don't build their dream tech startups is the lack of knowledge. They simply don't know where to start. They have good ideas, but they don't know how to build solutions based on those ideas. You might have expected to read that money was the biggest reason why most people don't start technology startups in the previous paragraph. The truth is that some of those entrepreneurs have some technology backgrounds, so they manage to get started on their projects, but they run out of resources pretty quickly because they chose a wrong technology and team for that. Even startups that get large investments from venture capitalists often run out of cash because of wasting all their resources on all the wrong things. That is why consulting professionals before you start spending your resources is so important. ## 1. Pick the Right Technologies ![Pick the right technologies](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/jui11zn6n8pdtyto0oos.jpg) I'm often asked what programming language we use in our projects. Those who know what programming is all about know that the answer is not simple. It's not like we use just one programming language for everything. Unfortunately, building software is not that simple. The database requires SQL. The back-end requires a back-end programming language such as Java, Python, or C#. The front-end requires HTML, CSS, and JavaScript. So the answer of what programming languages we use in our projects is that we use SQL, C#, HTML, CSS, and JavaScript for most projects, but there are some projects where we use even more languages. That doesn't even count the software development frameworks that we use along with those programming languages. As you can see, the technology choices are a lot, so a professional can advise you what technology stack you have to chose for your project. You don't actually have to know anything about Python or JavaScript to build software with a help of the right people. In fact, depending on your requirements, the chances are you may not even need any software developers for your project. For example, if all you want is an online store, you can just use some of the existing solutions for creating online stores such as Shopify or BigCommerce. Many small business owners spend a lot of money on building software from scratch without even realizing they could sign up for an existing SaaS service for something like $20 a month. I met quite a few small business owners who spent thousands of dollars on the design of their company website without knowing that they could just sign up for a website building service for $20 a month and pay only a couple hundred dollars to buy a premium theme for their website. Consulting a professional can help you decide if you need to hire a team of software developers or just sign up for a CMS or e-commerce service. Even if you have some technical background and based on your research, you think that you need certain tools for your project, consulting a professional software development firm may still be a good idea. That way you can at least confirm if you picked the right technology tools. ## 2. Hire the Right Team ![Hire the Right Team](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/u3i1rc4g9jr8hv2rmzym.jpg) When you know what technologies you will need for your project, you will have to find people who can build a solution for you with those technologies. Let's assume you decided to go with Node.js and MySQL for the back-end and React for the front-end combination. Now, you have to make a few important decisions about how your team will be structured: - Should you hire a few back-end and a few front-end developers? Should you hire full-stack developers instead of different people for the front and back ends? - What should be the level of expertise of all developers working on your project? Should all developers be seniors, or should your team be a mix of people with different experience levels? - Do you need any lead developers? If so, how many would you need? Can one lead developer lead the whole dev team? - Do you need a software architect? Who will come up with the software architecture? Hopefully, it's not going to be you. - Do you need a QA team? You may need a QA team to test your application, but at what point should you spend money on this? - Do you need any DevOps engineers? You will have to decide if you need a dedicated DevOps engineer in the team. Maybe one of the senior developers can handle this part of the problem for some time, but you may have to consider hiring a DevOps engineer in the future. Once you figure out what type of professionals you will need, another question would be how many people you should hire. Depending on your project complexity and requirements, it's possible that you may need just one developer to start with, but if you are not aware of that, you may end up hiring multiple people hoping that more developers will result in better performance. You may be wrong in doing that because it's not about quantity, it's about quality. One developer who is very good at what they do may outperform a hundred average developers. In software development, the difference in the performance of top and average professionals is that big. If you can find the best candidates for each role within your budget, then you can save money because you will hire less people and end up with a high quality work. That, of course, doesn't mean that you have to hire only senior level people. If someone is a senior at some profession that doesn't mean he or she can do well a junior's job. Your team has to be a healthy mix of different levels. You can think of it this way; Michelangelo's David couldn't be created without Michelangelo. A hundred average artists couldn't create David. However, a hundred Michelangelo's are not needed either because they would probably not work well together. ## 3. Pay the Right Compensation ![Pay the Right Compensation](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/c74dpfvjaso6mgs5v4f9.jpg) When you know what technologies you need and who you should hire for that job, you should find out how much you should pay the people you hire. It's not uncommon to overpay or underpay technical experts. If you overpay them, you obviously lose money. If you underpay them, you will not have their full focus, so if a better deal comes along while working on your project, they may prefer those clients over you. How much should you pay? If you hire 5 senior developers and pay $10,000 a month to each, your monthly budget should be at least $50,000 and yearly budget should be $600,000 for the salary of the developers only. That is the reason why I said that even if you get funding from investors, you may run out of money if you are not careful. Just paying a lot of money doesn't mean you will get great results. You might be asking yourself now whether you should hire an overseas development team. For instance, you may be able to hire a development team in some parts of the world and pay just $500 a month to each developer. However, that doesn't necessarily mean that you will save money. First, you have to understand the local employment rules and regulations to not get into trouble hiring people overseas. Second, you have to be able to screen the potential candidates from a foreign place that you don't know much about, so if you end up hiring people with poor skills, they may damage your software architecture so badly that fixing it may cost you a lot more. It's not so much about the amount you pay, it's about the quality of work you get for the money you spend. It means that you should not aim to pay little or generous compensations to the people you hire. It means that you have to pay the correct amount that doesn't exceed your project budget for the skills that those people have. ## 4. Know the Cost ![Know the Cost](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/n4ongx84k9jigskrse2h.jpg) If you figured out what type of professionals you have to hire and how much you have to pay them, it should be easy to estimate how much the project will cost. The project cost will roughly be the salary of the people involved plus the licenses for any 3rd party software or libraries you will need, then the the sum of those two multiplied by the time it will take to complete the project: ``` Project Cost ≈ (Salaries + 3rd Party Software Licenses) * Time ``` The salaries are going to be the biggest expense that is why we talked so much about them. The 3rd party software licenses are probably going to be a fraction of the cost of salaries. As you can see, your main expense is going to be the salaries, so the equation can be simplified to the cost of salaries multiplied by the time it takes to complete the project: ``` Project Cost ≈ Salaries * Time ``` How long it will take to complete the project? If your app is successful, it will never be fully "completed" because there will be a constant need for improvements as your business grows. If you were hoping to pay an X amount to build software and never have to spend a dime on it again, you might be disappointed, but that is the reality. Software is like a living organism, it constantly evolves and changes. If you want to be competitive and keep growing your business, you may never end spending on the maintenance and enhancements of your software. You can't estimate when the development truly ends because it often never ends, but you can estimate when will a Minimum Viable Product (MVP) be ready. An MVP is something that has the bare minimum of what your clients will need. It's not perfect, but it can be enough to get some clients or at least some early adopters of the product. You should not aim at building something perfect that has a stunning design and every possible feature that you can imagine. That will drain all your resources. You should create an MVP, get some clients, thus drive some revenue into your business, and continue the development to stay competitive. Once again, since we stated that successful projects usually don't end, let's rewrite our formula to better reflect the reality: ``` Minimum Viable Product ≈ Salaries * Time ``` There have been cases where some companies were able to sell their software products without even having MVP's. I'm not even sure if they started the development at all, but they were able to find some clients because they were good at selling and presenting their ideas to potential clients. Startups like them succeed because they get a stream of revenue while spending time and resources on building their products and growing their businesses. You may not be so good at sales to be able to find clients without even starting the development, but you may find some clients if you have an MVP and are willing to offer some discounts. ## Conclusion Consulting a software development firm before starting a software project doesn't cost much, but it can prevent some hefty mistakes that cost a lot. You can book a consultation session for an hour or two and learn a lot of about what to expect and how to deal with different issues. A professional software development firm can help you with the following: 1. **Picking the right technologies.** 2. **Hiring the right team.** 3. **Paying the right compensation.** 4. **Knowing the cost.** Our team at Developer Partners can help you with the questions mentioned above. If you would like to schedule a consultation with us, please use our contact form at the following page: [Contact Developer Partners for software development consultation.](https://developerpartners.com/contact-us) We covered a lot in this article, but there is still a lot to talk about on this topic. If you found it useful and want to see more articles like this, please consider subscribing to our newsletter to be notified when we publish a new post. Author: Hayk Shirinyan LinkedIn: https://www.linkedin.com/in/hayk-shirinyan-92980b59/
developerpartners
1,876,023
Environmental Impacts of Oilfield Drilling
Protecting the Earth Understanding the Environmental Impacts of Oilfield Drilling Introduction It is...
0
2024-06-04T00:39:37
https://dev.to/dhssdnd_cijsje_f0472fe382/environmental-impacts-of-oilfield-drilling-225f
oilfield
Protecting the Earth Understanding the Environmental Impacts of Oilfield Drilling Introduction It is important to understand the impact that production and drilling can have on the environment as we continue to rely on oil for energy. Oilfield drilling can have effects that are negative air and water quality, wildlife, and habitats that are natural. However, with innovation and consideration oilfield careful can also have advantages and be done safely. We are going to explore the environmental impacts of oilfield drilling and ways to mitigate results that are negative. Advantages of Oilfield Drilling Electric Control Valves Oilfield drilling provides us with the energy we need to power our homes and businesses. It might create job opportunities and increase the economy. When done safely and responsibly, oilfield drilling can provide these benefits while minimizing impacts that are negative are environmental. Innovation in Oilfield Drilling As concerns arise about the environmental impacts of oilfield drilling, companies are taking steps to innovate and reduce their impact. This Valves And Instruments includes using technologies such as horizontal drilling and fracturing hydraulic which allow for more efficient and precise drilling with less damage environmental. Companies are also investing in renewable energy sources and ways that are exploring production make more sustainable. Safety in Oilfield Drilling Safety is a priority top the Industrial Instruments oilfield drilling industry. Companies follow strict regulations and guidelines to ensure that workers and the environment are protected. These safety measures include proper training, equipment maintenance, and emergency response planning. Companies are also steps that are taking minimize the risks of spills and leaks by using monitoring advanced and better well design. Source: https://www.cngongboshi.com/Industrial-instruments
dhssdnd_cijsje_f0472fe382
1,876,020
How to Instantly Track Message Broker Job Status Within the Same Request With NestJS and RabbitMQ
Suppose you have a distributed job system. When you create a job to be processed by workers, you want...
0
2024-06-04T00:33:22
https://dev.to/luscasleo/how-to-instantly-track-message-broker-job-status-within-the-same-request-with-nestjs-and-rabbitmq-1g60
nestjs, rabbitmq, node, eventdriven
Suppose you have a distributed job system. When you create a job to be processed by workers, you want to return the result status if the job completes within an interval of 500 milliseconds or up to 10 seconds. This can be a challenging task. However, NestJS Microservices offer an easy way to achieve this. Let's say you have a basic NestJS Microservice setup with an API and a RabbitMQ consumer. The project setup configuration would look like this: ## Setting Up NestJS Microservices ```ts // main.ts import { NestFactory } from '@nestjs/core'; import { AppModule } from './app.module'; import { MicroserviceOptions, Transport } from '@nestjs/microservices'; async function bootstrapHttp() { const app = await NestFactory.create(AppModule); await app.listen(3000); } async function bootstrapConsumer() { const app = await NestFactory.createMicroservice<MicroserviceOptions>( AppModule, { transport: Transport.RMQ, options: { urls: ['amqp://localhost:5672'], queue: 'cats_queue', queueOptions: { durable: false, }, }, }, ); await app.listen(); } if (require.main === module) { if (process.env.MODE === 'consumer') { bootstrapConsumer(); } else if (process.env.MODE === 'http') { bootstrapHttp(); } else { throw new Error('Invalid mode'); } } ``` ```ts // app.module.ts import { Module } from '@nestjs/common'; import { AppController } from './app.controller'; import { AppService } from './app.service'; import { ClientsModule, Transport } from '@nestjs/microservices'; @Module({ imports: [ ClientsModule.register([ { name: 'MATH_SERVICE', transport: Transport.RMQ, options: { urls: ['amqp://localhost:5672'], queue: 'cats_queue', noAck: true, queueOptions: { durable: false, }, }, }, ]), ], controllers: [AppController], providers: [AppService], }) export class AppModule {} ``` ## Implementing the Controller Initially, the controller might look like this: ```ts // app.controller.ts import { Controller, Get, Inject } from '@nestjs/common'; import { ClientProxy, MessagePattern, Payload } from '@nestjs/microservices'; type EnqueuedJob = { status: 'enqueued'; jobId: string; }; type ProcessedJob = { status: 'processed'; jobId: string; }; type JobState = EnqueuedJob | ProcessedJob; const sleep = async (ms: number) => { return new Promise((resolve) => { setTimeout(resolve, ms); }); }; const generateRandomId = (): string => { return Math.random().toString(36).substring(7); }; @Controller() export class AppController { constructor( @Inject('JOB_QUEUE_SERVICE') private readonly client: ClientProxy, ) {} @Get() createJob(): JobState { const jobId = generateRandomId(); this.client.send('process_job', { jobId }).subscribe(); return { status: 'enqueued', jobId, }; } @Get('state/:jobId') getJobState(jobId: string): JobState { return { status: 'processed', jobId, }; } @MessagePattern('process_job') async getNotifications(@Payload() data: { jobId: string }) { console.log('Processing job', data.jobId); await sleep(10000); console.log('Processed job', data.jobId); } } ``` ## Running the Project To run the project in consumer mode: ```bash MODE=consumer yarn start ``` To run the project in HTTP mode: ```bash MODE=http yarn start ``` Now you can create a job by sending a GET request to the / endpoint. ``` curl http://localhost:3000 ``` With the subscribe function, the `producer` service awaits the consumer to process the message and reply to the messages auto generated id, not the one we created early. Look: ![RabbitMQ Queue Message Props](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/czkxug788u49voywtbdv.png) The message at rabbitmq has a property called `reply_to`. This property is set on `runtime` at the producer, waiting for a `signal`. NestJS then manages to use this unique string to send a message (the consumer functions's serialized return data) back to the producer, using the `callback queue` which is named by the `reply_to` property and the `correlation_id`. The return message is then sent to the producer, and the producer can then handle the return message. ## Modifying the Code for Synchronous Job Status Tracking The createJob method is responsible for creating a job ID and sending it to the queue. The client then needs to poll the /state/<jobId> endpoint to check if the job is completed. However, using NestJS Microservices' ClientProxy interface, which is compatible with RxJS, we can handle callbacks more effectively. Update the message sending code as follows: ```ts this.client .send('process_job', { jobId }) .subscribe({ next(value) { console.log('Processed. Result:', value); }, }); ``` ## Tracking Job Status Within the Same Request To track the job status within the same request, set a timeout. If the job is not completed within the timeout, return a status of enqueued. If the job is completed within the timeout, return a status of processed. Update the createJob method: ```ts import { Subject, lastValueFrom } from 'rxjs'; //... @Get() createJob() { const jobId = generateRandomId(); const maxWaitTimeMs = 1000; const jobStateSubject = new Subject<JobState>(); // Set a timeout to return 'enqueued' if the job is not completed within the timeout const timeoutId = setTimeout(() => { jobStateSubject.next({ status: 'enqueued', jobId, }); jobStateSubject.complete(); }, maxWaitTimeMs); this.client .send('process_job', { jobId }) .subscribe({ next(value) { // Clear the timeout and return 'processed' once the job is completed console.log('Received value', value); clearTimeout(timeoutId); jobStateSubject.next({ status: 'processed', jobId, }); jobStateSubject.complete(); }, }); return lastValueFrom(jobStateSubject); } ``` You may need to adjust the timeout value based on your requirements. ## Troubleshooting The Producer Is Not Receiving the Response from the Consumer Ensure that the consumer function returns a value. undefined is not valid. If you need to return nothing, return an empty object {} or null.
luscasleo
1,876,019
Introduction to Machine Learning Algorithms in R
Introduction Machine learning is a subset of artificial intelligence that focuses on...
0
2024-06-04T00:32:04
https://dev.to/kartikmehta8/introduction-to-machine-learning-algorithms-in-r-3eg5
react, ruby, rust, javascript
## Introduction Machine learning is a subset of artificial intelligence that focuses on developing algorithms and models that allow machines to learn and make autonomous decisions without being explicitly programmed. R is a popular programming language used for statistical computing and graphics, which is also widely used for implementing machine learning algorithms. In this article, we will provide an introduction to machine learning algorithms in R. ## Advantages One of the main advantages of using R for machine learning is its extensive library of packages. There are numerous packages available in R specifically designed for data manipulation, preprocessing, and modeling, making it a convenient tool for machine learning tasks. Furthermore, R's visual capabilities allow for quick and easy data exploration and model evaluation. ## Disadvantages While R has a vast library of packages for machine learning, it can be overwhelming for beginners to navigate through them. Additionally, R's syntax can be more complex compared to other programming languages, making it challenging for those without a strong background in coding. ## Features R offers a wide range of machine learning algorithms, including regression, decision trees, support vector machines, and neural networks. It also has powerful data preprocessing capabilities, such as handling missing values, scaling, and encoding categorical variables. It also has built-in cross-validation functions for evaluating model performance. ### Example of Machine Learning with R Here is a simple example of implementing linear regression in R, which is a fundamental machine learning algorithm: ```R # Load the necessary library library(stats) # Sample data data <- data.frame( hours = c(2, 3, 4, 5, 6, 7, 8), scores = c(20, 30, 40, 50, 60, 70, 80) ) # Build the linear regression model model <- lm(scores ~ hours, data = data) # Summarize the model summary(model) ``` This example demonstrates how to perform linear regression analysis, which is one of the most basic machine learning techniques, using R’s built-in functions. ## Conclusion Machine learning algorithms in R provide powerful tools for data analysis and predictive modeling. While it may have a steep learning curve for beginners, the extensive library of packages and advanced features make it a popular choice for implementing machine learning tasks. With the continuous growth and advancement in this field, R will remain an important language for machine learning applications.
kartikmehta8
1,876,017
Criei um banco de dados baseado no Universo de One Piece
Olá, pessoal! Aqui é o Saulo. Hoje vamos embarcar em uma aventura através dos mares de dados,...
0
2024-06-04T00:28:03
https://dev.to/me_saulo/crie-um-banco-de-dados-baseado-no-universo-de-one-piece-7jo
sql
Olá, pessoal! Aqui é o Saulo. Hoje vamos embarcar em uma aventura através dos mares de dados, construindo um banco de dados relacional inspirado no incrível universo de One Piece. Sim, eu sei, quase todo mundo conhece One Piece - se você não conhece, provavelmente está navegando em outro Grand Line! ![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/r4r4it4jiec2x5jujaj5.png) ## <center>O Que é One Piece</center> --- One Piece é um dos mangás e animes mais populares do mundo, criado por Eiichiro Oda. A história segue as aventuras de Monkey D. Luffy e sua tripulação de piratas, os Chapéus de Palha, enquanto buscam o lendário tesouro "One Piece" para se tornarem os próximos Reis dos Piratas. Com mais de mil episódios, arcos envolventes e uma infinidade de personagens carismáticos, One Piece cativou fãs de todas as idades ao redor do globo. Se você ainda não viu, talvez esteja preso em um barril no meio do mar! ![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/ur733800f7hu243z7cnj.png) ### <center>O Que é Banco De Dados E SQL</center> --- Antes de navegarmos pelos mares de SQL, vamos falar um pouco sobre bancos de dados. Um banco de dados é uma coleção organizada de dados, estruturada de maneira que possa ser facilmente acessada, gerenciada e atualizada. Em termos simples, é como um grande livro de registros onde armazenamos todas as informações que precisamos de maneira eficiente e organizada. Existem vários tipos de bancos de dados, mas o mais comum é o banco de dados relacional, que utiliza tabelas para organizar dados em linhas e colunas. Agora que entendemos o que é um banco de dados, vamos mergulhar no SQL. SQL, ou Structured Query Language, é a linguagem padrão usada para gerenciar e manipular bancos de dados relacionais. Com SQL, podemos criar tabelas, inserir dados, consultar informações e muito mais. É uma ferramenta poderosa para qualquer desenvolvedor ou administrador de banco de dados. Agora, vamos navegar pelos mares de dados e ver como podemos estruturar um banco de dados para capturar a riqueza do universo de One Piece. Prepare-se para zarpar! ### <center>Modelo Do Banco De Dados</center> Nosso banco de dados será composto por várias tabelas interligadas, cada uma representando diferentes aspectos do universo de One Piece. Vamos detalhar cada uma dessas tabelas e suas relações. ![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/wlv7z2rfz3jbemjpi2ah.png) ### <center>Estrutura Da Tabela</center> #### <center> Pessoas </center> ![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/h4ko6vym7jnkvq1vlxfv.png) Vamos começar pela tabela Pessoa, que armazena informações básicas sobre os personagens. Nesta tabela, cada pessoa tem um ID único, nome, sobrenome, data de nascimento e região de origem. Isso nos permitirá identificar claramente cada personagem e suas origens. #### <center> Piratas </center> ![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/dip1jurlz38eorq11u2a.png) a tabela Pirata, que contém informações específicas sobre os piratas. Cada pirata tem um ID, posição (como capitão, imediato, etc.), recompensa pela sua captura e uma referência à tabela Pessoa. Isso nos ajuda a conectar cada pirata à sua identidade básica. --- #### <center> Marinha </center> ![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/4lz96i0vapjahahop8yq.png) Similarmente, a tabela Marinha armazena dados sobre os membros da Marinha. Aqui, guardamos a posição na Marinha e ligamos cada membro à tabela Pessoa. --- #### <center> Afiliação (Bandos) </center> ![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/0bgn29dzdbvddhtznds4.png) A tabela Afiliação representa as diversas afiliações ou tripulações dos personagens. Cada afiliação tem um nome e um ID de capitão, permitindo a identificação das diferentes tripulações e grupos. --- #### <center> Piratas nas Afiliações </center> ![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/7v9wc4mf2aj40oxbb908.png) Esta tabela resolve a relação muitos-para-muitos entre piratas e suas afiliações. Com esta tabela, podemos determinar a quais afiliações cada pirata pertence. --- #### <center> Akumanomi </center> ![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/sd6rze4jkz79jg0bgwkm.png) A tabela Akumanomi armazena as frutas do diabo e suas associações com personagens. Cada fruta do diabo tem um nome e pode estar associada a uma pessoa. --- #### <center> Haki </center> ![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/ydw9rh9wjq9mpjhi6aem.png) A tabela Haki lista os tipos de Haki existentes. --- #### <center> Usuários De Haki </center> ![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/kn5dm6z7zmdrmh5yftdg.png) Finalmente, a tabela que relaciona pessoas com os tipos de Haki que possuem. --- #### <center>Integridade Referencial<center> --- Para garantir a integridade dos dados, usamos chaves estrangeiras que conectam nossas tabelas. Isso assegura que nossos relacionamentos sejam consistentes e precisos, como um bom navegador que sempre encontra o rumo certo. #### <center> Exemplos de Consulta </center> --- Para exemplificar como essas tabelas funcionam juntas, aqui está uma consulta que junta informações sobre piratas, suas afiliações e os tipos de Haki que possuem : ![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/b7l2141snqattceckrp5.png) --- Esta consulta busca listar todos os piratas que possuem Haki, incluindo detalhes sobre suas afiliações e o tipo de Haki que possuem: ![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/uxb7vsi0ijzjaqosk7zs.png) #### <center> Conclusão <center> E é isso, pessoal! Com este modelo de banco de dados, você está pronto para navegar pelos mares de One Piece e gerenciar todas as informações dos personagens de forma eficiente e organizada. Espero que tenham gostado desta aventura de SQL e, claro, que ela inspire vocês a criar seus próprios projetos. Até a próxima viagem! ![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/dyz1talmhk3mljsq4wxe.png)
me_saulo
1,876,016
Decadent Desserts Await: Unlocking the Potential of the Perfect Cake Pan
Decadent Treats Wait for: Opening the Prospective of the Ideal Cake Frying pan Are actually you a...
0
2024-06-04T00:23:28
https://dev.to/dhssdnd_cijsje_f0472fe382/decadent-desserts-await-unlocking-the-potential-of-the-perfect-cake-pan-3ben
dessert
Decadent Treats Wait for: Opening the Prospective of the Ideal Cake Frying pan Are actually you a follower of yummy as well as tasty treats Perform you like cooking as well as producing type that is various of deals with for your family and friends If therefore, after that you should understand the significance of possessing the cake that is pan that is ideal your kitchen area Benefits of Possessing a Ideal Cake Frying pan If you are actually questioning why possessing the ideal bakery oven trays is essential, allow me inform you that it has actually lots of benefits. First of all, it guarantees that the cake appears completely. Second of all, it creates your cake appearance visually feeling free to, which is actually essential if you wish to thrill your visitors. As well as finally, it creates cooking a wind, ensuring that the cake does not stay with the pan that is frying Development in Cake Frying pan Along with opportunity, lots of developments have actually been actually created in cake pans that are frying. Today, there's a range that is big of, forms, as well as products towards select from. You can easily currently select in between rounded, frying or area that is even rectangle-shaped or even choose forms that are distinct hearts, celebrities, or even rubies. As well as certainly not towards fail to remember, cake frying pans have actually happened a way that is very is long from the steel that is conventional, which were towards that are actually susceptible as well as bending Security of Utilizing Cake Frying pans While cooking deals that are tasty in a oven tray for baking that is frying actually an task that is enjoyable it is actually likewise essential to think about precaution. It is actually necessary to select a cake pan that is frying's risk-free for you as well as your household. Select a safe as well as chemical-free pan that is frying's made from food-grade products like silicone, ceramic or even glass Ways to Utilize a Ideal Cake Frying pan Utilizing a cake pan this is certainly frying actually easy and simple. Very initial, prep the batter of the option along with preheat your stove. Following, oil the pan this is certainly frying with butter if not food that is preparing as well as include your butter. Location it in the stove as well as allow it cook depending on for your dish. When performed, allow it awesome prior to eliminating it coming from the pan that is frying Solution as well as High premium that is top of Frying pans Whenever choosing a cake pan this is certainly frying it really is essential towards choose one that includes solution this is certainly great well as supreme quality. To locate a brand name name that delivers a warranty, gain plan, in addition to customer care that is outstanding. Furthermore, select a pan this is certainly frying durable along with resilient, rust-proof, along with simple towards cleanse Requests of Cake Frying pans Cake frying pans are now actually flexible in addition to could be utilized for possibly an array of treats. Regardless of conventional baking oven tray cakes, it is possible to utilize a cake pan this is certainly brownies which can be frying are create bars, muffins, bread, cheesecake, in addition to much a deal that is great. The opportunities are now actually unlimited, in addition to it is possible to check out dishes which can be produce that is various deals which can be new Source: https://www.wxhongbei.com/application/bakery-oven-trays
dhssdnd_cijsje_f0472fe382
1,875,967
Why Small Businesses Need Robust Commercial Security Measures
Running a small business is no easy task. Between managing employees, handling finances, and ensuring...
0
2024-06-04T00:09:47
https://dev.to/alpine_protectionservice/why-small-businesses-need-robust-commercial-security-measures-21hj
security, protection, commercialsecurity
Running a small business is no easy task. Between managing employees, handling finances, and ensuring customer satisfaction, there's a lot on a small business owner's plate. One critical aspect that often doesn't get the attention it deserves is security. Protecting your business from theft, vandalism, and other threats is vital for maintaining its success and reputation. In this blog, we'll explore why small businesses need robust security measures and how these measures can make a significant difference. The Importance of Protecting Your Assets As a small business owner, your assets are the lifeblood of your company. These assets include everything from your inventory and equipment to your financial records and proprietary information. Without proper protection, these valuable resources are at risk. A strong commercial security system helps safeguard your assets against theft and damage, ensuring your business can continue to operate smoothly. Preventing Theft and Vandalism Small businesses are often targeted by criminals because they tend to have fewer security measures in place compared to larger corporations. Theft and vandalism can cause significant financial losses and disrupt your operations. By investing in robust security measures, such as surveillance cameras, alarm systems, and secure locks, you can deter potential criminals and minimize the risk of these incidents occurring. ![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/dea9hxmm3yi2n3hsiq1f.jpg) **Ensuring Employee Safety** Your employees are one of your most valuable assets. Ensuring their safety should be a top priority. A well-implemented commercial security system can create a safer working environment by preventing unauthorized access and reducing the risk of workplace violence. When employees feel safe, they are more likely to be productive and satisfied with their jobs, which can lead to lower turnover rates and higher morale. **Protecting Sensitive Information** In today's digital age, protecting sensitive information is more important than ever. Small businesses often store customer data, financial records, and other confidential information that, if compromised, could lead to severe consequences. It measures, such as secure access controls, firewalls, and encryption, help protect this data from cyber threats and unauthorized access. By safeguarding your information, you can maintain customer trust and avoid potential legal issues. **Reducing Insurance Costs** Insurance is a necessary expense for any business, but it can be costly. Many insurance companies offer discounts on premiums for businesses that have robust [commercial security ](https://alpineprotection.ca/all-services/commercialsecurity-services/)systems in place. By investing in security measures, you can reduce the risk of incidents occurring, which in turn can lower your insurance costs. This not only saves you money but also provides peace of mind knowing your business is better protected. **Enhancing Customer Confidence** Customers want to feel safe when they visit your business. Whether you're running a retail store, a restaurant, or an office, a strong security system can enhance customer confidence. Visible security measures, such as surveillance cameras and well-lit parking areas, show customers that you take their safety seriously. This can lead to increased customer loyalty and positive word-of-mouth recommendations, helping your business grow. **Reducing the Risk of Internal Theft** While external threats are a significant concern, internal theft is another risk that small businesses must address. Employees may be tempted to steal money, inventory, or sensitive information, especially if there are no security measures in place. An inclusive commercial security system can help prevent internal theft by monitoring employee activities and providing a clear record of any suspicious behavior. This can deter potential thieves and help you quickly identify and address any issues. **Supporting Business Continuity** Unexpected incidents, such as natural disasters, fires, or break-ins, can disrupt your business operations and cause significant financial losses. Robust security measures can help you quickly respond to and recover from these incidents. For example, surveillance footage can provide valuable evidence for insurance claims, while alarm systems can alert authorities to a break-in, minimizing damage and loss. By having a solid security plan in place, you can ensure that your business can continue to operate even in the face of adversity. **Conclusion ** In conclusion, the imperative for small businesses to prioritize robust [commercial security](https://alpineprotection.ca/all-services/commercialsecurity-services/) measures cannot be overstated. From protecting assets and preventing theft to ensuring employee safety and enhancing customer confidence, the benefits of investing in inclusive security solutions are manifold. By embracing modern technologies, fostering a security-conscious culture, and partnering with professional security services, small businesses can create a fortified defense against a myriad of threats.
alpine_protectionservice
1,875,966
Introduction to Generative AI
The values we intend should be meaningful and beneficial to the growth of Digital era..Knowing we...
0
2024-06-04T00:08:32
https://dev.to/swirlybitz/introduction-to-generative-ai-3gib
The values we intend should be meaningful and beneficial to the growth of Digital era..Knowing we cannot harm humanity..
swirlybitz
1,875,965
Making My Own Karaoke Videos with AI
The other day I was at a Karaoke event and was frustrated that they didn't have the song I wanted. I...
0
2024-06-04T00:04:08
https://dev.to/muddylemon/making-my-own-karaoke-videos-with-ai-4b8l
ai, whisper, python, llm
The other day I was at a Karaoke event and was frustrated that they didn't have the song I wanted. I have an extremely limited range vocally. I can do Tom Waits, Bob Dylan and non-autotuned Kanye and even then, only the slower songs. Essentially, any male vocalist known more for their unique voice than their singing prowess fits my range. Given those limitations, there's not a lot of choice in the pop and country oriented karaoke apps that fit my "unique" abilities. Even the reliable YouTube search for "song name artist karaoke version" often falls short. That particular night I was thinking about the somewhat obscure [Dylan song "Every Grain of Sand"](https://reclinernotes.com/2021/07/04/every-grain-of-sand/) - a rare classic from Dylan's "Christian period" in the late 70s to early 80s. I found one result on Youtube - a homemade karaoke video that someone recorded in their living room. It didn't have the right tempo and, worst of all, used the album lyrics with the phrase "I am hanging in the balance of a perfect finished plan.” instead of the earlier, and in my opinion, superior line "I am hanging in the balance of the reality of man." While I sat listening to a perfect rendition of "Man, I feel like a woman!" by one of the regulars, I hatched a plan to whip up some python to get some robots to build a karaoke version of any song on demand. Here's how that went: ## Setting up the project and environment The first step is of course to create a little workshop on your machine to work out of. I created a new folder in my venerable ~/code/ directory named `custom-karaoke` and got to work. Since we're using python, let's first create an environment to contain all our dependencies and code. We're going to use venv to create a virtual environment to contain our dependencies and keep everything managed locally. ```bash mkdir custom-karaoke cd custom-karaoke python -m venv venv ./venv/Scripts/activate touch main.py ``` You will need to have [*ImageMagick*](https://imagemagick.org/script/download.php) installed on your system. If ImageMagick is installed in the standard location, you shouldn't need to tell moviepy where it is. If you do need to specify the location, you can call the `change_settings` function from `moviepy.config`. I use the following code to ensure the script works on my Macbook and my Windows PC: ```python from moviepy.config import change_settings import platform if platform.system() == "Darwin": imagemagick_path = "/opt/homebrew/bin/magick" elif platform.system() == "Windows": imagemagick_path = "C:/Program Files/ImageMagick-7.1.1-Q16-HDRI/magick.exe" else: raise NotImplementedError("Unsupported operating system") change_settings({"IMAGEMAGICK_BINARY": imagemagick_path}) ``` Now that we've got the rudiments of a python project up, let's write some code! First, we'll create a running python script with our main.py. Your IDE might complain about us importing things we're not using yet, but we will get to those soon enough. ```python import argparse import os import demucs.api import torch import whisper from moviepy.editor import * from moviepy.video.tools.subtitles import SubtitlesClip from moviepy.config import change_settings from whisper.utils import get_writer import platform if platform.system() == "Darwin": imagemagick_path = "/opt/homebrew/bin/magick" elif platform.system() == "Windows": imagemagick_path = "C:/Program Files/ImageMagick-7.1.1-Q16-HDRI/magick.exe" else: raise NotImplementedError("Unsupported operating system") change_settings({"IMAGEMAGICK_BINARY": imagemagick_path}) def parse_arguments(): parser = argparse.ArgumentParser( description="Create a karaoke video from a video file.", formatter_class=argparse.ArgumentDefaultsHelpFormatter, ) parser.add_argument( "video_path", help="Path to the video file.") return parser.parse_args() def main(): args = parse_arguments() video_path = args.video_path.replace("\\", "/") print(f"\nProcessing {video_path}.") if __name__ == "__main__": main() ``` And just like that we have a running program - it's not particularly useful, but it's a start. You can run this file like so: ```bash python ./main.py ../path-to/video-file.mp4 ``` With any luck this will print out `Processing ../path-to/video-file.mp4` and exit. As you may have guessed, the next step is... actually processing the video file. Before we can do that we need to figure out what it means to process the file. We are going to want to: 1. Extract the audio of the file 2. Split that audio file into a vocals track and a music track 3. Transcribe the contents of the vocals track into a subtitle file 4. Create a video that contains the video of the original overlayed with the lyrics as they're being sung and the audio of the music track sans vocals Sounds simple! Of course, we're not going to have to invent ways to do each of these steps, we're going to be relying on some innovative and powerful libraries published by some of the smartest coders in the world. ### Extract the Audio of the file For this step, we're going to use the `moviepy` library - which is mostly a python wrapper over the essential tool `ffmpeg`. Here's a function to create an mp3 audio file from our video file: ```python def video_to_mp3(video_path: str): """Converts a video file to an mp3 file.""" print(f"Converting video to mp3 -> {video_path}") audio_path = video_path.replace(".mp4", ".mp3") if os.path.exists(audio_path): return audio_path audio = AudioFileClip(video_path) audio.write_audiofile(audio_path, logger="bar") print(f"Audio saved to: {audio_path}") return audio_path ``` This function takes a video file path and using *AudioFileClip* (which is provided by moviepy) creates an audio file which is saved next to our original file with the extension .mp3 and returns the path to the mp3 file. You'll notice a pattern at the beginning of the function that we will be repeating later. Sometimes things will go wrong and it's frustrating having to start all over and run all these conversions again. With this check we can look for the mp3 file and skip creating it in subsequent runs. (More on this later) In order to run this code we're going to need to supply the **moviepy** library. Within the project directory, run: ```bash pip install moviepy ``` Then you can call the function from your main function: ```python def main(): args = parse_arguments() video_path = args.video_path.replace("\\", "/") print(f"\nProcessing {video_path}.") audio_path = video_to_mp3(video_path) print(f"Created audio file: {audio_path}.") ``` Now when you run the script (`python ./main.py ../path-to/video-file.mp4`) you will see the second message and should find the mp3 file sitting next to your original video file. You can run the script as much as you want, it will return the same file unless you delete it. ### Split the audio file into a vocals track and a music track The hardest part of this section is remembering how to spell *separate*. We're using the *dmucs* library to split the audio track into four separate *stems*: vocals, drums, bass and the ambiguously named "other." We will be using the vocal stem to create a transcript and combining the other stems into a single music track. We will use the *demucs* library to perform this magic. [Install **demucs**](https://github.com/adefossez/demucs) - I've found it necessary to install directly from github like so: ```bash pip install -U git+https://github.com/facebookresearch/demucs#egg=demucs ``` Now create a function in main.py to split the stems. ```python def separate_stems(audio_file_path: str) -> tuple[str, str]: """Separates vocals and music from an audio file.""" if not os.path.exists("./stems"): os.makedirs("./stems") audio_filename = audio_file_path.split("/")[-1] if os.path.exists(f"./stems/vocals_{audio_filename}"): return f"./stems/vocals_{audio_filename}", f"./stems/music_{audio_filename}" separator = demucs.api.Separator(progress=True, jobs=4) _, separated = separator.separate_audio_file(audio_file_path) for stem, source in separated.items(): demucs.api.save_audio( source, f"./stems/{stem}_{audio_filename}", samplerate=separator.samplerate) demucs.api.save_audio( separated["other"] + separated["drums"] + separated["bass"], f"./stems/music_{audio_filename}", samplerate=separator.samplerate) return f"./stems/vocals_{audio_filename}", f"./stems/music_{audio_filename}" ``` ### Transcribe the vocal track into a subtitle file Now that we have a clean vocal track we can create a subtitle file (.srt) by using [**Whisper**, OpenAI's audio transcription tool](https://github.com/openai/whisper). There are a number of Whisper related projects that add useful functionality, speed up transcription or offer additional features. For this example, we'll stick with the original by installing it like so: ```bash pip install openai-whisper ``` Take note of the *openai-* bit, more than once I've accidentally installed `whisper` which is a completely unrelated package. Whisper will run on the CPU - slowly. If you have an Nvidia GPU you can run whisper at a much swifter clip by installing torch and using the CUDA libraries. To set that up visit the [PyTorch installation page](https://pytorch.org/get-started/locally/) and copy the command it provides you based on your setup. Mine looks like this: ```bash pip3 install torch torchvision torchaudio --index-url https://download.pytorch.org/whl/cu118 ``` Now we just need to create a function to create the transcription of our vocal track. ```python def transcribe(audiofile_path: str, num_passes: int = 1) -> str: """ Converts an MP3 file to a transcript using Whisper Args: audiofile_path (str): The file path of the MP3 file to be processed. num_passes (int): Number of transcription passes to perform. Returns: str: The path to the SRT file containing the transcript from the last pass. """ try: subtitle_path = os.path.join("./subtitles", os.path.splitext( os.path.basename(audiofile_path))[0] + '.srt') if os.path.exists(subtitle_path): return subtitle_path if not os.path.exists("./subtitles"): os.makedirs("./subtitles") device = 'cuda' if torch.cuda.is_available() else 'cpu' model = whisper.load_model("large-v2").to(device) last_result = None for i in range(num_passes): print(f"Transcription pass {i + 1} of {num_passes}...") current_result = model.transcribe( audiofile_path, verbose=True, language="en", word_timestamps=True) last_result = current_result if last_result is None: raise ValueError("No transcription results obtained.") srt_writer = get_writer("srt", "./subtitles") srt_writer(last_result, audiofile_path, highlight_words=True) return subtitle_path except Exception as e: print(f"Error converting MP3 to transcript: {e}") return "" ``` This function loads a whisper model and runs the transcribe method on our audio file. There are several models available. I've had the best luck with `large-v2`. Oddly enough, `large-v3` gave me consistently worse results. The smaller models need less memory to run. If you are limited on memory you can try `medium.en` which is sufficiently robust to get the transcription mostly right. We're using the `srt_writer` function from Whisper to convert our results into a subtitle file (srt). This brings us to the real point of our 'short-circuit' code included in each of these functions. After your first run you'll be able to assess how well the transcription went. There are often at least a few mistakes that can be manually edited. After you fix the mistakes you can run the script again and it will start with your edited subtitles and not re-do all the work we've done so far. Did you notice the argument `word_timestamps` that we passed to the transcribe function? That is particularly important in our use case. That will allow us to highlight specific word being sung at the time. Here's an example showing off the word timestamps feature: {% embed https://www.youtube.com/watch?v=Docw0lvB4Ig %} Another helpful feature is the `num_passes` argument. By default we're going to run the transcription just once. However, especially when running a smaller model, you can get better results by letting the model *warm up* for a cycle or two. If you find the subtitle quality to be poor but don't have the memory for a larger model you can run the smaller models a couple times and see if you get better results. ## Putting It All Together Now to mash all of these bits back together into a useable karaoke video. First let's update our `main` function to call the new `create` function that we will be writing below: ```python def main(): args = parse_arguments() video_path = args.video_path.replace("\\", "/") print(f"Creating karaoke video..") create(video_path) ``` Now we can implement all of the functions we created above and produce a useable karaoke video. ```python def create(video_path: str): """Creates a karaoke video from the separated audio files and the original video file. Args: video_path (str): The path to the original video file. Returns: str: The filename of the created karaoke video. """ audio_path = video_to_mp3(video_path) vocals_path, music_path = separate_stems(audio_path) music = AudioFileClip(music_path).set_fps(44100) vocals_audio = AudioFileClip(vocals_path).volumex(0.05).set_fps(44100) combined_audio = CompositeAudioClip([music, vocals_audio]) background_video = VideoFileClip(video_path, target_resolution=(720, 1280)).set_fps( 30).set_duration(combined_audio.duration) dimmed_background_video = background_video.fl_image( lambda image: (image * 0.3).astype("uint8")) subtitles_file = transcribe(vocals_path, 1) def generator(txt): """Generates the subtitles for the karaoke video. Args: txt (str): The text to be added to the subtitles. Returns: TextClip: The subtitle text clip. """ return TextClip( txt, font="Impact Condensed", fontsize=36, color="#FFFFFF", stroke_color="#000000", stroke_width=0.5, size=(1200, None), method='pango' ) subtitles = SubtitlesClip(subtitles_file, generator) result = CompositeVideoClip([ dimmed_background_video, subtitles.set_position(('center', 'center'), relative=True) ]).set_audio(combined_audio) filename = f"karaoke_{os.path.basename(video_path)}" if not os.path.exists("./output"): os.makedirs("./output") result.write_videofile(f"./output/{filename}", fps=30, threads=4) return filename ``` This function starts off with the video path we passed in and then creates the mp3 audio file and separates the stems using the functions we created above. The next step is optional, but I like when the original vocals are just barely audible in the background. It's helpful for a guy with little to no rhythm like myself. To do this we create a new `CompositeAudioClip` using our music track and the vocals track turned down to 5% volume. We then create a copy of the original video with the screen dimmed. Note that because we cached our outputs in this script, you can swap out the original video with another after the first run, as long as they have the same name. I've used this trick when I have a video with pristine audio but a static or otherwise poor visual with a more visually interesting video. In the first karaoke video I tried, [*Every Grain of Sand*](https://www.youtube.com/watch?v=Un5XJziOFCI), the only source material for an intelligible version of Dylan's lyrics that I could find had a static background of the album cover. I replaced the background video in the final version with a live version that was more visually interesting but, as is typical with late Dylan performances, mostly mumbling along to the melody. At this point we create our subtitle file and then define a *generator* function that will run for every frame displaying the text of the lyric being sung at that moment. Because we used the argument `word_timestamps` in our transcribe call and we selected the method `pango`, the specific word will be wrapped in a `<u>tag</u>` which will underline it. If you want to decorate the word differently you can replace those tags in the *generator* with anything that `pango` can render. You can explore those options in the [pango documentation](https://docs.gtk.org/Pango/) - but for our purposes, you're better off [checking out these examples.](https://im.snibgo.com/pango.htm) The `TextClip` that the generator returns can be customized with your choice of font, font size, color and so on. The size argument requires a tuple of the (width, height) of the text. We want to restrict the width to a bit smaller than our output. We set our output in the `background_video` above. The height we leave as `None` so that it will be dynamically sized depending on the length of the text. Finally, we stack our background video and subtitles video along with our music track into our final karaoke style video and save it to disk. {% embed https://youtu.be/c-aXZXd_aNI %} You can find the complete code at this [GitHub repository](https://github.com/muddylemon/custom-karaoke/tree/main). Feel free to fork the project and add your own features. By setting up this custom karaoke solution, I’ve ensured that I’ll always have the perfect song ready to match my vocal range. Whether you’re also limited in your singing capabilities or just enjoy a custom karaoke experience, I hope you find this guide helpful. Happy singing! ## Helpful Tips If you're looking to download source material from the internet, [`yt-dlp`](https://github.com/yt-dlp/yt-dlp) is a great tool that can extract and save videos locally from a wide variety of sources like youtube, twitter and more. When I use `yt-dlp` I typically add the flag `-f b` which will default the highest resolution mp4. I hate dealing with .webm and .mkv files and the mp4 is good enough for our purposes. For this project I created a local folder named inputs to store my source videos. It's listed in the *.gitignore* file to keep those binary files out of source control. ```bash cd inputs yt-dlp https://video.site/watch?v=ABC123 -f b ``` You can choose any font on your system, but some fonts act a little wonky when being formatted with `pango`. Start with a short song! It's much better to find out that you have a bug after a few seconds of processing than after several minutes. Try updating the font to something unique. Try messing with the relative volumes of the tracks. Try changing the SRT to display the song title before the lyrics. This is a great project to use to improve your python skills! Add a requirements.txt with the following content: ```bash moviepy demucs @ git+https://github.com/facebookresearch/demucs@e976d93ecc3865e5757426930257e200846a520a openai-whisper ``` With this you can install all of your 3rd party packages in one command. Don't forget to activate your virtual environment before you do! ## Examples {% embed https://www.youtube.com/watch?v=5dxos4c8KXQ %} {% embed https://youtu.be/MG4-orqa_Dw %} {% embed https://youtu.be/YcGzvc5RkCE %} {% embed https://youtu.be/c9ujdsRyp7I %}
muddylemon
1,877,120
giving up on offline pgp keys
In 2018, I revamped my PGP keys, deprecating old keys that were created when I was a baby sysadmin,...
0
2024-06-16T18:34:43
https://cg505.com/blog/giving-up-on-offline-pgp
--- title: giving up on offline pgp keys published: true date: 2024-06-04 00:00:00 UTC tags: canonical_url: https://cg505.com/blog/giving-up-on-offline-pgp --- In 2018, I revamped my PGP keys, deprecating old keys that were created when I was a baby sysadmin, and replacing them with a ~new fancy offline master key with expiring subkeys~. This meant that my keys were on a Raspberry Pi that had its network interfaces disabled. I only ever used the built-in serial terminal to interface with the master key - it was otherwise fully airgapped and more secure than anything else has ever been in my life. Well, my subkeys expired in 2020, and because it was such a PITA to fix, I just let them expire. To be fair, there was a pandemic going on. But I also never got around to it in any of the four years that followed. In that time, I gave up on PGP in general. I read [The PGP Problem](https://www.latacora.com/blog/2019/07/16/the-pgp-problem/) and [Filippo’s blog post](https://words.filippo.io/giving-up-on-long-term-pgp/). [SKS died](https://gist.github.com/rjhansen/67ab921ffb4084c865b3618d6955275f), and we had to [kill the keyserver I helped run](https://github.com/ocf/puppet/issues/816). So, I didn’t have much incentive to preserve my PGP keys. But, eventually I realized that they can be useful. PGP keys are still frequently used for package signing or verification of git commits. I’d like to join [dn42](https://dn42.dev), and they use PGP keys to prevent AS or IP space takeovers instead of relying on LOAs (lol).<sup id="fnref:dn42-keys" role="doc-noteref"><a href="#fn:dn42-keys" rel="footnote">1</a></sup> Like it or not, in many spaces, PGP is the established default. So I’ve realized that slightly less secure keys are probably better than no keys at all. Rather than having to find my UART adapter, I’ve given up on the Pi setup. To this end, my master key is no longer offline - it’s on the laptop I’m using to publish this post, protected by a passphrase. This puts it in approximately the same class of security as my bank credentials, all the infra I have access to, my email account and all my backups, etc. So I think it’s probably fine. I’ve updated my keys to include the email I use these days. I also added a non-expired encryption subkey, in case you really need to send me something PGP-encrypted for whatever reason. I don’t have an active signing or authentication key, as I don’t use these at the moment. My keys are available on [keys.openpgp.org](https://keys.openpgp.org/search?q=F1DA0D0FD84CDA4C6FE052E365F6C6C95459F55E), or you can just download it from this website - [cg505.com/key.asc](/key.asc). The fingerprint is `F1DA0D0FD84CDA4C6FE052E365F6C6C95459F55E`. I will not be using WKD as [I’d like to be able to read my email](https://matduggan.com/why-cant-my-mom-email-me/) - this may require me to remove the key from keys.opepgp.org if I have problems in the future. If you want to sign my key, go ahead, I guess. I’m not going to be making an effort to get into the strong set or anything like that. If you want to reach me securely, please don’t send me an encrypted email. Message me on Signal, where my username is `cg5.05`. See you around! — cg505 1. You _can_ also use SSH keys to sign dn42 changes, but this feels like a misuse of SSH keys. I want my SSH keys to do one thing (authenticate me to SSH servers) and nothing else. I’d rather use PGP keys since they’re at least designed to be general-purpose, for better or worse. This argument gernalizes to all use of SSH keys for signing git commits. [↩](#fnref:dn42-keys)
cg505
1,876,775
Storyblok live editing with Next.js App Router and React Server Components
The problem When working with Storyblok there are two ways to set up your Next.js app if...
0
2024-06-17T12:37:08
https://techhub.iodigital.com/articles/storyblok-live-editing-nextjs-app-router
nextjs, storyblok
--- title: Storyblok live editing with Next.js App Router and React Server Components date: 2024-06-04 00:00:00 UTC published: true tags: Nextjs,Storyblok canonical_url: https://techhub.iodigital.com/articles/storyblok-live-editing-nextjs-app-router cover_image: https://techhub.iodigital.com/_next/image?url=%2Farticles%2Fstoryblok-live-editing-nextjs-app-router%2Fstoryblokxnextjs.webp&w=3840&q=75 --- ## The problem When working with Storyblok there are **two** ways to set up your Next.js app if you use the app router. The first way is to wrap your entire app in a provider which then takes care of updating the app when you edit anything in the preview environment of Storyblok, thus giving you live editing. Live editing is a cool feature because an editor can directly see the changes they made without constantly saving the page. The second approach keeps everything server-side. This is nice because we can then leverage the full power of server components. But this approach comes with a big limitation... you lose the live editing support and the editor can only see their changes after they've hit the save button. Or is there a way... I found this [Gist](https://gist.github.com/Ventanas95Dev/2683f50accac68369ef6bdc3fc62e392) from someone who stumbled across the same issue and solved it with a clever solution. I expanded on their solution and replaced their database (`@vercel/kv`) with something free and local. Let's dive in on how I did it! ## The solution When you are in the live editing environment of Storyblok, they add a class to the browser's `window` object called `StoryblokBridge`. This bridge allows you to listen to live editing events happening with `on()`: ```JS const sbBridge = new window.StoryblokBridge(options) sbBridge.on(['input', 'published', 'change '], (event) => { const story = event.story // ... }) ``` The event returned contains the updated story with the live editing data the user entered. Awesome! We can use this live story and save it somewhere, then revalidate the page using Next.js' `revalidatePath()` API. Let's see how: Let's first tackle the "save it somewhere" part of the solution. I used [node-cache](https://github.com/node-cache/node-cache) for this. Create an `instrumention.ts` file in the root or src folder of your project: ```JS import type NodeCache from 'node-cache' export async function register() { const NodeCache = (await import('node-cache')).default const config = { stdTTL: 100, } global.storyblokCache = new NodeCache(config) } ``` Add this to `next.config`: ```JS experimental: { instrumentationHook: true, }, ``` This setup makes sure the cache won't be reset with each request, only on server startup. Next, let's take a look at how we get the live editing data from Storyblok and save it in this cache. For this we first need to create a custom Storyblok bridge: ```JS export const registerStoryblokBridge = ({ onInput }) => { const isServer = typeof window === 'undefined' const isBridgeLoaded = !isServer && typeof window.storyblokRegisterEvent !== 'undefined' if (!isBridgeLoaded) { return } window.storyblokRegisterEvent(() => { const sbBridge = new window.StoryblokBridge() sbBridge.on(['input'], (event) => { if (!event?.story) return onInput(event.story) }) }) } ``` This function listens to live editing events, as we found out above, and makes a callback with the story containing the latest live editing data. We then use this function in a client component ```JS "use client"; import { previewUpdateAction } from "@/actions/previewUpdateAction"; import { registerStoryblokBridge } from "@/utils/storyblok"; import { useEffect, startTransition } from "react"; export const StoryblokPreviewSyncer = ({ pathToRevalidate }) => { function handleInput(story) { startTransition(() => previewUpdateAction({ story, pathToRevalidate, }) ); } useEffect(() => { registerStoryblokBridge({ onInput: handleInput, ); }, []); return null; }; ``` This client component makes sure the window event is fired with `useEffect`. The `handleInput` function uses React's `startTransition` to call a Next.js Server Action containing the latest data. Let's find out what this server action looks like. ```JS 'use server' import { revalidatePath } from 'next/cache' import { ISbStoryData } from '@storyblok/react' export async function previewUpdateAction({ story, pathToRevalidate }) { if (!story) { console.error('No story provided') return } try { global.storyblokCache.set(story.slug, JSON.stringify(story)) if (pathToRevalidate) { revalidatePath(pathToRevalidate) } } catch (error) { console.log(error) } } ``` This function takes the story with the live editing data and saves it to our cache. It then calls `revalidatePath` to make sure Next.js knows it needs to update the page. We now only need one more piece to solve the puzzle and that is the function that takes care of fetching the story: ```JS export const getStoryblokData = async (slug) => { const storyblokApi = getStoryblokApi() try { const story = global.storyblokCache?.get(slug) if (!story) { const result = await storyblokApi.get(`cdn/stories/${slug}`, { version: 'draft' }) return result.data.story } return JSON.parse(story) } catch (e) { console.log(e) } } ``` This function first tries to fetch the story from the database (this would be the story with the latest live editing). If this fails it falls back to the Storyblok API. We can then use this function on a page together with our `<StoryblokPreviewSync />` component: ```JS import { StoryblokComponent } from '@storyblok/react/rsc' import { StoryblokPreviewSyncer } from '@/components/StoryblokPreviewSync' import { getStoryblokData } from '@/utils/storyblok' export default async function Home() { const story = await fetchData() return ( <main> <StoryblokPreviewSyncer pathToRevalidate={'/'} /> <StoryblokComponent blok={story?.content} /> </main> ) } function fetchData() { return getStoryblokData('home') } ``` There you go! Now you should have live editing support, with the full power of React Server Components!
io_digital
1,875,536
How to get people to use your app as a solopreneur
I have been building web applications for about 6 years professionally now, and I have struggled to...
0
2024-06-03T23:58:51
https://dev.to/leonardoventurini/how-to-get-people-to-use-your-app-as-a-solopreneur-2o2f
webdev, tutorial, marketing, beginners
I have been building web applications for about 6 years professionally now, and I have struggled to get users for a long time until I realized one simple thing. Before we get to that thing, let me get some things out of the way. In the beginning you have ZERO track record, perhaps you have no money to pay for ads, or you don't want to (I don't think its a good idea until you reach a certain stage). You might even feel like no one cares about your product – an app is a product and you have to see it that way, and develop your knowledge of product design. On the off chance that you get someone to use it, they don't last long, perhaps they used it for the wrong reasons or as a favor. You need to educate and onboard them well. Let me tell you a little secret: You are the first user! You are the track record. Do you know who should be happy about your product first? You! If you are not happy with your product, if you don't use it, no one will! You are the carrier of your brand, and that will get you your first users. Then comes communication and marketing skills, but everything starts with you! Every interaction, trip or conference you go is an opportunity to sell your product and form meaningful connections. But first you have to BELIEVE. You need to believe that your product is valuable and that it will transform the lives it touches. Otherwise your energy will repel users instead of attracting them! Most likely, if you are building something you are an engineer by nature, and I myself was like this, I was very analytical, often stressed and grumpy. But we need to SMILE! We need to activate our human side if we want to be successful. You can go only so far by being the most incredible technical wizard in the world, perhaps you can even get lucky. But the most certain way of achieving wondrous results, is by helping other human beings, and many of them don't know they need what you have to sell! You should tell them, and you should tell them in a way that makes them feel incredible. Once you have your users rolling in and they are STAYING, i.e. loving your product, then you will have a track record which you can use to get ever more users. What got you here, will not get you there. Don't try to imitate big brands... the mechanics change at each stage in the growth of a product or brand. Being a solopreneur is difficult, but not impossible. The key takeaway here is: you are responsible for the marketing of your product, and you have more power than you think. And when you record that video showcasing your product: smile!
leonardoventurini
1,875,961
The Future of Elon Musk Artificial Intelligence, Insights and Perspectives
Elon Musk's foray into artificial intelligence (AI) has been both ambitious and controversial,...
0
2024-06-03T23:51:02
https://dev.to/jasierbro/the-future-of-elon-musk-artificial-intelligence-insights-and-perspectives-39im
ai, elonmusk
Elon Musk's foray into artificial intelligence (AI) has been both ambitious and controversial, sparking intense debate about the future of AI and its impact on humanity. As a visionary entrepreneur, Musk has founded several companies, including Neuralink, OpenAI, and Tesla, each with its own unique approach to AI development. In this inclusive exploration, we will delve into the future of Elon Musk's artificial intelligence ventures, examining insights and perspectives on the potential implications for society, technology, and the future of humanity. Vision for Elon Musk Artificial Intelligence Elon Musk has been vocal about his concerns regarding the potential risks associated with AI, famously referring to it as "the greatest risk we face as a civilization." Despite his warnings, Musk also recognizes the immense potential of AI to revolutionize various industries and enhance human capabilities. His vision for artificial intelligence encompasses both the benefits and challenges it presents, driving him to invest in AI research and development to steer its trajectory towards a positive outcome. **Merging the Human Brain with Artificial Intelligence ** One of Elon Musk's most ambitious projects, Neuralink, aims to develop brain-machine interface technology to merge the human brain with artificial intelligence. The goal of Neuralink is to enhance human cognition and communication by enabling direct communication between the brain and external devices. Musk envisions a future where individuals can seamlessly interact with AI systems, augmenting their intelligence and abilities through neural interfaces. ![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/vwr7y1kqv4lmkiia8vjb.jpg) **Democratizing Artificial Intelligence ** OpenAI, founded by [Elon Musk Artificial Intelligence](https://jasierbro.com/the-vision-of-elon-musk-and-his-hard-work-in-the-field-of-artificial-intelligence/) and others, is dedicated to advancing artificial intelligence in a responsible and ethical manner. The organization conducts research and develops AI technologies with the goal of ensuring that the benefits of AI are widely distributed and accessible to all. Through initiatives such as open-source AI projects and AI safety research, OpenAI seeks to democratize AI and mitigate potential risks associated with its development and deployment. Tesla, led by Elon Musk, is at the forefront of innovation in autonomous vehicles, leveraging AI technologies to develop self-driving cars. Tesla's Autopilot feature uses advanced AI algorithms to enable semi-autonomous driving capabilities, with the ultimate goal of achieving full autonomy. Musk believes that autonomous vehicles powered by AI will revolutionize transportation, making roads safer, reducing traffic congestion, and minimizing environmental impact. **Perspectives on the Future of Elon Musk Artificial Intelligence ** The future of Elon Musk's artificial intelligence ventures is a topic of great interest and speculation, eliciting diverse perspectives from experts, scholars, and the public. Some view Musk's efforts as visionary and groundbreaking, with the potential to unlock new frontiers in human-computer interaction and AI-driven innovation. Others express concerns about the ethical, social, and existential risks associated with AI development, urging caution and responsible stewardship. **Ethical Considerations ** One of the key areas of discussion surrounding Elon Musk's artificial intelligence ventures revolves around ethical considerations. As AI technologies continue to advance rapidly, questions arise about how they should be developed, deployed, and regulated to ensure that they benefit society while minimizing harm. Musk himself has emphasized the importance of ethical AI development and has advocated for proactive measures to address potential risks, such as the implementation of AI safety research and the establishment of regulatory frameworks. However, navigating the ethical complexities of AI requires careful consideration of various factors, including privacy, autonomy, accountability, and bias. As Elon Musk's AI ventures progress, ethical considerations will play an increasingly significant role in shaping the future of artificial intelligence and its impact on humanity. **Conclusion** In conclusion, the future of Elon Musk artificial intelligence holds immense promise and potential, as well as significant risks and challenges. By fostering dialogue, collaboration, and responsible innovation, we can harness the power of AI to improve lives, advance knowledge, and shape a more equitable and sustainable future for humanity. Elon Musk's vision for artificial intelligence serves as a catalyst for exploration and innovation, inspiring us to confront the opportunities and complexities of AI with courage, curiosity, and foresight.
jasierbro
1,875,959
Solana (SOL): Will it Rebound Back to $170 or Slip Down to $150?
With the resurgence of memecoin mania, Solana also received significant momentum. The bulls used all...
0
2024-06-03T23:47:41
https://dev.to/korofetova_mila/solana-sol-will-it-rebound-back-to-170-or-slip-down-to-150-41im
beginners, tutorial, react, ai
With the resurgence of memecoin mania, Solana also received significant momentum. The bulls used all their strength to keep the value above $180 but the growing bearish strength caused a notable pullback. As a result, the $SOL price is consolidating strongly within a narrow range of $163 to $172, indicating the possibility of a large move ahead. While the crypto markets have been outpowered by the bears, can the SOL price initiate a fresh upswing to nullify the selling pressure? Ever since the start of the rally in March, the SOL price has demonstrated its strength by marking highs above $200 a couple of times. However, a rejection followed, causing a 40% loss in value. Regardless of this, the current trade set-up suggests the bulls to be holding a tight grip over the rally and hence demonstrate a higher possibility of reclaiming $180 in the first few days of June. As suggested in the above chart, the SOL price continues its trade within a symmetrical triangle and is currently holding above the local support zone between $155 and $160. The tight accumulation has occurred due to the equal participation of the bulls and bears and hence this suggests a huge price action could be on the horizon. Besides, the technicals suggest a notable change in the trend as the Gaussian channel just turned green, indicating the beginning of an upswing. Moreover, the price is closely ranging just below the upper bands of the channel and if they manage to break above the levels, a fresh upswing may begin. Secondly, the stochastic RSI has also reached below the lower threshold and could be preparing for a rebound, substantiating the bullish claim. Therefore, Solana’s (SOL) price continues to remain within bullish influence and hence a bullish breakout above $175 may be expected at the beginning of the second half of 2024. But in my heart of hearts I would like a solana at $170 and a wbt at $20, amen.
korofetova_mila
1,848,219
Primeiros Meses como Nômade Digital [PT-BR]
Introdução Estou vivenciando o período mais surpreendente e único de toda a minha vida....
0
2024-06-03T23:47:12
https://dev.to/andredarcie/primeiros-meses-como-nomade-digital-pt-br-42g
webdev, braziliandevs
## Introdução Estou vivenciando o período mais surpreendente e único de toda a minha vida. Tudo começou após meu aniversário de 30 anos, quando decidi me aventurar como nômade digital. Inicialmente, passei um tempo em Juiz de Fora, Minas Gerais, segui para Vitória, Espírito Santo, e agora estou em Salvador, Bahia. Estou aberto a explorar muitos outros destinos que a vida possa me reservar. É fantástica essa possibilidade de conhecer uma cidade, seus pontos turísticos, mas além disso, conhecer realmente como é o dia a dia, a rotina, as pessoas, os lugares, a cultura local, a forma de pensar, fazer amigos, as coisas boas e ruins, uma experiência antropológica. Como disse Abujamra, "Um periscópio sobre o oceano do social." O que mais me surpreendeu, no fim, foi que eu me conheci muito mais, pois me expus a novas pessoas sem medo e sem receio, dada a liberdade da minha nova vida, pude ser completamente eu. ## Motivação Percebi que, enquanto nos distraímos, a vida simplesmente acontece ao nosso redor. Constatei que passei quase toda a minha vida nos mesmos lugares, mantendo a mesma rotina. Morei grande parte desse tempo em minha cidade natal e, posteriormente, na cidade onde inicialmente exerci meu trabalho presencial. Ter a possibilidade de trabalhar remotamente de qualquer lugar com internet é um privilégio imenso. Basta colocar o notebook na mochila, roupas na mala de bordo, e seguir de coração aberto, sem destino. Viajar apenas durante as férias, duas vezes ao ano, não é suficiente para mim. A visão meramente turística, roteirizada e mecânica, não captura a essência de um lugar. Vivenciar o dia a dia é tão diferente; você se acostuma com o local, sente falta das ruas onde morava, dos amigos que fez, e das conversas profundas que teve com pessoas completamente diferentes que fizeram seus olhos brilharem. Construí meu lar com minhas coisas, meus bens, minhas plantas, flores, quadros, arte, livros e presentes de amigos. Mas, depois de construir tudo, nada é melhor do que destruir e reconstruir tudo de uma maneira completamente diferente. É como ser um hobbit que decide deixar o Condado. No Condado, temos a família, os amigos, as bebidas, o tabaco no cachimbo e o conforto. Olhar para a estrada sem ter certeza de nada, enfrentar os perigos do mundo – a jornada parece sombria e distante. Mas, assim como Bilbo, nunca me arrependi. Quando ele voltou, tinha histórias para escrever e nunca mais foi o mesmo. ## Como funciona? Acredito que o aspecto mais interessante para quem deseja iniciar ou avaliar a viabilidade desse projeto é poder fazê-lo com um amigo. Meu amigo e eu trabalhamos na mesma empresa e ambos temos a flexibilidade de trabalhar 100% remotamente, o que nos permite dividir o custo do Airbnb, que é o elemento mais caro e crucial. É essencial que o local escolhido esteja completamente mobiliado e pronto para morar, equipado com itens essenciais e, principalmente, uma internet confiável, além de uma mesa e cadeira adequadas para o trabalho. Todo esse ambiente precisa acomodar confortavelmente duas pessoas. Inicialmente, o Airbnb pode parecer caro, pois muitas pessoas o utilizam para estadias curtas. No entanto, quando você reserva por um período maior, como um mês ou dois, o valor diminui. Dividindo o custo entre duas pessoas, acaba saindo praticamente o mesmo que alugar um lugar sozinho, embora isso possa variar bastante. Para viajar de uma cidade para outra, usamos ônibus ou, para distâncias maiores, avião. Na cidade, utilizamos o Google Maps, TripAdvisor, TikTok e Instagram para explorar e conhecer pessoas, perguntando sobre lugares interessantes para visitar, pontos turísticos, restaurantes, passeios, parques, museus, festas e baladas. Usamos aplicativos como 99 e Uber para nos locomover. Carrego comigo uma mochila com o essencial para trabalhar: notebook, mouse, base para o notebook, carregador e fone de ouvido. Além disso, levo uma mala de bordo com todas as minhas roupas e itens pessoais. O restante, como itens consumíveis, compro na cidade onde estou. ## Experiências ### Juiz de Fora - Minas Gerais Até mesmo a casa em Juiz de Fora, com o livro da Rita Lee, me deixou totalmente apegado. Aquela casa parecia guardar a história de uma família que viveu grandes momentos. E que delícia foi experimentar a comida local! O show do Sepultura foi emocionante, a roda punk, e beber na lâmpada foi uma experiência única e divertida. Fumar charuto e saborear a comida típica foram prazeres que nunca esquecerei. Visitar o Bar Viking e participar do sorteio da roleta foi uma aventura emocionante. Explorar o Museu Mariano Procópio foi fascinante; os jardins, o casarão e o museu com suas estátuas em estilo clássico, obras de arte e animais empalhados foram incríveis. O Museu da História do Brasil, com o famoso quadro do Tiradentes, foi uma viagem no tempo. Provar o melhor bacalhau com nata da vida, em um restaurante construido dentro de uma pedra gigante com agua escorrendo, depois pra ir embora se perder nos becos. Visitar o Museu do Poeta Murilo Mendes e o centro histórico foi enriquecedor. Subir no Morro do Imperador e apreciar a vista de toda a cidade, ver o Cristo diferente, comer um sorvete delicioso, seguir pela trilha e depois voltar. ### Vitoria - Espírito Santo Em Vitória, foi a primeira vez que vi a praia e senti a areia sob meus pés. Comer caranguejo foi uma experiência desafiadora e divertida; passei horas tentando e até fiquei sujo, mas valeu a pena! Sentir o cheiro da maresia todos os dias era revigorante, até a água do banho parecia diferente. Saborear carne de peixe fresca, dançar muito no Vitória Pub, várias vezes com amigos e até na despedida, foi maravilhoso. Ver tartarugas pequenas, médias e até gigantes no Projeto Tamar. Passava as noites sentado na praia, observando os aviões passarem, o mar, as estrelas no céu aberto, sentindo a brisa suave passar pelo meu corpo. Foram momentos de paz que nunca havia sentido antes. Visitei o Convento da Penha, com uma vista indescritível e um lugar antigo cheio de história. No pico, dava para ver várias praias e toda a cidade, tanto Vitória quanto Vila Velha. Dancei muito, comi muito e ri muito. Vi a estatua de Yemanjá, vi as ondas e a ponte gigante e curvada. Experimentei pela primeira vez a pizza oficialmente napolitana, andei de patinete elétrico, saboreei moqueca, chopp de sabores variados, café e chocolate amargo, frutos do mar, ostras, e um sofisticado macarrão com vinho. Fui a uma festa de aniversário no parque, caminhei pelas ruas sem destino à noite, conheci pessoas únicas e fui a um restaurante colorido e artístico. Visitei o Museu de Arte do Espírito Santo, vi os prédios históricos do centro, os monumentos, tomei canelinha e dancei com amigos antes de me despedir. Peguei um avião pela primeira vez na vida. Cada momento foi inesquecível e Vitória se tornou um lugar especial no meu coração. Ao caminhar pelas praias e sentir a areia entre os dedos, olho para o horizonte e me dou conta de como sou afortunado por estar aqui, por viver este momento. ### Salvador - Bahia Cheguei em Salvador e fui diretamente para o Pelourinho. Lá, vi capoeira, casas coloridas, museus históricos e a Igreja de São Francisco, que foi como parar no tempo. Nunca vi tanto ouro e tanta arte contida em um só lugar. As inscrições em latim "a morte vem para todos" me marcaram profundamente. Sem dúvida, é a igreja mais bonita que já vi na vida, cheia de história. Experimentei carne de sol e conheci a primeira sorveteria do Brasil. Visitei o lugar onde Michael Jackson dançou, vi o Elevador Lacerda e fui ao Bar do Preto. A cada dia que passa, sinto meu coração bater mais forte por Salvador. Estou encantado, apaixonado, transformado. Este lugar, com suas histórias e sua gente, está me mostrando um novo jeito de viver, mais leve, mais alegre, mais pleno. Provei o famoso Acarajé da Cira, fui à Praia da Barra, visitei o Museu Náutico e assisti ao pôr do sol. Fui ao farol pela primeira vez, vi canoas e navios, andei de caiaque, comi açaí com chocolate, observei a praia lotada e a alegria do povo, ao lado de um carnaval vibrante. Visitei a casa de Jorge Amado e vi seus amigos poetas, artistas, músicos e diretores de cinema. Ali, percebi que uma parte significativa da cultura brasileira foi criada. Assisti ao meu primeiro jogo de futebol oficial, vi a torcida gritar, chorar, comemorar e reclamar, cantar em sincronia. Comi carne de sol com farofa, sentei ao lado de uma estátua e saboreei o melhor vatapá da minha vida. Cada esquina uma nova aventura. O cheiro do acarajé fritando na rua, as cores vibrantes das vestes baianas, o som dos tambores que ecoam nas ladeiras do Pelourinho – tudo isso me faz sentir mais conectado com as raízes do nosso país. A energia de Salvador é contagiante e vou continuar por aqui por um bom tempo. ## Conclusão Está valendo a pena? Já bateu o arrependimento? Sinto saudades da minha família e amigos, mas tenho um medo profundo de, em outra dimensão, eu ter decidido ficar. Já sou uma pessoa diferente; vi e conheci coisas que nunca imaginaria que existiam. Amei sair para caminhar depois do trabalho na praia em Vitória, amei os amigos que fiz lá, os museus e as histórias, as noites. Agora, estou completamente apaixonado por Salvador. Que brasileiro sou eu que não conhecia Salvador, a primeira capital do Brasil! O Brasil é extremamente rico em cultura e diversidade; estou de coração aberto, nunca senti essa paixão arder dentro de mim de maneira tão intensa, de estar vivo e poder aproveitar tudo o que a vida oferece. Agradeço imensamente por ser um nômade. Ser capaz de explorar diferentes cantos do Brasil, cada lugar com suas particularidades e belezas únicas, é um privilégio inestimável. Compartilho todas essas experiências e aprendizados no meu Instagram [@andre.darcie](https://www.instagram.com/andre.darcie/). Sinto-me profundamente grato e animado para continuar essa jornada, descobrindo e vivendo intensamente cada momento. Muito obrigado pelo seu tempo e atenção em ler até aqui. Espero que este texto tenha te motivado e encantado de alguma forma. Sinta-se à vontade para perguntar qualquer coisa! 😊
andredarcie
1,875,547
Project Stage 1: Preparation(part-2)
Hiiii peeps!! I am back with another part for our project stage -1 called preparation and in this...
0
2024-06-03T23:43:47
https://dev.to/yuktimulani/project-stage-1-preparationpart-2-3oon
assembly, passes, argumentparsing, diagnosticdumps
Hiiii peeps!! I am back with another part for our project stage -1 called preparation and in this stage we will continue with Argument Parsing. So without wasting any time let's get started!! ## Task: Find the code that controls the argument parsing. Add a dummy argument and experiment with messages for the user that describe how and when that argument can be used. Argument parsing in GCC is the process where the compiler interprets the command-line options provided by the user to control the compilation process. This involves reading the arguments, validating them, and setting internal flags or configurations based on these options. Now how are we going to h=find the code that controls argument parsing. Remember where the gcc code base is? After installing and building gcc you will se a directory in the home directory called gcc and in that directory we have another directory called gcc , here is the code base and also the key file needed for argument parsing called "common.opt". So the address of the file will be `gcc/gcc/common.opt`. Below are the steps to add a dummy argument. 1. Define a dummy argument in common.opt The common.opt file defines the command-line options available to GCC. Each option has a specific format and fields that describe its behavior. Open common.opt and add a new line for your dummy argument. ``` fdummy-arg Common Report Dummy argument for testing ``` The fields here are: - fdummy-arg: The name of the argument (e.g., -fdummy-arg). - Common: Indicates that this option is available across different languages. - Report: The category of the option. - The last line provides a brief description. And this is were I started doubting my skills and knowledge. I felt like there is biiiig hole in my knowledge somewhere because the things after this step everything started going wrong. According to my research you need to implement your argument in the `gcc.cc` and I did the same but all my builds kept on failing. So, for now I will keep this task on the side to rethink it with a fresh mind and move on to our other tasks. 😔 ## Task:Find out where argument information is stored and how it can be accessed in code. Argument information is typically stored in structures like `cl_decoded_option`and managed in arrays such as `decoded_options`.You can access the argument information in your pass or other parts of the GCC codebase by iterating over these arrays. In my opinion the below code should work if the your new dummy options are working unlike mine. 😞 ``` for (int i = 0; i < decoded_options_count; i++) { if (strcmp(decoded_options[i].opt, "my-dummy-option") == 0) { // Handle the option } } ``` ## Task: Find out how dumps are produced during the compilation passes (in particular, during the tree passes). Become familiar with producing and reviewing these dumps. Create a dummy pass that produces a useful diagnostic dump. Dumps are usually produced by functions that print the intermediate representation of the code to files. These functions are often called within passes.Dumps in GCC are a powerful feature used for debugging and understanding the compilation process. They provide intermediate representations of the code at various stages of compilation. ### Enabling Dumps To enable dumps when compiling a program, use the -fdump options. These options control the generation of dump files for various stages. **Basic Usage** ` gcc -fdump-tree-all -c your_program.c ` **Specific Dumps:** Tree Dumps: ``` -fdump-tree-original: Dump the original AST. -fdump-tree-gimple: Dump the GIMPLE representation. -fdump-tree-optimized: Dump the optimized AST. ``` RTL Dumps: ``` -fdump-rtl-all: Dump all RTL stages. -fdump-rtl-expand: Dump RTL after expansion. -fdump-rtl-optimized: Dump the optimized RTL. ``` Control Flow Graph Dumps: ``` -fdump-tree-cfg: Dump the control flow graph for trees. -fdump-rtl-cfg: Dump the control flow graph for RTL. ``` ## Reflections ### What I Learned Embarking on the project to understand and modify the GCC codebase has been a profound learning experience. Despite the setbacks, I gained valuable insights into how GCC handles argument parsing and compilation passes. The intricate nature of a compiler like GCC, with its vast and complex codebase, highlighted the importance of having a structured approach when making modifications. ### Challenges The primary challenge I faced was in modifying the argument parsing mechanism. While adding a dummy argument to common.opt seemed straightforward, implementing the actual handling of this argument in gcc.cc proved difficult. The build process failed multiple times, indicating deeper issues with my approach or possibly gaps in my understanding of the code structure. ### Complexity of GCC Codebase: The sheer size and complexity of GCC's codebase made navigation and pinpointing the exact locations for modifications challenging. Each file and function has interdependencies that are not immediately apparent. ### Build Failures: The build failures were particularly frustrating as they often stemmed from small, seemingly insignificant mistakes. Error messages were sometimes cryptic, requiring extensive research to decode and understand. ## #Understanding GCC Internals: While I had a theoretical understanding of compilers, delving into GCC’s internals was a different ball game. The use of various data structures and the flow of data between them was more complex than anticipated. ## Knowledge Gaps This project highlighted several gaps in my knowledge: ### Deep Understanding of Compiler Theory: Although I had a basic understanding of compiler theory, I realized I needed a deeper comprehension, especially regarding GCC's specific implementation of these theories. ### Debugging and Troubleshooting Build Issues: My skills in debugging complex build issues need improvement. I often found myself stuck, unsure how to proceed after encountering a build error. ### Navigating Large Codebases: Efficiently navigating and understanding large codebases like GCC is a skill I need to develop further. This includes being able to track down the relationships between different parts of the code and understanding their interactions. ## How I Plan to Address These Gaps ### Studying Compiler Theory: I plan to delve deeper into compiler theory through academic resources and online courses. Understanding the foundational principles at a deeper level should help me grasp GCC's implementation better. ### Improving Debugging Skills: I will practice debugging in different environments and with different types of software projects. Additionally, learning to use advanced debugging tools and techniques will be crucial. ### Exploring Smaller Compiler Projects: Before jumping back into GCC, I will explore smaller, simpler compiler projects. This will allow me to build my skills and confidence in a less overwhelming environment. ### Engaging with the Community: I will become more active in the GCC community, seeking advice and learning from experienced contributors. This can provide practical insights and support as I continue to work on GCC. ## Tasks I Found Most Attractive Despite the challenges, I found the process of attempting to add new features to be the most engaging. Specifically, I enjoyed: ### Coding and Experimentation: Writing and experimenting with code, even when it didn't work out, was a rewarding challenge. The process of debugging and understanding errors, though difficult, was intellectually stimulating. ### Understanding the Compilation Process: Learning about the different passes in the compilation process and how GCC manages these was fascinating. It provided a clearer picture of how source code is transformed into executable programs. ## Conclusion While this part of the project didn't yield the results I hoped for, it was a significant learning experience. I now have a clearer idea of my strengths and the areas I need to improve. Moving forward, I am better prepared to tackle similar challenges, armed with the knowledge and experience gained from this attempt. So that is all for this failed series of Project Stage-1. Below are some sources that might help you when you get stuck up like me. I hope you can make a good use of them. ## Resources [GCC github-mirror](https://github.com/gcc-mirror/gcc) [GCC Documentation](https://gcc.gnu.org/onlinedocs/) [GCC Internals Mannual](https://gcc.gnu.org/onlinedocs/gcc-4.5.0/gccint/) [Installing GCC](https://gcc.gnu.org/install/) Thank you for reading even if it was a failed attempt. Until next time Happy Coding!!! 🙋‍♀️
yuktimulani
1,875,958
Optimize web content with html video tag
The &lt;video&gt; tag allows you to embed videos directly into your web pages, enhancing user...
0
2024-06-03T23:39:44
https://dev.to/hussein09/optimize-web-content-with-html-video-tag-no8
html, webdev, beginners, programming
The `<video>` tag allows you to embed videos directly into your web pages, enhancing user experience and interactivity. The feature adds playback controls such as play, pause, and volume. Have you used the `<video>` tag with different source formats in your web projects? for **Example** ``` <!DOCTYPE html> <html> <title></title> <body> <video width="320" height="240" controls> <source src="movie.mp4" type="video/mp4"> <source src="movie.ogg" type="video/ogg"> </video> <body> </html> ``` https://github.com/hussein-009/
hussein09
1,875,927
Sleepy Pikachu🥱 | Frontend Challenge June | CSS Art
This is a submission for Frontend Challenge v24.04.17, CSS Art: June. Inspiration The...
0
2024-06-03T23:12:45
https://dev.to/dhrutisubham03/sleepy-pikachu-4iha
frontendchallenge, devchallenge, css
_This is a submission for [Frontend Challenge v24.04.17](https://dev.to/challenges/frontend-2024-05-29), CSS Art: June._ ## Inspiration The June Prompt reminded me of beaches in no time(stole the beach idea from glam up challenge). And I deep dived pinterest to find some cool(and sleepy---because I'm posting this at 4:25am in the morning) pixel art that I could make up in CSS. ## Demo Here's the final result of my night-long strive (●'◡'●) (_View in 0.5x_) {% codepen https://codepen.io/dhrutisubham/pen/JjqNWvd %} ## Journey The journey of this art is quite straightforward. I got inspired by the [Previous CSS Art winner](https://dev.to/floscode/the-frontend-challenge-bananas-are-the-superior-fruit-42n3) who was inspired by a [Medium Blog](https://medium.com/@FlangerHanger/create-your-own-css-pixel-art-with-two-divs-box-shadow-33653e3d3228) who was inspired by a [YouTube Video](https://www.youtube.com/watch?v=LjlHcmEclFE). And I wanted to try to make pixel art using CSS(and I make some on paper and paste it around in my room too) ![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/8bndh8uq77nw9m6vsu3h.jpg) Then I went to the best place to steal others' artwork---Pinterest 😛 I stumbled upon a cute **Pikachu**, who looked no less sleepy than I was. Here are the images I used to make this art: [Pikachu🥰](https://in.pinterest.com/pin/363102788723807007/) [Beach🏖️](https://in.pinterest.com/pin/108508672265164444/) I wish I added some animation(but that would lead to more sleepless nights, and my mother getting disappointed with me missing breakfast everyday 😹) Here's a Pikachu Meme and Cute Pikachu Photo to help me get more reactions on this post. ![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/hog4mf1w66dmeyy5kvnd.png) ![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/q6ll7nqj303u0qx755bn.gif) Peace Out! ✌️
dhrutisubham03
1,875,925
Controlling user auth flow with Lambda & Cognito (pt2)
Last post, we wrote the code for our preAuth trigger that would handle the count of attempts to...
0
2024-06-03T23:06:11
https://dev.to/jodamco/controlling-user-auth-flow-with-lambda-cognito-pt2-plc
aws, cognito, lambda, javascript
[Last post](https://dev.to/jodamco/controlling-user-auth-flow-with-lambda-cognito-28k9), we wrote the code for our preAuth trigger that would handle the count of attempts to login. The idea now is to reset the counter after the login is successful since we want all the atempts to be available when the user come to login for another session. The code for the postAuth trigger is way simpler than the one for the preAuth. Let's dive into it ``` module.exports.postAuthTrigger = async (event) => { await this.clearLoginAttempts(event) return event } exports.clearLoginAttempts = async (event) => { const updateParams = { UserAttributes: [ { Name: 'custom:login_attempts', Value: '0', }, ], UserPoolId: event.userPoolId, Username: event.userName, } await cognitoService.adminUpdateUserAttributes(updateParams).promise() } ``` To reset the login attempts, we just need to update the same counter we used in the preAuth trigger, which is stored into the prop 'custom:login_attempts'. We can do it by calling the _adminUpdateUserAttributes_ function from the cognito API. One other important thing to mention is that we need to return the 'event' object that we receive when the lambda is called since cognito will expect to have it to continue with the auth flow. After creating the lambdas, we need to setup the cognito accordingly with the needed property (login_attempts) and the setup for the triggers. ![Cognito console on AWS](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/d3zhbcuw2kfcswi8nnhl.png) First you may need to create your user pool. To do so you start by signing in to the AWS Management Console and navigating to Amazon Cognito. Click "Manage User Pools" and then "Create a user pool". Along the wizard to create the user pool you will notice an option to create custom attributes. Here you will create your 'login_attempts' attribute. You will notice that even though we set the name as 'login_attempts', cognito will ask you to access it by calling 'custom:login_attempts'. That's the default for custom attributes on cognito ![Custom attribute on cognito wizard](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/ibplzeewma3iiltw6ba7.png) To finish the creation of the user pool, follow the steps and after review your configurations and click "Create pool." Now, you just simply need to attach the created lambdas to your cognito. Open the created user pool and search for 'User pool properties', there you'll find the lambda trigger setup. Click on 'Add lambda trigger'. ![Lambda trigger setup](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/5qwq50f5ub953uhth02y.png) You will notice a few different types of triggers. We will use Authentication triggers. Select the Authentication option, the preAuth trigger and attach the preAuthTrigger lambda you created. Then repeat the process but to attach the postAuthTrigger lambda to postAuth trigger. And it's done! Now you have a cognito user pool setup to block user after _n_ unsuccessful attempts of login! To test it out, you may integrate cognito with some web or mobile app using the Amplify SDK. You can also use this same triggers to add other features, such as saving last login from the user or triggering other services after the login.
jodamco
1,875,924
How AI is revolutionizing a developer’s life
Artificial intelligence (AI) is not just a buzzword; It’s a transformative force reshaping...
0
2024-06-03T23:04:07
https://dev.to/goumricom/how-ai-is-revolutionizing-a-developers-life-24n2
developerlife, ai, developer
Artificial intelligence (AI) is not just a buzzword; It’s a transformative force reshaping industries, and software development is no exception. As a developer, you wonder how AI can impact your day-to-day work and long-term projects. This article takes a deeper look at the practical application of AI in the world of software development, highlighting its benefits and potential challenges. ## 1. Introduction The integration of AI into software development is creating a new paradigm for how developers approach coding, debugging, and project management. AI tools are designed to automate repetitive tasks, increase code quality, and provide insights that can significantly reduce development time. ## 2. Enforcement of AI One of the main areas where AI makes a mark is in writing code. Tools like GitHub Copilot powered by OpenAI Codex are changing the coding process. Automated code suggestions: AI tools can assess and suggest code snippets as you write, making coding faster and more efficient. Code completion: AI can complete all code blocks, reducing the chances of syntax errors and saving time on boilerplate coding. Language translation: AI can help translate code from one programming language to another, making multilingual work easier. ## 3. AI in Code Review Code reviews are essential for maintaining code quality and ensuring best practices. AI-powered code review tools like DeepCode and Codacy are transforming this process. Automated Review: These tools can automatically review code for common issues, ensuring consistency and adherence to coding standards. Pattern Recognition: AI can recognize patterns in code that may lead to potential bugs, security vulnerabilities, or performance bottlenecks. Continuous Learning: AI systems continuously learn from previous code reviews, improving their accuracy and relevance over time. ## 4. AI in Bug Detection and Fixing Finding and fixing bugs is one of the most time-consuming tasks in software development. AI is streamlining this process through advanced bug detection tools. Predictive Analysis: AI can predict potential bugs by analyzing code patterns and historical data. Automated Testing: Tools like Test.ai can create and execute test cases automatically, identifying issues early in the development cycle. Self-Healing Code: AI systems can sometimes suggest or even implement fixes for detected bugs, reducing downtime and manual intervention. ## 5. AI in Project Management Project management is crucial for the successful delivery of software projects. AI tools like Jira and Asana are enhancing project management with AI capabilities. Task Automation: AI can automate repetitive tasks such as task assignment and progress tracking. Resource Optimization: AI algorithms can predict resource requirements and optimize their allocation based on project needs. Risk Management: AI can assess project risks by analyzing historical data and current project metrics, providing early warnings and mitigation strategies. ## 6. AI in Learning and Skill Development Continuous learning is vital for developers to keep up with rapidly evolving technologies. AI is playing a significant role in personalized learning and skill development. Personalized Learning Paths: AI can create customized learning paths based on your current skill set and career goals. Adaptive Learning: AI-powered platforms like Coursera and Udacity offer adaptive learning experiences, adjusting the difficulty and pace based on your progress. Skill Assessment: AI tools can assess your coding skills through real-time code analysis and provide feedback to help you improve. ## 7. Conclusion AI is undeniably transforming the life of developers, making their work more efficient, accurate, and less monotonous. By automating repetitive tasks, enhancing code quality, and providing deep insights, AI tools are becoming indispensable in the software development lifecycle. As AI continues to evolve, its integration into development workflows will only deepen, opening new avenues for innovation and efficiency. Embracing AI is not just about adopting new tools; it's about rethinking how we approach software development. By leveraging AI's capabilities, developers can focus more on creative problem-solving and innovation, ultimately leading to better software and a more fulfilling development experience.
goumricom
1,875,923
JavaScript Promises: Still Struggling with it? Here's your solution!
Overview In this article, you will understand more about Promises methods in JavaScript...
0
2024-06-03T23:00:47
https://dev.to/godinhojoao/still-struggling-with-javascript-promises-kdh
javascript, node, webdev, programming
## Overview - In this article, you will understand more about Promises methods in JavaScript and the differences between them. - This article is for those who already know JavaScript, and want to improve their knowledge about JavaScript Promises. ## Table of Contents - [What is JavaScript Promise object](#what-is-javascript-promise-object) - [Promise chaining vs Promise nesting](#promise-chaining-vs-promise-nesting) - [Promise methods - .all, .allSettled, .race, and .any](#promise-methods--all-allsettled-race-and-any) ## What is a JavaScript Promise object? - An object representing the eventual completion or failure of an asynchronous operation. - For example: Requesting an API the GitHub repositories of someone. - It was created to avoid callback hell and make the way of handling asynchronous in JavaScript code easier. - A promise object has one of these three states: - pending: initial state - resolved: the operation was successful executed - rejected: operation failed - Below there is a simple example of a Promise in JS: ```javascript const myPromise = new Promise((resolve, reject) => { // Asynchronous task: setTimeout(() => { resolve("Promise resolved after 1 second"); }, 1000); }); // using .then(), .catch(), and .finally() myPromise .then((successValue) => console.log(successValue)) // .then to handle success .catch((error) => console.error(error)); // .catch to handle error .finally(() => console.log('Process completed')); // Handle both success and error cases // using try/catch and async/await try { const successValue = await myPromise; // your code will be here until the process ends console.log(successValue); } catch (error) { console.error(error); } finally { console.log('Process completed.'); // This will run regardless of success or error } ``` ## Promise Chaining vs Promise nesting? - **Promise chaining**: Handling multiple asynchronous operations in which each `.then()` method returns a new Promise, allowing the next `.then()` to be called and making your code more **readable**. ```javascript function fetchUser(userId) {} // it returns a promise function fetchPosts(userId) {} // it returns a promise function fetchComments(postId) {} // it returns a promise // Start the promise chain fetchUser(1) .then((user) => { console.log("User:", user); return fetchPosts(user.id); // Return the next promise }) .then((posts) => { console.log("Posts:", posts); return fetchComments(posts[0].id); // Return the next promise }) .then((comments) => { console.log("Comments:", comments); }) .catch((error) => { console.error("Error:", error); }); ``` - **Promise nesting**: Placing one Promise inside another's `.then()` method. This can lead to more indented code and can make it **harder to read**, especially when dealing with multiple asynchronous operations. ```javascript function fetchUser(userId) {} // it returns a promise function fetchPosts(userId) {} // it returns a promise function fetchComments(postId) {} // it returns a promise // Start the promise nesting fetchUser(1) .then((user) => { console.log("User:", user); return fetchPosts(user.id).then((posts) => { console.log("Posts:", posts); return fetchComments(posts[0].id).then((comments) => { console.log("Comments:", comments); }); }); }) .catch((error) => { console.error("Error:", error); }); ``` ## Promise methods - .all, .allSettled, .race, and .any - ## Promise.all() - MDN Web Docs: "The Promise.all() static method takes an iterable of promises as input and returns a single Promise. This returned promise fulfills when all of the input's promises fulfill (including when an empty iterable is passed), with an array of the fulfillment values. **It rejects when any of the input's promises rejects, with this first rejection reason.**" - This highlighted phrase is one of the most important aspects to consider when using Promise.all(). ```javascript const promise1 = Promise.resolve(3); const promise2 = 42; const promise3 = new Promise((resolve, reject) => { setTimeout(resolve, 100, "foo"); }); Promise.all([promise1, promise2, promise3]).then((values) => { console.log(values); }); // Expected output: Array [3, 42, "foo"] ``` - ## Promise.allSettled() - MDN Web Docs: "The Promise.allSettled() static method takes an iterable of promises as input and returns a single Promise. This returned promise fulfills when all of the input's promises settle (including when an empty iterable is passed), with **an array of objects that describe the outcome of each promise.**" - This highlights the most useful aspect when you need to manage each of your promises independently, handling success cases and errors individually for each promise inside Promise.allSettled(). ```javascript const promise1 = Promise.resolve(3); const promise2 = new Promise((resolve, reject) => setTimeout(reject, 100, "foo") ); const promises = [promise1, promise2]; Promise.allSettled(promises).then((results) => results.forEach((result) => console.log(result.status)) ); // Expected output: // "fulfilled" // "rejected" ``` - ## Promise.race() - Returns when the first promise settles, (error or success). - Imagine you're waiting for responses from multiple servers. You use Promise.race to get the response from the server that responds the quickest. ```javascript const promise1 = new Promise((resolve, reject) => { setTimeout(resolve, 500, "one"); }); const promise2 = new Promise((resolve, reject) => { setTimeout(resolve, 100, "two"); }); Promise.race([promise1, promise2]).then((value) => { console.log(value); // Both resolve, but promise2 is faster }); // Expected output: "two" ``` - ## Promise.any() - Returns when the first promise resolves (success). If all promises fails it went to `.catch()`. - You're fetching data from multiple APIs, but you're interested in the data from the first API that responds successfully. You use Promise.any to handle this scenario. ```javascript const fetchFromAPI1 = fetch("https://api.example.com/endpoint1"); const fetchFromAPI2 = fetch("https://api.example.com/endpoint2"); const fetchFromAPI3 = fetch("https://api.example.com/endpoint3"); Promise.any([fetchFromAPI1, fetchFromAPI2, fetchFromAPI3]) .then((response) => response.json()) .then((data) => { console.log("Received data from the first successful API call:", data); }) .catch((error) => { console.error("All API calls failed:", error); }); ``` ## References - [MDN - Using promises](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Using_promises) - [Javascript.info - Promise chaining](https://javascript.info/promise-chaining) - [w3schools - JavaScript Promises](https://www.w3schools.com/js/js_promise.asp) ## Thanks for Reading! - Feel free to reach out if you have any questions, feedback, or suggestions. Your engagement is appreciated! ## Contacts - You can find this and more content on: - [My website](https://godinhojoao.com/) - [GitHub](https://github.com/godinhojoao) - [LinkedIn](https://www.linkedin.com/in/joaogodinhoo/) - [Dev Community](https://dev.to/godinhojoao)
godinhojoao
1,875,916
Opt-In VS Opt-Out
Consideration In our digital world, consideration for user consent is paramount. Two...
0
2024-06-03T22:58:13
https://dev.to/cxdezign/opt-in-vs-opt-out-2c48
ethics, privacy, practices, compliance
## Consideration In our digital world, consideration for user consent is paramount. Two primary methods for obtaining consent are **opt-in** and **opt-out**. Understanding these concepts is crucial for developers aiming to balance engagement, trust, and compliance with privacy regulations. ## Opt-In **Opt-in** requires users to explicitly agree to participate. This method is proactive, ensuring that users are fully aware and have offered their consent knowingly. ### Pros: - **Transparency**: Users are informed and give explicit consent. - **Compliance**: Meets strict regulatory standards (e.g., GDPR). - **Trust**: Builds a positive relationship with users. ### Cons: - **Engagement**: Fewer users may participate due to the required extra steps. ## Opt-Out Opt-out assumes user consent by default, requiring users to take action to withdraw from participation. ### Pros: - **Engagement**: More users participate by default. - **Simplicity**: Easier for users who might overlook consent options. ### Cons: - **Intrusiveness**: Users might perceive their privacy or choice as compromised. - **Risks**: May not meet stricter privacy regulations and compliance. ## Developer-conscious mindset Adopting a developer-conscious mindset means prioritising ethical considerations and user experience when implementing consent mechanisms. **User-Centric Design:** - Design with the user's best interests in mind. - Ensure consent requests are clear and non-intrusive. **Compliance and Ethics:** - Stay updated with relevant privacy laws and regulations. - Implement consent methods that respect user privacy and choice. **Transparency:** - Provide clear information on what users are consenting to. - Offer easy ways for users to change their preferences. **Feedback and Improvement:** - Continuously gather user feedback to refine consent processes. - Stay open to improvements that enhance user trust and satisfaction. ## Conclusion Choosing between opt-in and opt-out methods requires balancing user experience, engagement rates, and regulatory compliance. By adopting a developer-conscious mindset, you ensure that your approach to user consent is ethical, transparent, and user-friendly, fostering trust and long-term engagement.
cxdezign
1,875,920
Handle state management and concurrency issues in Terraform and Ansible?
1 Terraform state management Terraform utilizes a state file to store the current state of...
0
2024-06-03T22:45:47
https://dev.to/vaibhavhariaramani/handle-state-management-and-concurrency-issues-in-terraform-and-ansible-2dp8
## 1 Terraform state management Terraform utilizes a state file to store the current state of the infrastructure, which includes the attributes and dependencies of the resources. This file is essential for Terraform to perform operations such as plan, apply, and destroy; however, it can also be a source of problems when working in a team or across multiple environments. Some of these issues include keeping the state file in sync with the actual infrastructure, avoiding conflicts and corruption of the state file, managing sensitive data in the state file, and scaling the state file for large or complex infrastructures. To address these challenges, Terraform offers several features and best practices such as using remote backends to store and access the state file securely and reliably, utilizing state locking to prevent concurrent modifications of the state file, utilizing workspaces to isolate and manage multiple state files, using modules and variables to reuse and customize configurations, utilizing outputs and data sources to share information between configurations, and using sensitive attributes and encryption to protect sensitive data in the state file. ## 2 Ansible state management Ansible does not use a state file to manage the infrastructure, but instead relies on the desired state defined in the playbooks and roles. This means that Ansible will only make changes to the hosts if they are not already in the desired state, and that Ansible will describe what to do, rather than how to do it. Some of the advantages of this stateless approach are no need to sync or backup the state file, no risk of conflicts or corruption of the state file, no exposure of sensitive data in the state file, and easier scalability and parallelization of execution. However, there are some drawbacks such as difficulty tracking and auditing changes made by Ansible, dependency on target hosts' connectivity and availability, lack of native support for dependencies and dependencies resolution, and complexity managing dynamic and heterogeneous infrastructures. To address these drawbacks, Ansible offers features like facts and inventory gathering, handlers and notifications triggering actions based on task results, tags and conditions controlling execution flow and scope, roles and collections structuring reusable configurations, and vault and secrets encrypting sensitive data. ## 3 Terraform concurrency issues Terraform concurrency issues happen when multiple users or processes try to modify the same resources simultaneously, which can lead to inconsistent or unexpected outcomes such as two users attempting to create or delete the same resource, or one user trying to update a resource that another user has already modified. These issues can be caused by lack of coordination, communication, visibility, or isolation of resources. To prevent or resolve these issues, Terraform offers features and best practices such as remote backends and state locking for single user access, workspaces and modules for organizing resources, terraform plan and apply for previewing changes, terraform import and refresh for updating existing resources, and terraform taint and untaint for marking resources for recreation. ## 4 Ansible concurrency issues Ansible concurrency issues can arise when multiple users or processes attempt to apply the same or conflicting desired states to the same target hosts simultaneously, potentially leading to inconsistent or unexpected outcomes. Such issues can be caused by a lack of coordination or communication between users and processes, lack of visibility or feedback on the desired and actual states of target hosts, and lack of isolation or segregation of the target hosts. To prevent or resolve Ansible concurrency issues, Ansible offers features and best practices such as inventory groups and variables for separating and organizing target hosts, ansible-playbook --check and ansible-playbook --diff for previewing and comparing changes before applying them, ansible-pull and ansible-pull --purge for pulling and applying the latest configurations from a remote repository, ansible-galaxy and ansible-galaxy --force for installing or updating roles and collections from a remote source, and ansible-lint and ansible-test for validating and testing playbooks and roles.
vaibhavhariaramani
1,875,918
Setting Up GitHub Environment Configurations in Neovim on Linux
TOC Introduction gitconfig zshrc and bashrc Configurations lazygit Lazygit Setup and...
0
2024-06-03T22:43:30
https://dev.to/gokayburuc/setting-up-github-environment-configurations-in-neovim-on-linux-5499
git, github, neovim, vim
## TOC - [Introduction](#introduction) - [gitconfig](#gitconfig-configurations) - [zshrc and bashrc Configurations](#zshrc-and-bashrc-configurations) - [lazygit](lazygit) - [Lazygit Setup and Configurations](#lazygit-setup-and-configurations) - [Lazygit Usage](#lazygit-usage) ## Introduction For those involved in Open-Source projects, dealing with frequent commits can be tedious, especially when prompted for a username and password during push/pull requests on Git. Neovim users can streamline their git push and pull operations by configuring it to use `GIT_USERNAME` and `GIT_ACCESS_TOKEN` with just a click. This article will guide you through the initial setup needed for this. #.gitconfig configurations Firstly, let's incorporate the following helper function into our `.gitconfig` file to globally recognize `GIT_USERNAME` and `GIT_ACCESS_TOKEN`. In Linux, navigate to the `/home/` directory using `cd` to access $HOME and create or edit the `.gitconfig` file. If you already have a config file, append the following helper function under `[credential]` : ```bash # HOME cd # open .gitconfig file nvim .gitconfig ``` In the opened file, create a new configuration field like this: ```git [user] email = ....@yandex.com name = G... B.... [credential] helper = "!f() { echo \"username=${GIT_USERNAME}\"; echo \"password=${GIT_ACCESS_TOKEN}\"; }; f" [core] editor = nvim ``` Then, paste the helper function provided below it and save the file. When using the shell with the helper function, system-wide variables named 'GIT_USERNAME' are automatically called in the username field and 'GIT_ACCESS_TOKEN' in the access_token field. > Helper Function: A helper function is a function that assists in the computation of another function. It improves code readability by performing specific calculations and giving them descriptive names. ## zshrc and bashrc configurations ![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/3hl9bqliwsz744lny9ll.png) **Extras**: - [zsh](https://github.com/ohmyzsh/ohmyzsh/wiki/Installing-ZSH) - [OHMYZSH](https://ohmyz.sh/) Depending on your system's shell, add the following two lines to its configuration file. ```bash # HOME directory cd # if you are using zsh nvim .zshrc # if you are using bash nvim .bashrc ``` Anywhere in your .zshrc or .bashrc file, add the following variables and replace <your-access-token> with the `GIT_ACCESS_TOKEN` you received from Github. ```zsh GIT_USERNAME="<your-username>" GIT_ACCESS_TOKEN="<your-access-token>" ``` ## Lazygit Lazygit is a dashboard and Git manager that simplifies all Git-related operations onto one screen. It streamlines tasks like commit, file management (add/remove), ignore, merge, branch, pull/push, and more into a user-friendly interface. ![lazygit](https://user-images.githubusercontent.com/1813121/87866391-79fcfe00-c93e-11ea-94a9-204947de1b39.gif) ## Lazygit Setup and Configurations Astro.nvim users are encouraged to integrate it with 'lazygit' installed on their system. Follow the installation steps provided in the links below if you haven't already. - [AstroNvim - Official Website](https://astronvim.com/) - [Github - Lazygit.nvim](https://github.com/kdheepak/lazygit.nvim) - [Github - Lazygit](https://github.com/jesseduffield/lazygit) If you're using the 'Lazy' package manager in Neovim, install it with the following line of code: ```lua -- nvim v0.8.0 return { "kdheepak/lazygit.nvim", cmd = { "LazyGit", "LazyGitConfig", "LazyGitCurrentFile", "LazyGitFilter", "LazyGitFilterCurrentFile", }, -- optional for floating window border decoration dependencies = { "nvim-lua/plenary.nvim", }, -- setting the keybinding for LazyGit with 'keys' is recommended in -- order to load the plugin when the command is run for the first time keys = { { "<leader>lg", "<cmd>LazyGit<cr>", desc = "LazyGit" } } } ``` ## Lazygit Usage You can learn the necessary information about usage and key combinations on the Lazygit official website [Github - Lazygit](https://github.com/jesseduffield/lazygit). You can also find the `lazygit` tutorial on the **_typecraft_dev_** channel. {% embed https://www.youtube.com/watch?v=TLNdwvIFoCg %}
gokayburuc
1,875,917
How to Avoid SQL Injection: A Comprehensive Guide
Hello everyone, السلام عليكم و رحمة الله و بركاته Introduction SQL injection is one of...
0
2024-06-03T22:40:06
https://dev.to/bilelsalemdev/how-to-avoid-sql-injection-a-comprehensive-guide-18ca
sql, attacks, programming, python
Hello everyone, السلام عليكم و رحمة الله و بركاته #### Introduction SQL injection is one of the most common and dangerous security vulnerabilities in web applications. It occurs when an attacker inserts or "injects" malicious SQL code into a query, which can then be executed by the database. This can lead to unauthorized access to sensitive data, data corruption, or even complete control over the database server. This article provides a detailed guide on how to avoid SQL injection, ensuring your applications remain secure. #### Table of Contents 1. Understanding SQL Injection 2. Common Types of SQL Injection 3. Techniques to Prevent SQL Injection - Parameterized Queries - Stored Procedures - Input Validation - Least Privilege Principle 4. Best Practices 5. Conclusion #### 1. Understanding SQL Injection SQL injection is a code injection technique that exploits vulnerabilities in an application's software. When user input is incorrectly handled, it can allow an attacker to execute arbitrary SQL code, potentially compromising the database. For example, consider a login form where the SQL query is constructed by concatenating strings: ```sql SELECT * FROM users WHERE username = 'user' AND password = 'pass'; ``` If an attacker inputs `user' OR '1'='1` as the username and anything as the password, the query becomes: ```sql SELECT * FROM users WHERE username = 'user' OR '1'='1' AND password = 'pass'; ``` This condition is always true, granting unauthorized access. #### 2. Common Types of SQL Injection - **Classic SQL Injection:** Direct insertion of malicious SQL into queries. - **Blind SQL Injection:** The attacker gets no direct feedback from the database, relying on true/false responses. - **Error-Based SQL Injection:** Uses error messages to gain insights into the database structure. - **Union-Based SQL Injection:** Uses the UNION SQL operator to combine the results of multiple queries. #### 3. Techniques to Prevent SQL Injection **Parameterized Queries:** Using parameterized queries ensures that user input is treated as data and not executable code. This is supported by most modern database access libraries. *Example in TypeScript with Node.js and MySQL:* ```typescript import mysql from 'mysql2'; const connection = mysql.createConnection({ host: 'localhost', user: 'root', database: 'example' }); const username: string = 'user'; const password: string = 'pass'; connection.execute( 'SELECT * FROM users WHERE username = ? AND password = ?', [username, password], (err, results, fields) => { if (err) throw err; console.log(results); } ); ``` **Stored Procedures:** Stored procedures are SQL code that is stored and executed on the database server. They can help mitigate SQL injection by separating data from code. *Example:* ```sql CREATE PROCEDURE GetUser (@username NVARCHAR(50), @password NVARCHAR(50)) AS BEGIN SELECT * FROM users WHERE username = @username AND password = @password; END ``` **Input Validation:** Validating user inputs to ensure they meet expected formats and types can help prevent malicious input. *Example in TypeScript:* ```typescript const isValidUsername = (username: string): boolean => { const regex = /^[A-Za-z0-9_]+$/; return regex.test(username); } const username: string = 'test_user'; if (!isValidUsername(username)) { console.log('Invalid username.'); } ``` **Least Privilege Principle:** Limit database user permissions to only what is necessary for the application to function. This reduces the potential damage of an SQL injection attack. #### 4. Best Practices - **Use ORM Frameworks:** Object-Relational Mapping (ORM) frameworks like Sequelize for Node.js can abstract and protect against SQL injection. - **Regularly Update and Patch:** Keep your database and application frameworks up to date with the latest security patches. - **Employ Web Application Firewalls (WAF):** WAFs can help detect and block SQL injection attacks. - **Security Testing:** Regularly perform security audits and penetration testing to identify and fix vulnerabilities. #### 5. Conclusion Preventing SQL injection requires a combination of secure coding practices, proper input handling, and regular security assessments. By implementing parameterized queries, stored procedures, input validation, and adhering to the principle of least privilege, you can significantly reduce the risk of SQL injection attacks and protect your application and data from malicious actors. #### References - OWASP SQL Injection Prevention Cheat Sheet: [OWASP](https://cheatsheetseries.owasp.org/cheatsheets/SQL_Injection_Prevention_Cheat_Sheet.html) - SQL Injection Attacks and Defense: [Web Security Guide](https://www.websecurity.com/sql-injection) --- This article provides a comprehensive overview of SQL injection and its prevention methods, aimed at developers and security professionals. It highlights essential techniques and best practices to safeguard applications from SQL injection attacks.
bilelsalemdev
1,875,915
Zero Downtime with blue-green deployment
1 Benefits of blue-green deployment One of the main benefits of blue-green deployment is...
0
2024-06-03T22:37:09
https://dev.to/vaibhavhariaramani/zero-downtime-with-blue-green-deployment-5c8l
## 1 Benefits of blue-green deployment One of the main benefits of blue-green deployment is that it reduces the risk of errors and bugs affecting the users. By testing the new version in a separate environment, you can ensure that it works as expected and meets the quality standards. You can also perform smoke tests, load tests, and user acceptance tests before switching the environments. Another benefit is that it enables continuous delivery and deployment, which means faster and more frequent releases. You can deliver new features and improvements to your customers without waiting for scheduled maintenance windows or downtime. ## 2 Challenges of blue-green deployment However, blue-green deployment also comes with some challenges that you need to consider. One of them is the cost and complexity of maintaining two identical environments. You need to have enough resources, such as servers, storage, and network, to run both environments simultaneously. You also need to synchronize the data and configuration between them, which can be tricky and time-consuming. Another challenge is the coordination and communication between the teams and stakeholders involved in the deployment process. You need to have clear roles and responsibilities, as well as a reliable switch mechanism, to avoid confusion and errors. ## 3 Best practices for blue-green deployment To make the most of blue-green deployment, it’s important to follow some best practices. Automation is key here; use tools and scripts to create, configure, and deploy the environments, as well as to perform the switch and rollback operations. Additionally, you should monitor and measure the performance and behavior of both environments to compare the results and identify any issues or anomalies. Lastly, communication and collaboration are essential; use a common platform or channel to share information, feedback, and notifications about the deployment status and actions. This will help ensure transparency and alignment. ## 4 Examples of blue-green deployment To illustrate how blue-green deployment works in practice, let's look at some examples of companies that use it. One of them is Netflix, which uses blue-green deployment to release new features and updates to its streaming service. Netflix uses a tool called Asgard to manage its cloud infrastructure and switch between the environments. Another example is Amazon, which uses blue-green deployment to update its e-commerce platform. Amazon uses a tool called Elastic Load Balancing to distribute the traffic between the environments. ## 5 Alternatives to blue-green deployment Blue-green deployment is not the only technique for releasing software updates without downtime or disruption. There are other alternatives that you can explore, depending on your needs and preferences. One of them is canary deployment, which involves releasing the new version to a small subset of users or servers, and gradually increasing the exposure until it reaches the entire system. This way, you can test the new version in a real environment and monitor its performance and feedback. Another alternative is feature flags, which involve hiding or enabling the new features behind a toggle or switch, and controlling their visibility and availability to different users or groups. This way, you can release the new features without affecting the existing functionality and behavior.
vaibhavhariaramani
1,875,914
5 Common Challenges Faced by Programmers and Viable Fixes
Becoming a successful programmer is a challenging journey. Whether you're a seasoned programmer or a...
0
2024-06-03T22:36:07
https://dev.to/syedbalkhi/5-common-challenges-faced-by-programmers-and-viable-fixes-2f9a
coding, beginners
Becoming a successful programmer is a challenging journey. Whether you're a seasoned programmer or a beginner, you'll encounter various obstacles along the way. Experienced programmers often find it easier to solve problems they encounter. However, for newcomers, overcoming these challenges can seem daunting as they struggle to find optimal solutions. Simply getting your code to run successfully doesn't mean it's the end of all your problems. Even poorly written code might function properly. However, you may encounter numerous difficulties when scaling or maintaining your code down the road. Sometimes, your code may be overly complex and lack readability, causing issues in the long term. Other than that, there are many other challenges that programmers may encounter. These issues may severely affect their performance and make it difficult for them to stay focused at work, especially when they're at a beginner's level. Below are some common challenges programmers face and effective ways to solve them. ## 1. Offering a Seamless User Experience It's important to prioritize the user experience when writing code. Whether you're writing code to create a website or build an application, people who actually use the digital product may have different expectations and perceive it differently than developers. As a programmer, you typically don't interact directly with users, which makes it hard to understand their interests, needs, and preferences. This can lead to creating a digital product that doesn't offer a smooth user experience or [attract a relevant audience](https://www.monsterinsights.com/how-to-get-more-traffic-on-wordpress/) effectively. To address this issue, collaborate closely with UX experts and marketers to understand user expectations. Working with other teams [increases your efficiency](https://memberpress.com/10-digital-tools-to-maximize-efficiency/) and provides valuable insights about your target audience. This approach helps you write code that requires fewer changes or adjustments later, ensuring it meets user expectations from the start and offers them a seamless experience. ## 2. Bugs and Errors When writing code, bugs and errors are bound to happen, especially when you have just gotten started with your coding journey. Some of these issues are simple to resolve, while others can be more time-consuming. To prevent these errors from occurring, it's crucial to aim for error-free and [clean code](https://www.wpbeginner.com/plugins/how-to-scan-your-wordpress-site-for-potentially-malicious-code/) from the start. Multiple errors can slow down the process, delaying project completion and affecting the user experience. This not only frustrates you but also affects your employer or client. Therefore, having a debugging plan from the beginning is essential. Even well-written code might need [debugging](https://wpforms.com/developers/how-to-enable-debugging-in-wordpress/), so having effective strategies can save a lot of time. A good debugging plan helps you get started smoothly and keeps a record of past errors. By learning from these mistakes and preventing future bugs, you can distinguish yourself as a proficient developer and [stand out](https://www.blogtyrant.com/how-to-stand-out/) from others who are competing. ## 3. Maintenance and Modifications Writing efficient code is a process that demands continuous improvement through a series of iterations. You can't just write code that works and leave it at that. Ongoing maintenance and optimization are necessary over time to create [digital products](https://easydigitaldownloads.com/blog/trending-digital-products-in-high-demand/) that offer an exceptional user experience. This may seem overwhelming, but it becomes more manageable when you make full use of available technology. Development tools are always evolving, and the latest versions can simplify your workflow and help you stay on top of the tasks on your [to-do list](https://formidableforms.com/how-to-create-to-do-list-wordpress/). It's important to stay updated with the latest developments and learn about changes in the tools you use. The latest versions of the tools can streamline your workflows and make it easier for you to keep up with your deliverables. Additionally, keeping an eye on the latest trends and best practices will improve your coding skills and help you find effective solutions to the problems you encounter. You can also leverage relevant learning resources available online to enhance your skills and expand your knowledge over time. ## 4. Code Complexity Sometimes, identifying and fixing the issues in your code can take longer than expected. There can be various reasons for this, such as writing complex code that makes problem-solving difficult. When you're the one who wrote the code, it might look fine to you, making it hard to spot errors and come up with viable fixes. To tackle this, it's best that you seek assistance from more experienced developers or reach out to professionals in online coding communities. These communities are generally welcoming and supportive for beginners, so you can ask members to review your code and help you identify potential errors. You can also ask them about solutions to the challenges you're facing. Seeking guidance from senior programmers offers a new perspective and can help you find effective solutions to the issues you face quickly. ## 5. Committing to Deadlines Whether you're employed by a company or working as a [freelancer](https://www.wpbeginner.com/showcase/23-top-tools-for-wordpress-freelancers-designers-and-developers/), providing accurate estimates for project completion is essential. It's best that you anticipate potential challenges, create realistic milestones, and adhere to what you committed. Unnecessary delays can damage trust and leave a negative impression. To avoid this, being proactive and a good planner is crucial. Begin by breaking your project into smaller tasks and estimating the time required to complete each. This approach helps you gauge the overall workload and provide accurate completion estimates. It's also wise to add a buffer to the committed deadlines. You can't always predict the severity of the problems you'll face or how long it will take to resolve the issues. A buffer gives you extra time to handle unexpected challenges, making it easier for you to deliver your projects on time. Effective time management is another key aspect. You should devise strategies to avoid procrastination and ensure you're using your time efficiently. However, this doesn't mean that you should work nonstop. Take regular breaks to recharge and replenish your energy. The goal is to avoid wasting time and strive to meet the deadlines you've set for project completion. ## It's a Wrap This article talks about five common challenges faced by programmers when getting started and ways to overcome them. If you've been facing issues similar to the ones mentioned, the recommendations in this article may help you come up with viable solutions.
syedbalkhi
1,870,117
Week 3 of Community Bonding
I'll admit that I've been doing a lot of work in this community bonding period to stave off all forms...
27,442
2024-06-03T22:33:26
https://dev.to/chiemezuo/week-3-of-community-bonding-5ea7
gsoc, summerofcode, wagtail, opensource
I'll admit that I've been doing a lot of work in this community bonding period to stave off all forms of imposter syndrome very early on. I promised myself a fun internship and I'm laying a good foundation for it. This week was when some major dots started connecting, and I'm more than happy to share. ## Weekly Check-in As mentioned previously in this series, I start my week with a meeting session with my mentors to discuss expectations and action plans for the week. My mentors and I decided to move some tasks to Sprint 3, because they weren't immediate priorities. We also agreed to keep modifying the RFC to our satisfaction, and I had made good progress on my Proof of Concept. My lead mentor also pointed me to an area of Wagtail to do more research on: StructValue, as well as some considerations for the second goal of the project: modifying the existing image model to accept image descriptions. I also asked my mentors for permission to use their names in my writings, and they told me I was free too. My two amazing mentors are: [Storm ](https://stormheg.co/)and [Saptak](https://saptaks.website/). ## What I learned I had to make lots of alterations to my Proof of Concept. I set out to look for the approach that involved modifying only the least amount of Wagtail internal code. In hindsight, I think I opted for that course of action out of some level of nervousness. I was worried once more about my inexperience showing too much. I envisioned a situation where I would do something one way when there was a more efficient (yet seemingly obvious) way of doing it from the get-go, so I tilted towards the path that would let me make the least mistakes. I showed it to the lead dev and he wasn't so keen on my approach, not because it didn't work, but because it involved introducing some new behavior to an existing feature of Wagtail, just to accommodate a small change. My mentors also had similar views, so I decided to let go of my fears and be very experimental, and this led me to the best approach yet. It's surprising just how much better you can perform a task when calm. I did my due diligence, read large amounts of Wagtail documentation, and played around with the existing features. Thankfully, Wagtail offers a lot of flexibility and allows functionality to be extended in creative ways. There was a lot I had to discover, but my mentors had given me a comfortable ground to fall on, so it was my job to fall as many times as I could with their guidance. Without any pressure to get it right so quickly, I got around to understanding the `Block` behaviour and its underlying Javascript. Getting the Javascript to work was tricky until I remembered I had to compile static files. This led me to work with Webpack and entry points for the first time ever. Eventually, my Proof of Concept got to a level that we were all very content with, but due to the sheer number of iterations, I had a messy commit history. I perfected the act of rebasing commits. Along these lines, something unexpected happened: I got better at communicating the changes I was making, and I also got better at hypothesizing the effects that certain changes would cause. ## Challenges I was essentially in the wild this time around, and I found everything tough. I spent so much time looking at my screen, trying things out, reading docs, and probing deeper into topics. I had a nasty eye strain at some point, and the fact that I was using the Docker setup slowed down my progress. I decided I'd be done with Docker and configure my computer to use the fully local setup, without any form of virtualization. That was my new week's goal. It was an exciting week yet again, and I had some personal wins that I was (and still am) quite grateful for. Cheers. 🥂
chiemezuo
1,875,913
CSS ART : Something Unique about JUNE
This is a submission for Frontend Challenge v24.04.17, CSS Art: June. Inspiration The...
0
2024-06-03T22:24:28
https://dev.to/sardiusjay/css-art-something-unique-about-june-54gj
frontendchallenge, devchallenge, css
_This is a submission for [Frontend Challenge v24.04.17](https://dev.to/challenges/frontend-2024-05-29), CSS Art: June._ ## Inspiration <!-- What are you highlighting today? --> The inspiration behind the June-themed CSS art is a blend of seasonal elements associated with the month of June. 1. **Sun**: June often marks the beginning of summer in many parts of the world. The sun is a symbol of warmth, longer days, and outdoor activities. The bright yellow sun in the art represents the sunny days of June. 2. **Leaves**: In Africa, because that is my location. June is a time of transition. it's when leaves are lush and green, while in the southern part of the country, it might be the start of autumn with leaves changing color. The green leaves in the artwork capture this duality. 3. **Raindrops**: June can bring both rain and sunshine. The raindrops symbolize the occasional showers that nourish the earth and contribute to the vibrant greenery. They also represent the unpredictability of weather during this month. 4. **Colors**: The choice of colors—yellow for the sun, green for leaves, and blue for raindrops—reflects the natural palette associated with June. ## Demo ![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/hk9b93dkheky3tsgj0c3.png) **HTML CODE** ``` <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <link rel="stylesheet" href="index.css"> <title>CSS Art</title> </head> <body> <div class="sun"></div> <div class="leaf leaf1"></div> <div class="leaf leaf2"></div> <div class="raindrop raindrop1"></div> <div class="raindrop raindrop2"></div> <div class="raindrop raindrop3"></div> <div class="raindrop raindrop4"></div> </body> </html> ``` **CSS CODE** ``` * { padding: 0; margin: auto; box-sizing: border-box; } body { background-color: black; } /* Sun */ .sun { position: absolute; top: 50%; left: 50%; transform: translate(-50%, -50%); width: 100px; height: 100px; background-color: #f9d71c; border-radius: 50%; } /* Leaves */ .leaf { position: absolute; width: 0; height: 0; border-left: 20px solid transparent; border-right: 20px solid transparent; border-bottom: 40px solid #228b22; transform-origin: bottom center; } /* Leaf 1 */ .leaf1 { top: 60%; left: 30%; transform: rotate(30deg); } /* Leaf 2 */ .leaf2 { top: 60%; left: 70%; transform: rotate(-30deg); } /* Raindrops */ .raindrop { position: absolute; width: 10px; height: 20px; background-color: #00aaff; border-radius: 50%; animation: fall 2s infinite linear; } /* Raindrop 1 */ .raindrop1 { top: 10%; left: 20%; } /* Raindrop 2 */ .raindrop2 { top: 15%; left: 40%; } /* Raindrop 3 */ .raindrop3 { top: 20%; left: 60%; } /* Raindrop 4 */ .raindrop4 { top: 25%; left: 80%; } /* Animation */ @keyframes fall { 0% { transform: translateY(-10%); } 100% { transform: translateY(100%); } } ``` ## Journey **The Process** _**Inspiration:**_ The initial inspiration came from the user’s prompt, which mentioned various aspects of June—summer solstice, falling leaves, Father’s Day, and Pride Month. _**Conceptualization:**_ I visualized a scene that combined these elements: a sunny day with green leaves, raindrops, and a cheerful vibe. Design Choices: I chose simple shapes (sun, leaves, raindrops) and vibrant colors to represent June’s essence. _**CSS Implementation:**_ I crafted the art using CSS properties like position, border-radius, and animation. _**Animation:**_ The raindrops falling animation was added to create movement and dynamism. **What i Learn** _**CSS Art Techniques: **_Creating art with CSS involves thinking creatively within the constraints of CSS properties. It’s a fun way to blend design and code. _**Symbolism:**_ Each element in the art symbolizes something—sun for warmth, leaves for seasonal change, and raindrops for unpredictability. **what am particularly Proud of** _**Balancing Simplicity and Aesthetics:**_ Achieving a visually appealing result with minimal shapes and colors. Responsive Design: Ensuring the art adapts well to different screen sizes. **Next Steps:** _**Explore More Complex Art:**_ I’d like to experiment with more intricate CSS art, perhaps incorporating gradients, shadows, and more detailed shapes. _**Interactive Elements:**_ Adding interactivity (hover effects, transitions) to CSS art for an engaging user experience. _**Collaboration:**_ Collaborating with other developers/artists to create larger-scale CSS art projects.
sardiusjay
1,875,912
Sprucing Up the Sunshine City: Commercial Building Painters in St. Petersburg, FL
Discover the best commercial building painters in St. Petersburg, FL. Learn how to choose the right...
0
2024-06-03T22:24:07
https://dev.to/efcestimatefloridaconsulting/sprucing-up-the-sunshine-city-commercial-building-painters-in-st-petersburg-fl-1mn1
![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/rud40yhs5m1qze74xqit.jpg) Discover the best [commercial building painters in St. Petersburg, FL](https://estimatorflorida.com/commercial-building-painters-in-st-petersburg-fl/). Learn how to choose the right painter, what to expect, and why a fresh coat of paint makes a difference. Introduction Ever wondered why some buildings just seem to pop out at you? Chances are, they’ve been given a little TLC by professional painters. In St. Petersburg, FL, known for its sunny skies and vibrant communities, the look of a commercial building can make all the difference. Whether it’s a sleek office building or a charming storefront, a fresh coat of paint can transform the ordinary into the extraordinary. Why Choose Professional Painters? The Magic Touch of Professionals When you see a building that looks sharp and inviting, it’s likely the handiwork of professional painters. These folks aren’t just slapping paint on walls; they’re artists in their own right. They know the right types of paint for Florida’s hot and humid climate, ensuring your building looks great and withstands the elements. Plus, they can help you pick colors that not only match your brand but also make your building stand out. Time and Money Savers Let’s face it, painting a commercial building is no small feat. It's time-consuming and can be downright messy if you don’t know what you’re doing. Professional painters have all the right tools and expertise to get the job done quickly and efficiently. This means less downtime for your business and more bang for your buck. What to Expect from Commercial Building Painters Thorough Preparation Before a single brushstroke hits the wall, professional painters will prep your building. This includes power washing, repairing any damage, and priming surfaces. Think of it as laying the groundwork for a masterpiece. Expert Execution These painters don’t cut corners. They’ll meticulously apply each coat of paint, ensuring even coverage and smooth finishes. With their expertise, you won’t have to worry about streaks, bubbles, or uneven textures. Clean-Up and Inspection Once the painting is done, professionals will clean up any mess they’ve made. They’ll also conduct a thorough inspection to make sure everything is perfect. Your satisfaction is their top priority. Choosing the Right Painter Check Their Credentials Make sure the painters you hire are licensed and insured. This not only protects you but also guarantees that they have met certain standards of quality and professionalism. Read Reviews and Get References Look at what previous clients have to say. Reviews and references can give you a good idea of the painter’s reliability and the quality of their work. Get Multiple Quotes Don’t just go with the first painter you find. Get quotes from several companies to ensure you’re getting a fair price. Remember, the cheapest option isn’t always the best. Ask About Their Process A good painter will be happy to explain their process to you. They’ll walk you through the steps they’ll take to prep, paint, and finish your building, so you know exactly what to expect. Benefits of a Fresh Coat of Paint Improved Aesthetic Appeal A freshly painted building looks more attractive and can draw in more customers. It’s a simple way to make a big impact on your business’s curb appeal. Protection from the Elements Paint acts as a barrier against the harsh Florida sun, rain, and humidity. It helps protect your building’s exterior, extending its lifespan and saving you money on repairs. Increased Property Value If you’re looking to sell or lease your commercial property, a fresh coat of paint can increase its market value. It’s an investment that pays off in the long run. FAQs Q: How often should I repaint my commercial building? A: It depends on the type of building and the paint used, but generally, every 5-10 years is a good rule of thumb. Q: Can painting be done in the rainy season? A: It’s best to paint during dry weather to ensure the paint adheres properly. In Florida, the winter months are usually ideal. Q: How long does it take to paint a commercial building? A: This varies based on the size of the building and the complexity of the job, but most projects take a few days to a couple of weeks. Conclusion Choosing the right [commercial building painters in St. Petersburg, FL](https://estimatorflorida.com/commercial-building-painters-in-st-petersburg-fl/) can make a world of difference for your business. From improving curb appeal to protecting your property, a fresh coat of paint is a smart investment. So, don’t wait—get in touch with a professional painter today and watch your building transform before your eyes.
efcestimatefloridaconsulting
1,875,910
About the Author of the Website https://joseph-wilson.pw/
In the ever-evolving digital world, it’s essential to have a skilled professional who can bridge the...
0
2024-06-03T22:11:57
https://dev.to/joseph_wilson_/about-the-author-of-the-website-httpsjoseph-wilsonpw-4j0i
web
In the ever-evolving digital world, it’s essential to have a skilled professional who can bridge the gap between technical expertise and creative vision. Joseph Wilson, the author and owner of [https://joseph-wilson.pw/](https://joseph-wilson.pw/), is a prime example of such a professional. This article explores Joseph Wilson's background, his journey into the digital realm, and what makes him a standout figure in web development and digital marketing. Who is Joseph Wilson? A Brief Background Joseph Wilson is a seasoned web developer and digital marketing expert with a passion for creating high-quality, functional, and aesthetically pleasing websites. He has carved out a niche for himself in the digital industry, known for his ability to blend technical prowess with creative ingenuity. His journey into the world of web development and digital marketing is marked by a continuous drive to learn and innovate. Early Beginnings Joseph's interest in technology began at a young age. Fascinated by how websites were built and operated, he started teaching himself the basics of coding and design. This early passion set the foundation for his future career. As he grew older, he pursued formal education in computer science and digital marketing, gaining a deeper understanding of the technical and strategic aspects of web development. Professional Expertise Web Development Skills Joseph's web development skills are comprehensive, covering both front-end and back-end development. He is proficient in various programming languages and frameworks, including HTML, CSS, JavaScript, and PHP. His expertise allows him to create custom websites that are not only visually appealing but also robust and scalable. Digital Marketing Proficiency In addition to his technical skills, Joseph is also well-versed in digital marketing. He understands the importance of SEO, content marketing, and social media in driving traffic and engagement. His ability to integrate marketing strategies with web development ensures that the websites he creates are optimized for both performance and visibility. Journey and Achievements Career Milestones Over the years, Joseph has worked with a diverse range of clients, from small businesses to large corporations. Each project has contributed to his growth as a professional, allowing him to refine his skills and expand his portfolio. Some of his notable achievements include developing high-traffic e-commerce platforms, creating engaging corporate websites, and implementing effective SEO strategies that have significantly improved his clients' online presence. Continuous Learning and Innovation Joseph is committed to staying at the forefront of the industry. He continually updates his knowledge by learning about new technologies, design trends, and marketing strategies. This commitment to continuous learning ensures that his clients receive the best possible solutions, tailored to the ever-changing digital landscape. What Sets Joseph Apart? Client-Centric Approach One of the key aspects that sets Joseph apart is his client-centric approach. He believes in understanding his clients' needs and goals thoroughly before starting any project. This ensures that the final product not only meets but exceeds expectations. His dedication to client satisfaction is reflected in the numerous positive testimonials and repeat business he receives. Attention to Detail Joseph's attention to detail is another standout quality. He takes the time to ensure that every aspect of a website, from the design to the functionality, is perfect. This meticulous approach results in websites that are not only beautiful but also highly functional and user-friendly. Holistic Solutions By combining his web development skills with his digital marketing expertise, Joseph offers holistic solutions that address all aspects of an online presence. This integrated approach ensures that his clients' websites are optimized for both user experience and search engine performance, providing a solid foundation for digital success. Joseph Wilson is a remarkable figure in the world of web development and digital marketing. His unique blend of technical skills, creative vision, and client-focused approach makes him a valuable asset to any project. Through his website, joseph-wilson.pw, he continues to showcase his expertise and dedication to excellence, helping businesses establish and grow their online presence in an ever-competitive digital world.
joseph_wilson_
1,876,708
Generating a random string in PHP
Learn the best ways to generate random strings in PHP, whether you're using the latest PHP 8.2 with...
0
2024-06-03T22:00:00
https://backendtea.com/post/php-random/
Learn the best ways to generate random strings in PHP, whether you're using the latest PHP 8.2 with the Randomizer class or working with earlier versions. This post provides detailed explanations, code snippets, and practical use cases, including how to ensure deterministic results for unit tests. Improve your PHP skills with these techniques. You can find the full blog post [right here](https://backendtea.com/post/php-random/?utm_source=devto&utm_campaign=php-random-string)
backendtea
1,876,512
Evaporating a pot of water
Originally published on peateasea.de. As part of tutoring physics and maths to high school students,...
0
2024-06-05T10:16:04
https://peateasea.de/evaporating-a-pot-of-water/
physics, python, school
--- title: Evaporating a pot of water published: true date: 2024-06-03 22:00:00 UTC tags: Physics,Python,School canonical_url: https://peateasea.de/evaporating-a-pot-of-water/ cover_image: https://peateasea.de/assets/images/evaporation-process-sketch2.png --- *Originally published on [peateasea.de](https://peateasea.de/evaporating-a-pot-of-water/).* As part of tutoring physics and maths to high school students, I sometimes write up [deep-dive explanations](https://github.com/paultcochrane/after-school-help) of questions arising during lessons. The question below discusses how long it takes to completely evaporate a pot of water. * * * You have been given the question: > A pot containing 850 mL of water is sitting on a stove element. Initially, the water has a temperature of 20 °C. The element is turned on and delivers 1000 J per second. Calculate when the water is completely evaporated. We’re now going to do a “deep dive” into the question, so buckle up! ## Finding useful information in the question Problem-solving tip: extract the essential information from the question to reduce the problem to its “bare bones”. Also, note any information about the problem’s context that might be relevant to solving the problem. This is something that takes practice and patience! One strategy to solve a problem like the one we have is to read the entire question first before doing anything else to get a high-level overview of what’s being asked. Then we return to the beginning of the question and take each sentence one at a time and pull out the information that might be useful to us and categorise it somehow. For instance, in the first sentence > A pot containing 850 mL of water is sitting on a stove element. the main piece of information is that we have 850 mL of water which will be heated up. The fact that it’s in a pot on a stove is only secondary; it could be in a glass flask on a heating element or could be in a plastic bowl in a microwave oven. What’s important here is that we have a certain amount of water and energy is going to be fed into it to heat it up. > Initially, the water has a temperature of 20 °C. The water is at 20 °C before anything else happens to it. This is also a hint that the temperature is going to change somehow and that we’ve been given a reference temperature for later calculations. > The element is turned on and delivers 1000 J per second. Fairly obviously, 1000 J of energy is being added to the water per second. This is the bit where we realise that it’s being heated up. However, this part of the question tells us exactly how: 1000 J for every second (which, incidentally, is 1000 W; a [Watt](https://en.wikipedia.org/wiki/Watt) is the amount of energy per unit time, in particular the number of Joules per second). We know from reading the whole question at the beginning that we have to calculate a time, so having time (i.e. seconds) turn up in one piece of information is very helpful to keep in the back of our heads for the remainder of the question. > Calculate when the water is completely evaporated. The important words in this sentence are “when” and “evaporated”. We’ve thus been asked for an amount of time (“when”; which probably could be more precisely specified as “how many seconds are required to completely evaporate the water” or “how much time will pass before all the water has evaporated”). An amount of time links back to the energy rate we have from the previous sentence (1000 J/s is an energy _rate_: it is how much energy per unit time is being added to the system). The second important word “evaporated” tells us the final state of the system, i.e. all the _liquid_ water has been turned into _gaseous_ water (steam) and is thus “gone” into the air. Using the words from the question, the task we’ve been asked to perform is thus reduced to: > 850 mL water, 20 °C; 1000 J/s; when evaporated? Another way to write the same thing<sup id="fnref:rewording-tip" role="doc-noteref"><a href="#fn:rewording-tip" rel="footnote">1</a></sup> would be something like this, where we make time more explicit: - t<=0: 850 mL water at 20 °C - t=0: 1000 J/s - t=? when water volume is 0 mL? We could also look at this pictorially: ![evaporation process sketch](https://peateasea.de/assets/images/evaporation-process-sketch2.png) We have a rate of energy per unit time, thus if we know how much energy we need to completely evaporate the water, we can then work out how much time that will take (the energy rate is constant, which also makes things easier to calculate). ## A physical intuition of the overall evaporation process So how do we get from water at 20 °C to all of it being completely evaporated? This is a two-step process: - heat the water to 100 °C - convert the liquid water into gaseous water (steam). Note that there’s a simplifying assumption being used here: evaporation doesn’t occur until the water has reached 100 °C. We know from experience that water doesn’t have to be boiling for it to evaporate, however in this case that process is _much slower_ than how quickly the water is being heated by the stove element, thus we ignore any evaporation which might be happening as the water is heated from 20 °C to 100 °C. That might sound a bit weird. After all, isn’t water at 100 °C boiling? And thus it’s already turning into steam? This is true to a degree, yet when water is boiling at 100 °C it is actually a mixture of liquid and gaseous water, both states being at 100 °C.<sup id="fnref:states-of-matter" role="doc-noteref"><a href="#fn:states-of-matter" rel="footnote">2</a></sup> When water is a gas, the water molecules have so much energy that they don’t interact with one another very much. The situation is very different in the liquid state: water molecules are held together by their intermolecular force, which is mostly due to [hydrogen bonding](https://en.wikipedia.org/wiki/Water#Hydrogen_bonding) but also partially due to the [van der Waals force](https://en.wikipedia.org/wiki/Van_der_Waals_force). These bonds look something like this: ![Hydrogen bonding between water molecules](https://peateasea.de/assets/images/hydrogen-bonding-between-water-molecules.jpg) For liquid water to become a gas, these forces have to be overcome and that takes energy. Thus, we need two lots of energy to evaporate water: heat it to boiling point and then break the intermolecular bonds. These two steps are governed by two pieces of [thermodynamics](https://en.wikipedia.org/wiki/Thermodynamics): the [specific heat capacity](https://en.wikipedia.org/wiki/Specific_heat_capacity) and the [heat of vaporisation](https://en.wikipedia.org/wiki/Enthalpy_of_vaporization).<sup id="fnref:heat-of-vaporisation-name" role="doc-noteref"><a href="#fn:heat-of-vaporisation-name" rel="footnote">3</a></sup> The specific heat capacity is the amount of energy (per unit mass) that it takes to raise a substance by 1 °C. You will often see this written with units of {% katex inline %}\mathrm{\ J \cdot kg^{-1} \cdot K^{-1}}{% endkatex %}, where a temperature change of 1 K is the same as a temperature change of 1 °C. Thus, the specific heat is what we can use to work out how much energy it will take to heat the water from 20 °C to 100 °C. Note that replacing the temperature change units from K to °C works because the two temperature scales have the same slope, i.e. the markings on the scale of a thermometer using °C and one using Kelvin are the [same distance apart](https://en.wikipedia.org/wiki/File:CelsiusKelvinThermometer.jpg). We can convince ourselves that temperature differences in both units have the same numerical value by converting each of the temperatures from °C to K. The formula is “Temperature in °C” + 273.15 K = “Temperature in K”. The interesting thing to note here is that there is no factor to be applied to the value of temperature in °C, or, written more explicitly, there is a factor of 1 K/°C (to get the right units). So we get {% katex %} T\_{\mathrm{diff}} = (100 °C \cdot 1 K/°C + 273.15 K) - (20 °C \cdot 1 K/°C + 273.15 K) {% endkatex %} {% katex %} \Rightarrow T\_{\mathrm{diff}} = 373.15 K - 293.15 K = 80 K {% endkatex %} in the same way that the difference 100 °C - 20 °C is 80 °C. This means that as long as we are dealing with temperature _differences_ we can use either K or °C. The heat of vaporisation is the amount of energy per unit mass required to change from the liquid into the gaseous state. This is sometimes quoted in units of J/g or kJ/kg, which is the same thing. Unfortunately, the values for these parameters are not given in the question and hence we have to look them up and make some assumptions about which values we are expected to use (there is sometimes variation in which value one could use). This isn’t a problem because this is a much better reflection of how the real world works: if one doesn’t know what a certain parameter is, then one has to go looking for it and work out if the numbers one finds make sense in the given context. This is a really good situation because we’ve got a great opportunity to learn new things! So what is the specific heat capacity for water? To find this out we can look up the value in a [table of specific heat capacities](https://en.wikipedia.org/wiki/Table_of_specific_heat_capacities) and for water at 25 °C (close enough for our purposes) the value is {% katex inline %}4.1813 \mathrm{\ J \cdot kg^{-1} \cdot K^{-1}}{% endkatex %}. And what about the heat of vaporisation? After a bit of looking around, we find a [table on the Enthalpy of vaporisation Wikipedia page](https://en.wikipedia.org/wiki/Enthalpy_of_vaporization#Other_common_substances) which lists values for common substances, one of which is water. Note the comment on [that same Wikipedia page](https://en.wikipedia.org/wiki/Enthalpy_of_vaporization): > The enthalpy of vaporization is often quoted for the normal boiling temperature of the substance. The fact that the enthalpy of vaporisation is specified with respect to the normal boiling point backs up our intuition that the evaporation process is split into two parts: heating to the boiling point and then vaporising. Thus we can be more confident that we’re on the right path. ## Building a physical intuition from experiment But you don’t have to take my word for it, you can make an experiment to try it out. The [heating curves page](https://gchem.cm.utexas.edu/thermo/index.php#enthalpy/heat-curves.html) of the [University of Texas Chemistry 301 thermodynamics course](https://gchem.cm.utexas.edu/thermo/index.php) describes this experiment. The setup they use is like the problem we’re trying to solve: take a beaker with ice in it and put it on a hot plate at a temperature well above 100 °C (in this case 120 °C). Through experience, we know that the ice will melt into water and as we add more heat to the water it will eventually boil. The temperature of the hot plate must be above the boiling point of water so that we know that the hot plate is always adding energy to the water. If we measure the temperature of the water as we add more energy, then we’ll see that the temperature will rise until we have an ice-water solution, at which point the temperature will stay constant at 0 °C until all the ice has melted. Once all the ice has melted, the water’s temperature will start rising again and at a rate proportional to the amount of energy we add to it per unit time. The temperature will keep rising until the water starts to boil and we have a water-steam mixture at a temperature of 100 °C. The water-steam mixture will stay at this temperature until all the water has evaporated into steam and then the temperature of the steam will continue rising in proportion to the amount of energy we’re adding per unit time. If we plot the temperature of the system against the energy we add to it, we get a [heating curve](https://chem.libretexts.org/Bookshelves/General_Chemistry/Map%3A_A_Molecular_Approach_(Tro)/11%3A_Liquids_Solids_and_Intermolecular_Forces/11.07%3A_Heating_Curve_for_Water) like that shown below. ![heating curve of water](https://peateasea.de/assets/images/heating-curve-water.svg) There’s an interesting point to make here: if we know we are adding energy to the system at a constant rate (as we are in the problem we’re trying to solve), then an x-axis of energy (Joules as in the graph above) is _equivalent_ to an x-axis of _time_ because time is directly related to energy through the energy rate (1000 J/s in the problem we want to solve). Thus the graph above could also be read as temperature changes over time. This helps us better understand the problem we want to solve because we merely need to work out the point on the x-axis that matches 20 °C and then work out how much energy is required to get to the plateau at 100 °C. After that, we calculate the energy required to convert the water-steam mixture at 100 °C into all steam (i.e. all the water has evaporated). Thus the problem we want to solve is a subset of the heating curve for water that we are now familiar with: ![heating curve water evaporation sketch](https://peateasea.de/assets/images/heating-curve-water-evaporation-sketch.png) ## Calculating how long it takes for the water to evaporate Let’s scale down the problem to consider heating only 1 mL of water from 20 °C to 100 °C (because 1 mL is easier to think about than 850 mL). ### Heating the liquid water The [specific heat capacity](https://en.wikipedia.org/wiki/Specific_heat_capacity) of liquid [water](https://en.wikipedia.org/wiki/Water) is 4184 J/kg/K and is sometimes quoted more approximately by 4.2 kJ/kg/K (where we use kJ to scale down the numerical value by a factor of 1000 (this makes the numbers easier to work with)) or equivalently 4.2 J/g/K (because the “kilo” part in kJ and kg cancel when dividing). Thus, the energy to raise 1 g of water from 20 °C to 100 °C is (let’s call this the heating energy {% katex inline %}E\_h = E\_1 - E\_0{% endkatex %}; see also the heating curve diagram above): {% katex %} \begin{equation} E\_h(1\mathrm{\ g}) = 4.2 \mathrm{\ J/g/K} \cdot (100 - 20) \mathrm{\ K} = 336 \mathrm{\ J} \end{equation} {% endkatex %} We can use [Python](https://www.python.org/) in a [Jupyter notebook](https://jupyter.org/) to run the calculation. Enter the following code into a Jupyter notebook. ```python specific_heat_capacity = 4.2 boiling_temperature = 100 initial_temperature = 20 # energy to raise 1 g of water from 20 °C to boiling point boiling_energy_1g = specific_heat_capacity * (boiling_temperature - initial_temperature) print(f"Energy to raise 1 g of water from 20 °C to boiling point: {boiling_energy_1g} J") ``` Running the associated cell, you should get this output: ``` Energy to raise 1 g of water from 20 °C to boiling point: 336.0 J ``` However, we have a _volume_ of water, not a _weight_, thus we need to work out how many grams there are in 1 mL of water. Water has a density of 0.9970474 g/mL at 25 °C, thus: {% katex %} \begin{equation} 1\mathrm{\ mL\ of\ water} = 0.9970474\mathrm{\ g\ of\ water} \end{equation} {% endkatex %} For our purposes, this is close enough to the value 1, so we can assume that 1 mL of water weighs 1 g. With this simplification in mind, we can say that the energy required to raise 1 mL of water from 20 °C to 100 °C (i.e. 80 °C) is: {% katex %} \begin{equation} E\_h(1\mathrm{\ mL}) = 4.2 \mathrm{\ J/g/K} \cdot (100 - 20) \mathrm{\ K} = 336 \mathrm{\ J} \end{equation} {% endkatex %} Thus, to raise 850 mL of water by 80 °C (equivalently by 80K) is: {% katex %} \begin{equation} E\_h = 850 \mathrm{\ g} \cdot 4.2 \mathrm{\ J/g/K} \cdot (100 - 20) \mathrm{\ K} = 285600 \mathrm{\ J} \end{equation} {% endkatex %} In a new cell in your Jupyter notebook, enter the following code: ```python specific_heat_capacity = 4.2 boiling_temperature = 100 initial_temperature = 20 water_volume = 850 # energy to raise given volume of water from 20 °C to boiling point heating_energy = water_volume * specific_heat_capacity * (boiling_temperature - initial_temperature) print(f"Energy to raise a volume of water from 20 °C to boiling point: {heating_energy} J") ``` Running this cell should give you this output: ``` Energy to raise a volume of water from 20 °C to boiling point: 285600.0 J ``` ### Turning boiling liquid water into steam The [heat of vaporisation for water](https://en.wikipedia.org/wiki/Enthalpy_of_vaporization#Other_common_substances) is given as 2257 J/g or [2265 kJ/kg = 2265 J/g](https://en.wikipedia.org/wiki/Latent_heat#Table_of_specific_latent_heats) or [2260 kJ/kg](https://link.springer.com/referenceworkentry/10.1007/978-90-481-2642-2_327) depending upon where one looks. This is why it would have been helpful to have the expected values to use as part of the question. I don’t think the exact value matters that much really, so we’ll just use the value from the [heat of vaporisation for water Wikipedia page](https://en.wikipedia.org/wiki/Enthalpy_of_vaporization#Other_common_substances), i.e. 2257 J/g. We have 850 mL of water = 850 g of water at 100 °C. Thus the energy required to evaporate this amount of water is (let’s call this amount of energy {% katex inline %}E\_v{% endkatex %}; the energy of vaporisation): {% katex %} \begin{equation} E\_v = 2257 \mathrm{\ J/g} \cdot 850 \mathrm{\ g} = 1918450 \mathrm{\ J} \end{equation} {% endkatex %} In another cell in your Jupyter notebook, enter the following code: ```python heat_of_vaporisation = 2257 water_volume = 850 # energy of vaporisation vaporisation_energy = heat_of_vaporisation * water_volume print(f"Energy of vaporisation: {vaporisation_energy} J") ``` Running this cell should give this result: ``` Energy of vaporisation: 1918450 J ``` An interesting point to note here is how large this value is in comparison to the energy required to boil the water: it's almost _7 times_ as much energy! In other words, it takes _much more_ energy to evaporate water as it does to simply heat it. Thus we can see that phase changes--such as transitioning from the liquid to the gaseous state--require a lot of energy. ### Total energy and total time to evaporate water The total energy we need to evaporate all the water, {% katex inline %}E\_{\mathrm{tot}}{% endkatex %} is thus {% katex %} \begin{equation} E\_{\mathrm{tot}} = E\_h + E\_v = 285600 \mathrm{\ J} + 1918450 \mathrm{\ J} = 2204050 \mathrm{\ J} \end{equation} {% endkatex %} Again, we can run this calculation ourselves by creating a new cell in the Jupyter notebook and entering this code: ```python total_energy = heating_energy + vaporisation_energy print(f"Total energy required to evaporate water: {total_energy} J") ``` Running the cell gives: ``` Total energy required to evaporate water: 2204050.0 J ``` Since we know that we’re adding energy to the system at a rate of 1000 J/s, it will thus take {% katex inline %}E\_{\mathrm{tot}}/1000{% endkatex %} s to evaporate all the water. I.e. the time to evaporate all the water, {% katex inline %}t\_e{% endkatex %} is: {% katex %} t\_e = 2204050 / 1000 \mathrm{\ s} = 2204.05 \mathrm{\ s} = 2204.05 / 60 \mathrm{\ minutes} = 36.73 \mathrm{\ minutes} {% endkatex %} To run the final calculation, enter the following code into a new cell in your Jupyter notebook: ```python evaporation_time_seconds = total_energy / 1000 print(f"Evaporation time (seconds): {evaporation_time_seconds}") evaporation_time_minutes = evaporation_time_seconds / 60 print(f"Evaporation time (minutes): {evaporation_time_minutes:.2f}") ``` This should give you this output: ``` Evaporation time (seconds): 2204.05 Evaporation time (minutes): 36.73 ``` In other words, it will take just over half an hour to evaporate all the water. This result seems about right from previous experience one might have of boiling water on a stove. One could, of course, attempt this experiment at home (be careful!), to confirm the result of this calculation. ## Returning to where we came from Now that we’ve solved the problem and have found a solution, let’s summarise it to round off the discussion. We could describe the situation as follows: > To evaporate all the water, we need to first bring the water to boiling point and then vaporise the water. Given the heat capacity of water of 4.2 J/g/K, the temperature difference of 80K and the mass of water (850 mL = 850 g), it will take {% katex inline %}850\mathrm{\ g} \cdot 4.2 \mathrm{\ J/g/K} \cdot 80 \mathrm{\ K} = 285600\mathrm{\ J}{% endkatex %} to boil the water. Given the heat of vaporisation of {% katex inline %}2257 \mathrm{\ J/g}{% endkatex %} it will take {% katex inline %}850\mathrm{\ g} \cdot 2257 \mathrm{\ J/g} = 1918450\mathrm{\ J}{% endkatex %} to vaporise the water. The total energy required is thus {% katex inline %}285600 \mathrm{\ J} + 1918450 \mathrm{\ J} = 2204050\mathrm{\ J}{% endkatex %}. At a constant rate of 1000 J/s, this will take {% katex inline %}2204050 \mathrm{\ J} / 1000 \mathrm{\ J/s} = 2204.05\mathrm{\ s}{% endkatex %} (approximately half an hour) to evaporate all the water. And that’s it! ## Trying out other ideas As part of this exercise, you’ve created a Jupyter notebook with lots of information in it. You could try changing the initial temperature value (`initial_temperature`) to a different number and then re-run the entire notebook and see how long evaporation takes in that case. You can even start to think up crazy thought experiments like: - how long would it take to evaporate a pot of water if the boiling point of water was 50 °C instead of 100 °C? - how long would it take to evaporate a 10L bucket of water? - how much energy does it take to evaporate an Olympic-sized swimming pool? - how long would it take to evaporate a pot of ethanol? Give it a go and see what happens! 1. Tip: rewording the same question in different ways gives a new perspective and sometimes brings insight into how to solve a given question. [↩](#fnref:rewording-tip) 2. Note that the [solid, liquid and gaseous states](https://en.wikipedia.org/wiki/State_of_matter) are also called “phases”, thus one can talk about when water is in the “gaseous phase” or equivalently the “gaseous state”. [↩](#fnref:states-of-matter) 3. The heat of vaporisation is also called the [enthalpy of vaporisation](https://en.wikipedia.org/wiki/Enthalpy_of_vaporization), the latent heat of vaporisation, or the heat of evaporation. [↩](#fnref:heat-of-vaporisation-name)
peateasea
1,875,864
Principais Hooks no React com exercícios
O que são Hooks no React? De acordo com a documentação legacy do React Hooks são funções...
0
2024-06-03T21:59:27
https://dev.to/parkournick3/principais-hooks-no-react-com-exercicios-46m7
react, braziliandevs
### O que são Hooks no React? De acordo com a [documentação legacy do React](https://pt-br.legacy.reactjs.org/docs/hooks-overview.html) >Hooks são funções que permitem a você “ligar-se” aos recursos de state e ciclo de vida do React a partir de componentes funcionais. ## Lista com todos os hooks Existem vários Hooks Built-in no React ( está na versão react@18.3.1 no momento que estou escrevendo ) sendo eles: - useReducer - useContext - useRef - useImperativeHandle - useEffect - useLayoutEffect - useInsertionEffect - useMemo - useCallback - useTransition - useDeferredValue - useDebug - useId - useSyncExternalStore - useActionState https://pt-br.react.dev/reference/react/hooks ## Regras dos Hooks > Hooks são funções JavaScript, mas eles impões duas regras adicionais: - Apenas chame Hooks no nível mais alto. Não chame Hooks dentro de loops, condições ou funções aninhadas. - Apenas chame Hooks de componentes funcionais. Não chame Hooks de funções JavaScript comuns. (Há apenas um outro lugar válido para se chamar Hooks — dentro dos seus próprios Hooks customizados. Iremos aprender sobre eles em breve.) - O nome de um Hook deve sempre seguir o formato: useXxxxx ## Exercícios Entre neste [repositório](https://github.com/parkournick3/principais-hooks-react) e modifique os exercícios dentro da pasta "app > exercises"
parkournick3
1,875,907
Git Commands
Main Git Commands that are important to know! -Initialize a Repo % git init Enter...
0
2024-06-03T21:53:41
https://dev.to/mayas1111/git-commands-2mm
git, beginners, programming, terminal
Main Git Commands that are important to know! -Initialize a Repo % git init -Create a Commit % git add -A % git commit -m "Title of your snapshot" -Stage file on at a Time (not using "add -A") % git add path/to/file1 % git add location/of/file2 % git commit -m "My surgical commit" -Check your status often % git status -See what’s changed with diff % git diff -Create a new branch % git checkout -b fancy-new-version-name -Switch to a different branch To list all branches: % git branch To switch to another existing branch: % git checkout branch-name -See the git log To see the history of your current branch: % git log To see a graph of all your branches at once, try: % git log --oneline --decorate --graph --all -30 - Jumpback to a Previous Commit % git checkout [SHA of commit you want to go back to] -Push % git push The very first time you push to a branch, it may ask you to do something like: % git push --set-upstream origin your-branch-name -Start on a new task Start on a new task When you’re ready to start on a new task, the best practice is to first switch back to the main branch, get the freshest version, and then to start a new branch from there: % git checkout main % git pull % git checkout -b my-next-task
mayas1111
1,875,906
Learning 06/03/24
Durable Skills The Unspoken Rules - Gorick Ng | A helpful guide for tips in corporate...
0
2024-06-03T21:51:41
https://dev.to/dylansarikas/learning-060324-h2j
## Durable Skills 1. The Unspoken Rules - Gorick Ng | A helpful guide for tips in corporate America 2. Rueben's Bookclub - Wednesday's at 8am 3. Excel Basics down before June 18th - Fourmulas, Worksheet Basic, Modify Worksheet, Charts 4. Word Basics down beofre June 18th ## Updated ruby using homebrew 1. changed the $PATH to use ruby 3.3 instead of ruby 2.6, website used below 2. https://mac.install.guide/ruby/13 ## Good Rails Documentation 1. https://guides.rubyonrails.org/getting_started.html 2. https://guides.rubyonrails.org/active_record_basics.html 3. https://guides.rubyonrails.org/routing.html 4. https://guides.rubyonrails.org/action_controller_overview.html 5. https://guides.rubyonrails.org/active_record_validations.html ## Bootstrap 1. Bootstrap is a tool for simple CSS 2. Bootstrap Builds allows you to create a customized Boostrap ## Lecutre 1. One to Many vs Many to Many relationships 2. Foreign Key goes on the many table or the belongs to table 3. In rails, Model is Singular, Database table is Plural
dylansarikas
1,875,905
User behavior in the website or webapp
You can find our open-source repo on Github &amp; we hope you'll share some love with us and provide...
0
2024-06-03T21:51:22
https://dev.to/litlyx/user-behavior-in-the-website-or-webapp-3kg0
webdev, javascript, beginners, programming
You can find our open-source repo on [Github] (https://github.com/Litlyx/litlyx) & we hope you'll share some love with us and provide constructive feedback. **Kindly, leave a star to help us!** 🙏 share some love for 🇮🇹 devs! 🔥 --- Every great product starts with a simple idea. For us at [Litlyx](https://litlyx.com), it began with a realization: tracking analytics should be easy and accessible for everyone, regardless of their technical expertise. As developers and data enthusiasts, we understood the pain points faced by many businesses—setting up complex analytics tools, dealing with bulky software, and struggling to make sense of endless data streams. We envisioned a solution that was lightweight, easy to set up, and powerful enough to track essential KPIs in real-time. That's how our journey to build Litlyx began. Imagine a tool that requires just one line of code to start tracking over 10 key performance indicators. That’s [Litlyx](https://litlyx.com). We designed it to be open-source, allowing for high customization and flexibility. Whether you're a startup founder looking to understand user behavior, a marketer seeking insights into campaign performance, or a developer wanting to monitor system metrics, [Litlyx](https://litlyx.com) has got you covered. Our mission was clear: create an analytics solution that’s not only robust but also incredibly easy to implement. We aimed for a product that integrates seamlessly with your existing workflow, providing real-time insights without the overhead of traditional analytics platforms. One of the standout features of [Litlyx](https://litlyx.com) is its AI-powered data analyst assistant. This assistant helps you interpret complex data, offering actionable insights and generating comprehensive reports effortlessly. It’s like having a dedicated data analyst on your team, available 24/7, helping you make data-driven decisions with confidence. The feedback we've received from our community has been overwhelmingly positive. Users love how [Litlyx](https://litlyx.com) simplifies their analytics process, saving them time and resources while delivering precise, actionable data. --- Would you try it yourself for FREE??. Let’s revolutionize analytics together! Antonio | CEO & Founder at [Litlyx.com](https://litlyx.com)
litlyx
1,875,904
LEMIOUTGAMES
**I have been working on this game for the past 7 to 8 months. It's now available on Epic Games and...
0
2024-06-03T21:49:11
https://dev.to/jacobjufeili/lemioutgames-1858
gamedev, development
**I have been working on this game for the past 7 to 8 months. It's now available on Epic Games and Steam and there's a demo you can try out. I've been developing games for 1 year and 5 months, and I am continually learning how to make better games in the future. If you guys are interested here is link to my game https://store.steampowered.com/app/2836120/The_Nightmare_Of_Arrival_Chapter_1/ Regards, LEMIOUTGAMES AKA Jacob Jufeili**
jacobjufeili
1,875,903
Building Blocks Of Zig: slices
What are Zig Slices? Slices are a way to represent a contiguous sequence of elements in...
0
2024-06-03T21:42:59
https://dayvster.com/blog/building-blocks-of-zig-slices/
zig, programming, lowlevel
## What are Zig Slices? Slices are a way to represent a contiguous sequence of elements in Zig. They are essentially a single item pointer and a usize length. Slice types are defined as `[]T` where `T` is the type of the elements in the slice. Zig slices are used to represent arrays, string and other data structures that are contiguous in memory and can be accessed in a linear fashion. ## How Are Zig Slices Different From Arrays? Both single item arrays and slices in zig are fairly similar. You can get their length, iterate over them, and access their elements. In fact the Zig compiler will automatically convert a slice with an "unknown" length to a single item array pointer for us at compile time if we do not specify a predetermined fixed length for the slice that can be used during runtime. The main difference between slices and arrays in zig is that the slices length has to be known at runtime while the arrays length is part of the type and known at compile time. ## How To Create A Slice In Zig To create a slice in Zig you can use the `[]` syntax. Here is an example of creating a slice of integers: ```zig const std = @import("std"); pub fn main() void { // this array could be generated mathematically or a result of a function var arr = [_]i32{1,1,2,3,5,8,13,21,34,55}; // create a slice of the first 5 elements of the array var slice = arr[0..5]; } ``` What we have done there is created a slice out of the first 5 elements of the array. The slice is a pointer to the first element of the array and a length of 5. The array may be subject to change in length but the slice will always point to the first 5 elements of the array and always have a fixed length of 5. ## How To Access Elements In A Slice You can access elements in a slice using the `[]` syntax. Here is an example of accessing the first element in a slice: ```zig const std = @import("std"); pub fn main() void { var arr = [_]i32{1,1,2,3,5,8,13,21,34,55}; var slice = arr[0..5]; const firstElement = slice[0]; } ``` Just like with arrays, you can access elements in a slice using the `[]` syntax. The first element in the slice is accessed by using `slice[0]`. ## How To Iterate Over A Slice You can iterate over a slice using a for loop. Here is an example of iterating over a slice of integers: ```zig const std = @import("std"); pub fn main() void { var arr = [_]i32{1,1,2,3,5,8,13,21,34,55}; var slice = arr[0..5]; for (slice) |element| { std.debug.print("{d}\n", .{element}); } } ``` In this example we are simply iterating over each element in the slice and printing it out to the console. Much like you would with an array. ## Conclusion Slices are a powerful feature in Zig that allow you to work with contiguous sequences of elements. They are similar to arrays but have a few key differences. Slices are a pointer to the first element of the sequence and a length. You can create slices using the `[]` syntax and access elements in a slice using the `[]` syntax. You can also iterate over a slice using a for loop. Slices are a fundamental building block in Zig and are used to represent arrays, strings and other data structures that are contiguous in memory and have a fixed length that is known at runtime.
dayvster
1,875,902
Prometheus and Grafana: A Beginner's Guide
1. Prometheus Stores Data: Collects and stores time-series data from different sources...
0
2024-06-03T21:42:36
https://dev.to/vaibhavhariaramani/prometheus-and-grafana-a-beginners-guide-3e31
## 1. Prometheus Stores Data: - Collects and stores time-series data from different sources (exporters). - Acts like a data library, organizing and saving metrics over time. - Automatically manages storage by removing older data to make space for new. - Stores metrics in compressed and optimized format that's easy to query and retrieve. - Requires installation of exporters on the systems you want to monitor. ## 2. Grafana: - Grafana is a visualization and dashboarding tool that allows you to create interactive and customizable dashboards - Grafana integrates seamlessly with Prometheus and other data sources to display time-series data in a user-friendly and informative way. - When you set up Grafana, you configure it to connect to your Prometheus instance as a data source. - Grafana queries the Prometheus database to retrieve the metrics you want to visualize. - Creates custom dashboards to display data in an understandable way. ## Working Together: - Exporters (e.g., , mysqld_exporter) are needed to provide metrics. - Prometheus scrapes metrics from exporters at scheduled intervals. - Grafana connects to Prometheus to access and request specific metrics. - Grafana translates Prometheus data into dynamic, colorful visualizations. - This collaboration allows monitoring and informed decision-making. ## Conclusion As you start using Prometheus and Grafana to keep an eye on your apps and make sure they work well, think of these tools as your helpful companions. Don't hesitate to dive deeper, experiment, and explore the vast capabilities they offer.
vaibhavhariaramani
1,875,900
Testing Bunjs Web Application With Cucumber Js And Keploy
In our previous blog, we explored how to build a modern web server using BunJs and Prisma,...
0
2024-06-03T21:37:35
https://keploy.io/blog/community/testing-bunjs-web-application-with-cucumber-js-and-keploy
webdev, programming, python, ai
In our previous blog, we explored how to build a modern web server using BunJs and Prisma, integrating robust authentication mechanisms with JWT tokens. Now, it's time to ensure our application is reliable and error-free through thorough testing. In this blog, we'll dive into testing methodologies using Cucumber JS and Keploy, both are a powerful tools that streamline the testing process and enhance the quality of our application. **Understanding the Importance of Testing** By systematically executing test cases, developers can uncover bugs and errors early in the development process, preventing costly issues in later stages. For instance, in our BunJs web application, thorough testing would involve scenarios such as user authentication, post creation, and database interactions. By testing each feature extensively, developers can verify that user authentication works as expected, posts are created and retrieved accurately, and database queries return the correct results. And testing our BunJs application's authentication mechanism ensures that users can securely sign up, log in, and access protected resources. Additionally, performance testing can validate that the application performs efficiently, even under high traffic loads. By prioritizing testing throughout the development lifecycle, teams can build robust, secure, and user-friendly applications that meet the needs and expectations of their users while minimizing the risk of critical failures and enhancing overall quality. **Testing BunJs with Cucumber JS** First, let's create our work directory and install necessary dependencies via npm: ``` mkdir features && mkdir features/support npm i @cucumber/cucumber chai ``` Let's move towards writing the tests and setting up folder structures for cucumber-js; this is how the folder structure should look like ``` ├── features │ ├── support │ │ ├── steps.mjs │ ├── post.feature ``` We have already prepared our folder structure similar to above while installing dependencies,so now let's start with steps.mjs file: - ``` import { Given, When, Then } from '@cucumber/cucumber'; import { expect } from 'chai'; import axios from 'axios'; let createdRecipeId; Given('I have a valid token', async function () { // Signin to get the valid token this.token = 'eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJpZCI6Ijk3Y2E1MWUzLWFiMWYtNDdkZC04ODM3LWFmMjkwZGQ1ZDAzYiIsImVtYWlsIjoiaXNzc2FsY3VwbmFtZGVAYWJjLmNvbSIsImlhdCI6MTcxNTU4MjEyNCwiZXhwIjoxNzE1NjY4NTI0fQ.T3WR8TO1uiV9t_ZIPm93JbdgWpYeXiUkRW3CUeyyOVQ'; }); When('I create a new recipe with title {string} and body {string}', async function (title, body) { try { const response = await axios.post('http://localhost:4040/create-post', { title: title, body: body, }, { headers: { Authorization: `Bearer ${this.token}`, }, }); expect(response.status).to.equal(200); if (response.data && response.data.recipe && response.data.recipe.id) { createdRecipeId = response.data.recipe.id; } else { throw new Error('Failed to retrieve recipe ID from response'); } } catch (error) { console.error('Error:', error); // Log any errors this.error = error.response.data.error; } }); Then('I should receive a successful response with the created recipe', function () { expect(this.error).to.be.undefined; expect(createdRecipeId).to.not.be.undefined; }); Given('I have an invalid token', function () { this.token = 'eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJpZCI6MSwiZW1haWwiOiJ4eXpAYWJjLmNvbSIsImlhdCI6MTcxMzI1NTk2NSwiZXhwIjoxNzEzMzQyMzY1fQ.0RvrxVrkG6pQNGw0tjcDFqQuhmbVCmUcXuEy1brMED0'; // Create an Expired Token }); When('I attempt to create a new recipe with title {string} and body {string}', async function (title, body) { try { const response = await axios.post('http://localhost:4040/create-post', { title: title, body: body, }, { headers: { Authorization: `Bearer ${this.token}`, }, }); if (response.data && response.data.recipe && response.data.recipe.id) { createdRecipeId = response.data.recipe.id; } } catch (error) { console.error('Error:', error); // Log any errors this.error = error.response.data.error; this.responseStatus = error.response.status; } }); Then('I should receive an ok response with status code {int}', function (statusCode) { expect(this.error).to.be.undefined; expect(createdRecipeId).to.not.be.undefined; }); ``` **Writing Feature Files with Gherkin Syntax** Now that we have our step file ready, it's time to create our post.feature file based on our steps. ``` Feature: Creating a new recipe post Scenario: Create a new recipe post with a valid token Given I have a valid token When I create a new recipe with title "Delicious Pasta" and body "A simple pasta recipe" Then I should receive a successful response with the created recipe Scenario: Attempt to create a new recipe post with an invalid token Given I have an invalid token When I attempt to create a new recipe with title "Delicious Pasta" and body "A simple pasta recipe" Then I should receive an ok response with status code 200 ``` **Executing Tests with Cucumber JS** Now that we have our post.features and steps.mjs ready to be executed, let's start our application first before running our test. ``` # Start our database instance sudo docker-compose up -d # Start our application in dev mode bun --watch index.ts ``` Once we have our application and postgres database instance up and running, we can executed our Cucumber tests:- ``` npx cucumber-js ``` We will see that all our test secaniors has passed: - ![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/662zvj8mvpzcyuwe2q8u.png) But what happens once our valid token expire would the test cases still pass? Let's replace our valid token with invalid token and see if our test cases are still passing or not ``` // existing steps ... Given('I have a valid token', async function () { // Replaced the token with invalid token this.token = 'eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJpZCI6MSwiZW1haWwiOiJ4eXpAYWJjLmNvbSIsImlhdCI6MTcxMzI1NTk2NSwiZXhwIjoxNzEzMzQyMzY1fQ.0RvrxVrkG6pQNGw0tjcDFqQuhmbVCmUcXuEy1brMED0'; }); ... //existing steps ``` Now when we run our tests again we get:- ![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/uoq1cv47d9qdqkr7gd4c.png) Our first scenario failed as the token we provided was not correct. This is one of the scenario where token has been expired or invalid token, this is a common problem while writting e2e tests with cucumber, each time we have to provide token for the scenario to be passed since after a while they will get expried. **Introduction to Keploy** Keploy is an Open Source API testing platform to generate Test cases out of data calls along with data mocks. In simple words, with keploy we don’t have to create or maintain manual test cases. As it records all network interactions from the application and based on expected responses & request it generates test cases and data mocks to make our work easy and efficient. **Testing BunJs application with Keploy** Let's get started by installing the Keploy with one-click command:- ``` curl -O https://raw.githubusercontent.com/keploy/keploy/main/keploy.sh && source keploy.sh ``` You should see something like this: ``` ▓██▓▄ ▓▓▓▓██▓█▓▄ ████████▓▒ ▀▓▓███▄ ▄▄ ▄ ▌ ▄▌▌▓▓████▄ ██ ▓█▀ ▄▌▀▄ ▓▓▌▄ ▓█ ▄▌▓▓▌▄ ▌▌ ▓ ▓█████████▌▓▓ ██▓█▄ ▓█▄▓▓ ▐█▌ ██ ▓█ █▌ ██ █▌ █▓ ▓▓▓▓▀▀▀▀▓▓▓▓▓▓▌ ██ █▓ ▓▌▄▄ ▐█▓▄▓█▀ █▓█ ▀█▄▄█▀ █▓█ ▓▌ ▐█▌ █▌ ▓ Keploy CLI Available Commands: example Example to record and test via keploy generate-config generate the keploy configuration file record record the keploy testcases from the API calls test run the recorded testcases and execute assertions update Update Keploy Flags: --debug Run in debug mode -h, --help help for keploy -v, --version version for keploy Use "keploy [command] --help" for more information about a command. ``` Now we are all set to create testcases with keploy. **Create Tests for our BunJs application** Since Keploy uses eBPF to instrument applications without code changes, all we need to do is pass application running command to keploy:- ``` keploy record -c "bun --watch index.ts" ``` Let's make API calls to record the interaction between our BunJs application and Prisma-ORM based Postgres ``` ## Create User curl --request POST \ --url http://localhost:4040/signup \ --header 'Content-Type: application/json' \ --data '{ "name":"Yash", "email":"isssalcupnamde@rbc.com", "password":"1234" }' ## Login User curl --request POST \ --url http://localhost:4040/login \ --header 'Content-Type: application/json' \ --data '{ "email":"isssalcupnamde@rbc.com", "password":"1234" }' ## Create a Post curl --request POST \ --url http://localhost:4040/create-post \ --header 'Content-Type: application/json' \ --header 'Authorization: Bearer eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJlbWFpbCI6Imlzc3NhbGN1cG5hbWRlQHJiYy5jb20iLCJpYXQiOjE3MTU1ODQzMDYsImV4cCI6MTcxNTY3MDcwNn0.G7llqJc27ZQFunDiNjduMt9FZ2B4MbB0Xbhk_y7pzT0' \ --data '{ "title":"Anime", "body":"AOT from quantum universe" }' ``` We should be able to see something like this:- ![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/4dhzvdw35d0l466jtlod.png) Once we have our test cases ready, let's execute them in keploy test mode:- ``` keploy test -c "bun --watch index.ts" ``` We will notice that one of our test cases failed due to fact the each time the user.token would be different ![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/0s7gyp8nsfj9pdx9dlnn.png) So to avoid this keploy provides two feature, time-freezing and denoising, for this blog we are using denoising feature. We know that our test-2 is failing, so let's open the test-2.yaml file : - ``` version: api.keploy.io/v1beta1 kind: Http name: test-2 spec: metadata: {} req: method: POST proto_major: 1 proto_minor: 1 url: http://localhost:4040/login header: Accept: '*/*' Accept-Encoding: gzip, deflate, br Cache-Control: no-cache Connection: keep-alive Content-Length: "63" Content-Type: application/json Host: localhost:4040 Postman-Token: 8568266d-8c8e-41c3-95cc-5782f7f2c717 User-Agent: PostmanRuntime/7.32.1 body: |- { "email":"isssalcupnamde@rbc.com", "password":"1234" } timestamp: 2024-05-13T12:41:46.83176148+05:30 resp: status_code: 200 header: Content-Length: "224" Content-Type: application/json Date: Mon, 13 May 2024 07:11:46 GMT body: '{"message":"User logged in successfully","token":"eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJlbWFpbCI6Imlzc3NhbGN1cG5hbWRlQHJiYy5jb20iLCJpYXQiOjE3MTU1ODQzMDYsImV4cCI6MTcxNTY3MDcwNn0.G7llqJc27ZQFunDiNjduMt9FZ2B4MbB0Xbhk_y7pzT0"}' status_message: OK proto_major: 0 proto_minor: 0 timestamp: 2024-05-13T12:41:49.018139032+05:30 objects: [] assertions: noise: header.Date: [] body.token: [] created: 1715584309 curl: |- curl --request POST \ --url http://localhost:4040/login \ --header 'Host: localhost:4040' \ --header 'User-Agent: PostmanRuntime/7.32.1' \ --header 'Cache-Control: no-cache' \ --header 'Postman-Token: 8568266d-8c8e-41c3-95cc-5782f7f2c717' \ --header 'Content-Type: application/json' \ --header 'Accept: */*' \ --header 'Connection: keep-alive' \ --header 'Accept-Encoding: gzip, deflate, br' \ --data '{ "email":"isssalcupnamde@rbc.com", "password":"1234" }' ``` And under noise add body.token: [] :- ``` assertions: noise: header.Date: [] body.token: [] ``` Now let's run our testcases again, we can see that our testcases have passed except one which is failing due the error of prisma which as been reported to prisma here:- Could not figure out an ID in create · Issue #23907 · prisma/prisma (github.com) ![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/dt5ztjqhbtqs8ls28mjk.png) **Conclusion** In this comprehensive guide, we've explored the process of testing a BunJs web application using Cucumber JS and Keploy. By leveraging these powerful tools, developers can ensure the reliability, security, and functionality of their applications. With a focus on Behavior-Driven Development (BDD) and automated testing, teams can streamline their testing process and deliver high-quality software with confidence. As testing continues to evolve, embracing new tools and methodologies is essential for staying ahead in the ever-changing landscape of web development. **FAQ's** **What are the benefits of testing a BunJs application with Cucumber JS and Keploy?** Testing with Cucumber JS allows for behavior-driven development (BDD), ensuring that the application behaves as expected from the user's perspective. Keploy simplifies testing by automatically generating test cases based on recorded interactions, reducing manual effort and improving efficiency. **How does Cucumber JS help in testing BunJs applications?** Cucumber JS allows developers to write test scenarios in plain language using the Gherkin syntax, making it easy to understand and collaborate on tests. These scenarios can then be executed against the application to validate its behavior. **What is the advantage of using Keploy for testing BunJs applications?** Keploy automates the process of generating test cases by recording interactions between the application and external services. This eliminates the need for manual test case creation and ensures thorough test coverage. How does Keploy handle authentication tokens in BunJs application testing Keploy provides features like time-freezing and denoising to handle dynamic data like authentication tokens. These features ensure that tests remain stable even when data changes, such as token expiration, by allowing developers to specify which parts of the response to ignore during comparison. **Can Keploy be used for performance testing of BunJs applications?** While Keploy primarily focuses on functional testing by generating test cases from recorded interactions, it can indirectly contribute to performance testing by ensuring that the application functions correctly under various scenarios and load conditions. However, for specific performance testing needs, additional tools may be required. **How does testing with Cucumber JS and Keploy enhance the reliability of BunJs applications?** By systematically executing test cases and automating test generation, Cucumber JS and Keploy help identify bugs and errors early in the development process. This results in more reliable and robust BunJs applications that meet user expectations and minimize the risk of critical failures.
keploy
1,875,899
Shadcn-ui codebase analysis: Perfect Next.js dark mode in 2 lines of code with next-themes.
So I wanted to figure out how ui.shadcn.com implemented dark mode on their website. I looked at its...
0
2024-06-03T21:36:49
https://dev.to/ramunarasinga/shadcn-ui-codebase-analysis-perfect-nextjs-dark-mode-in-2-lines-of-code-with-next-themes-8f5
javascript, nextjs, opensource, shadcnui
So I wanted to figure out how [ui.shadcn.com](http://ui.shadcn.com) implemented dark mode on their website. I looked at its [source code](https://github.com/shadcn-ui/ui/blob/main/apps/www/app/layout.tsx). These things usually lie in providers. ![](https://media.licdn.com/dms/image/D4E12AQHaNMwhN2LNjw/article-inline_image-shrink_1500_2232/0/1717449447046?e=1723075200&v=beta&t=tEzGDEwcnnlgbs9mTCymVaQBRtFg60_0EOal5pXyxi4) That is when I came across [next-themes](https://github.com/pacocoursey/next-themes/tree/main). You can easily add dark mode to your next.js app using next-themes. In this article, you will learn the below concepts: 1. How to configure next-themes in Next.js? 2. How is next-themes configured in shadcn-ui/ui? 3. useTheme to toggle dark/light modes. 4. How is useTheme written in shadcn-ui/ui? > _Want to learn how to build shadcn-ui/ui from scratch? Check out_ [_build-from-scratch_](https://github.com/Ramu-Narasinga/build-from-scratch) _and give it a star if you like it. Sovle challenges to build shadcn-ui/ui from scratch. If you are stuck or need help?_ [_there is a solution_](https://tthroo.com/build-from-scratch)_._ How to configure next-themes in Next.js? ---------------------------------------- ### With app/ You’ll need to update your app/layout.jsx to use next-themes. The simplest layout looks like this: ``` // app/layout.jsx export default function Layout({ children }) { return ( <html> <head /> <body>{children}</body> </html> ) } ``` Adding dark mode support takes 2 lines of code: ``` // app/layout.jsx import { ThemeProvider } from 'next-themes' export default function Layout({ children }) { return ( <html suppressHydrationWarning> <head /> <body> <ThemeProvider>{children}</ThemeProvider> </body> </html> ) } ``` Note that ThemeProvider is a client component, not a server component. > _Note! If you do not add_ [_suppressHydrationWarning_](https://reactjs.org/docs/dom-elements.html#suppresshydrationwarning:~:text=It%20only%20works%20one%20level%20deep) _to your_ <html> _you will get warnings because_ next-themes _updates that element. This property only applies one level deep, so it won't block hydration warnings on other elements._ How is next-themes configured in shadcn-ui/ui? ---------------------------------------------- The answer is in [Layout.tsx](https://github.com/shadcn-ui/ui/blob/main/apps/www/app/layout.tsx#L89), it has a [ThemeProvider](https://github.com/shadcn-ui/ui/blob/main/apps/www/components/providers.tsx#L10) imported from [@/components/providers.tsx](https://github.com/shadcn-ui/ui/blob/main/apps/www/components/providers.tsx#L10). Shadcn-ui/ui follows the same configuration provided in the official documentation, except for few properties. They are shown in the image below: ![](https://media.licdn.com/dms/image/D4E12AQG2sSFbALv2Vw/article-inline_image-shrink_1500_2232/0/1717449445888?e=1723075200&v=beta&t=zSJYHkdqDLZP16YyoVFCPWN3rxr6mSMIuz7G-A6Em1M) * attribute = 'data-theme': HTML attribute modified based on the active theme, accepts class and data-\* (meaning any data attribute, data-mode, data-color, etc.) ([example](https://github.com/pacocoursey/next-themes/tree/main#class-instead-of-data-attribute)) * defaultTheme = 'system': Default theme name (for v0.0.12 and lower the default was light). If enableSystem is false, the default theme is light * enableSystem = true: Whether to switch between dark and light based on prefers-color-scheme * disableTransitionOnChange = false: Optionally disable all CSS transitions when switching themes ([example](https://github.com/pacocoursey/next-themes/tree/main#disable-transitions-on-theme-change)) useTheme to toggle dark/light modes. ------------------------------------ Your UI will need to know the current theme and be able to change it. The useTheme hook provides theme information: ``` import { useTheme } from 'next-themes' const ThemeChanger = () => { const { theme, setTheme } = useTheme() return ( <div> The current theme is: {theme} <button onClick={() => setTheme('light')}>Light Mode</button> <button onClick={() => setTheme('dark')}>Dark Mode</button> </div> ) } ``` > _Warning! The above code is hydration unsafe and will throw a hydration mismatch warning when rendering with SSG or SSR. This is because we cannot know the_ theme _on the server, so it will always be_ undefined _until mounted on the client._ How is useTheme written in shadcn-ui/ui? ---------------------------------------- [mode-toggle.tsx](https://github.com/shadcn-ui/ui/blob/13d9693808badd4b92811abac5e18dc1cddf2384/apps/www/components/mode-toggle.tsx#L6) exports a component named ModeToggle which is used in [site-header.tsx](https://github.com/shadcn-ui/ui/blob/13d9693808badd4b92811abac5e18dc1cddf2384/apps/www/components/site-header.tsx#L9) ModeToggle in the header on [ui.shadcn.com](http://ui.shadcn.com) is shown below: ![](https://media.licdn.com/dms/image/D4E12AQH4BiVBGU5UqA/article-inline_image-shrink_1500_2232/0/1717449446075?e=1723075200&v=beta&t=S7Lwl_SscfBkprYkVQp7RSgc5xuZIV0d4b03N5_l2-I) The following code is from mode-toggle.tsx ``` "use client" import \* as React from "react" import { MoonIcon, SunIcon } from "@radix-ui/react-icons" import { useTheme } from "next-themes" import { Button } from "@/registry/new-york/ui/button" import { DropdownMenu, DropdownMenuContent, DropdownMenuItem, DropdownMenuTrigger, } from "@/registry/new-york/ui/dropdown-menu" export function ModeToggle() { const { setTheme } = useTheme() return ( <DropdownMenu> <DropdownMenuTrigger asChild> <Button variant="ghost" className="w-9 px-0"> <SunIcon className="h-\[1.2rem\] w-\[1.2rem\] rotate-0 scale-100 transition-all dark:-rotate-90 dark:scale-0" /> <MoonIcon className="absolute h-\[1.2rem\] w-\[1.2rem\] rotate-90 scale-0 transition-all dark:rotate-0 dark:scale-100" /> <span className="sr-only">Toggle theme</span> </Button> </DropdownMenuTrigger> <DropdownMenuContent align="end"> <DropdownMenuItem onClick={() => setTheme("light")}> Light </DropdownMenuItem> <DropdownMenuItem onClick={() => setTheme("dark")}> Dark </DropdownMenuItem> <DropdownMenuItem onClick={() => setTheme("system")}> System </DropdownMenuItem> </DropdownMenuContent> </DropdownMenu> ) } ``` In order to switch modes, setTheme function is exposed by the useTheme hook. Conclusion: ----------- This approach seems quite straight forward, except for few additional properties passed into ThemeProvider in shadcn/ui. You need to first configure the ThemeProvider and then use the useTheme hook to switch dark/light modes. About me: --------- Website: [https://ramunarasinga.com/](https://ramunarasinga.com/) Linkedin: [https://www.linkedin.com/in/ramu-narasinga-189361128/](https://www.linkedin.com/in/ramu-narasinga-189361128/) Github: [https://github.com/Ramu-Narasinga](https://github.com/Ramu-Narasinga) Email: [ramu.narasinga@gmail.com](mailto:ramu.narasinga@gmail.com) References: ----------- 1. [https://github.com/shadcn-ui/ui/blob/main/apps/www/app/layout.tsx](https://github.com/shadcn-ui/ui/blob/main/apps/www/app/layout.tsx) 2. [https://github.com/shadcn-ui/ui/blob/main/apps/www/components/providers.tsx#L10](https://github.com/shadcn-ui/ui/blob/main/apps/www/components/providers.tsx#L10) 3. [https://github.com/pacocoursey/next-themes/tree/main](https://github.com/pacocoursey/next-themes/tree/main) 4. [https://github.com/shadcn-ui/ui/blob/13d9693808badd4b92811abac5e18dc1cddf2384/apps/www/components/mode-toggle.tsx#L6](https://github.com/shadcn-ui/ui/blob/13d9693808badd4b92811abac5e18dc1cddf2384/apps/www/components/mode-toggle.tsx#L6) 5. [https://github.com/shadcn-ui/ui/blob/13d9693808badd4b92811abac5e18dc1cddf2384/apps/www/components/site-header.tsx#L9](https://github.com/shadcn-ui/ui/blob/13d9693808badd4b92811abac5e18dc1cddf2384/apps/www/components/site-header.tsx#L9) 6. [https://github.com/shadcn-ui/ui/blob/13d9693808badd4b92811abac5e18dc1cddf2384/apps/www/app/(app)/layout.tsx](https://github.com/shadcn-ui/ui/blob/13d9693808badd4b92811abac5e18dc1cddf2384/apps/www/app/(app)/layout.tsx)
ramunarasinga
1,812,754
Integrate Snowflake with Laravel
Snowflake is a cloud-based data warehousing service that offers high performance, scalability, and...
0
2024-06-03T21:29:55
https://dev.to/emanuelnav/integrate-snowflake-with-laravel-450g
laravel, php, snowflake, database
Snowflake is a cloud-based data warehousing service that offers high performance, scalability, and flexibility for managing large volumes of data. Using the offical pdo driver, PHP applications can directly interact with Snowflake, enabling seamless execution of queries and retrieval of data. In order to integrate Snowflake with our Laravel application using PostgreSQL we're going to use the [laravel-pdo-odbc](https://github.com/appsfortableau/laravel-pdo-odbc) package and the [pdo_snowflake](https://github.com/snowflakedb/pdo_snowflake) PHP PDO driver from snowflake. At the end of the post I leave a script with all the steps to build and install the driver in a Dockerfile. > NOTE: Snowflake PHP PDO driver does not yet support ARM/AARCH64 architecture on Linux. ## PHP PDO Driver First we have to build and install the pdo driver. ### Prerequisites To build the Snowflake PHP PDO Driver, we need to have installed the following software: On Linux: - PHP 8.1 or higher (Note: support for PHP 8.0 or lower is deprecated). - gcc 5.2 or higher. - cmake 2.8 or higher And the following php modules: - php-pdo - pdo_pgsql - pdo_odbc ### Building the Driver 1.Set the PHP_HOME environment variable to the path to the bin directory containing the `phpize` executable. For example, if the `phpize` executable is in `/usr/local/bin`, run the following command: ``` export PHP_HOME=/usr/local ``` 2.Clone the `pdo_snowflake` repository, and run the script to build the driver: ``` git clone https://github.com/snowflakedb/pdo_snowflake.git cd pdo_snowflake ./scripts/build_pdo_snowflake.sh ``` To verify that the driver was succesfully built, run the next command: ``` $PHP_HOME/bin/php -dextension=modules/pdo_snowflake.so -m | grep pdo_snowflake ``` It should appear `pdo_snowflake` in the output from the command. ### Installing the Driver 1.Copy `pdo_snowflake.so` from the modules subdirectory in the repository to the PHP extension directory. ``` cp modules/pdo_snowflake.so /usr/local/lib/php/extensions/no-debug-non-zts-*/ ``` 2.Copy `cacert.pem` from the `libsnowflakeclient` subdirectory in the repository to the PHP configuration directory containing the PHP configuration files. To find the PHP configuration directory, you can use this command `$PHP_HOME/bin/php -ini`. ``` cp ./libsnowflakeclient/cacert.pem /usr/local/etc/php/cacert.pem ``` 3.In the same directory that contains the PHP configuration files, create a config file named `pdo_snowflake.ini` that contains the following settings: ``` extension=pdo_snowflake.so pdo_snowflake.cacert=<path to PHP config directory>/cacert.pem ``` 4.If you are using PHP with an application server or web server (e.g. Apache or nginx), restart the server. ## Integrating the PHP Driver in Laravel Once we have the driver set up we need to install the package to make the integration with laravel. 1.To add the package to your project, run the following command: ``` composer require yoramdelangen/laravel-pdo-odbc ``` 2.Register the service provider in the `app` file from you project: ``` // app.php 'providers' => [ // ... LaravelPdoOdbc\ODBCServiceProvider::class, ]; ``` 3.Add a Database configuration into the `database` file: ``` // database.php 'snowflake' => [ 'driver' => 'snowflake_native', 'account' => '{account_name}.eu-west-1', 'username' => '{username}', 'password' => '{password}', 'database' => '{database}', 'warehouse' => '{warehouse}', 'schema' => 'PUBLIC', // change it if necessary. 'options' => [ // Required for Snowflake usage \PDO::ODBC_ATTR_USE_CURSOR_LIBRARY => \PDO::ODBC_SQL_USE_DRIVER ] ], ``` 4.Finish! Now you can use Eloquent ORM, and other Illuminate components as usual. ``` # Facade $users = DB::connection('snowflake') ->table('users') ->where('created_at', '>', '2024-03-15') ->get(); # ORM $users = User::all(); ``` To know more about the PHP pdo driver and the laravel package, you can check the documentation here: PHP PDO drive: https://github.com/snowflakedb/pdo_snowflake Laravel package: https://github.com/appsfortableau/laravel-pdo-odbc ## Dockerfile If you use Docker in your local environment, here is the script to add into your dockerfile to download and install the php pdo driver. > NOTE: If you are using Docker on an ARM architecture, you can force it to a x86 architecture adding `platform linux/x86_64` on the `docker-compose.yml` file in the container that you are installing the driver. ``` # Dockerfile # Install system dependencies RUN apt-get update && apt-get install -y \ cmake \ && docker-php-ext-configure pgsql -with-pgsql=/usr/local/pgsql \ && apt-get clean && rm -rf /var/lib/apt/lists/* \ && docker-php-ext-configure pdo_odbc --with-pdo-odbc=unixODBC,/usr \ && docker-php-ext-install \ pdo \ pdo_pgsql \ pdo_odbc \ ENV PHP_HOME /usr/local # Pull the Snowflake PDO repo and install the driver RUN mkdir /tmp/pdo_snowflake && \ git clone https://github.com/snowflakedb/pdo_snowflake.git /tmp/pdo_snowflake RUN cd /tmp/pdo_snowflake && \ bash ./scripts/build_pdo_snowflake.sh && \ cp modules/pdo_snowflake.so /usr/local/lib/php/extensions/no-debug-non-zts-*/ && \ cp ./libsnowflakeclient/cacert.pem /usr/local/etc/php/cacert.pem RUN echo "extension=pdo_snowflake.so" > /usr/local/etc/php/conf.d/pdo_snowflake.ini && \ echo "pdo_snowflake.cacert=/usr/local/etc/php/cacert.pem" >> /usr/local/etc/php/conf.d/pdo_snowflake.ini ```
emanuelnav
1,875,897
test
A post by Suresh Kumar
0
2024-06-03T21:27:23
https://dev.to/suresh_kumar_ee6ad89b3646/test-3kc2
suresh_kumar_ee6ad89b3646
1,875,896
You should probably have a Bragging Doc
Getting a dev job is one thing, but being recognized at that job is another. Expanding on the advice...
0
2024-06-03T21:27:13
https://bryanliao.dev/blog/you-should-probably-have-a-bragging-doc/
career
Getting a dev job is one thing, but being recognized at that job is another. Expanding on the advice of advocating for yourself, it’s important that you keep track of your own accomplishments and contributions to the company. I’ve personally been pretty terrible at keeping track of the work that I’ve done and had trouble showing the “impact” that I’ve had on my team. I had the mentality that my work would speak for itself. Silly me, that’s incorrect and a terrible way to think 🙂 When performance reviews came around I was scrambling to remember everything I had worked on in the past year and talk up how much I was improving the product. There’s also a social aspect of contribution that’s harder to track down. Aside from performance reviews, I believe it’s also a good idea to keep a bragging doc handy for when you’re trying to get promoted. At least where I’ve worked, there’s usually some process of collecting proof that you’re performing at the next level. There’s more involvement with your manager, but the idea is similar on your end. It may sound like a lot of work to maintain, but it’ll save you a lot of cramming and searching once you start. Future you will thank you. Probably 😛
liaob
1,875,892
What are the pros and cons of using Terraform vs Ansible for multi-cloud deployments?
What is Terraform? Terraform is an open-source tool that allows you to define, provision,...
0
2024-06-03T21:12:49
https://dev.to/vaibhavhariaramani/what-are-the-pros-and-cons-of-using-terraform-vs-ansible-for-multi-cloud-deployments-4k14
## What is Terraform? Terraform is an open-source tool that allows you to define, provision, and update your cloud infrastructure using a declarative language called HCL (HashiCorp Configuration Language). Terraform can work with multiple cloud providers, such as AWS, Azure, Google Cloud, and more, as well as other services, such as Kubernetes, Docker, and GitHub. Terraform uses a state file to keep track of the current and desired state of your resources, and applies changes to your infrastructure by creating, modifying, or deleting resources as needed. ## 2. What is Ansible? Ansible is an open-source tool that automates the configuration, deployment, and orchestration of your cloud applications and servers using a simple and human-readable language called YAML (Yet Another Markup Language). Ansible can also work with multiple cloud providers, as well as other platforms, such as Linux, Windows, VMware, and more. Ansible uses an agentless architecture, which means you do not need to install any software on the remote hosts you want to manage. Ansible executes tasks on the remote hosts by using SSH or WinRM protocols, and reports the results back to you. ## 3 When to use Terraform? Terraform is ideal for creating and managing the underlying infrastructure of your cloud environment, such as networks, security groups, load balancers, databases, and more. Terraform allows you to codify your infrastructure as code, which means you can version control, test, and reuse your code across different environments and projects. Terraform also enables you to leverage the cloud-native features of each provider, such as tags, policies, and roles, and integrate them with your Terraform code. Terraform is also great for handling complex dependencies and parallelism among your resources, as well as scaling up or down your infrastructure according to your demand. ## 4 When to use Ansible? Ansible is ideal for configuring and deploying your cloud applications and servers, such as installing software packages, setting up users and permissions, running scripts, and more. Ansible allows you to automate your repetitive and tedious tasks, which saves you time and reduces human errors. Ansible also enables you to modularize your code into reusable units called roles and playbooks, which can be customized and parameterized according to your needs. Ansible is also great for orchestrating your workflows across multiple hosts and groups, as well as performing ad-hoc commands and checks on your remote hosts. ## 5 What are the pros of Terraform? Using Terraform offers a range of advantages, such as supporting a wide range of cloud providers and services, using a declarative language, maintaining a consistent state of your infrastructure, allowing dry runs and plans before applying changes, and integrating with other tools and platforms. This makes it easier to track changes, avoid conflicts or drifts, gain more confidence and control over your actions, and enhance DevOps practices. ## 6 What are the cons of Terraform? Using Terraform can be challenging, as it has a steep learning curve and requires careful management of the state file. Errors or inconsistencies can arise if not handled properly. Additionally, it may be slow or inefficient when dealing with large or complex infrastructures, and difficult to troubleshoot when something goes wrong due to the vague error messages and logs. Furthermore, customizing or extending the functionality of Terraform depends on the availability and quality of the providers and modules that you use.
vaibhavhariaramani
1,875,891
JobCopilot - Get 10x more job interviews with job application automation
JobCopilot helps you get more job interviews by automating job applications. Your AI JobCopilot...
0
2024-06-03T21:06:46
https://dev.to/jobcopilot/jobcopilot-get-10x-more-job-interviews-with-job-application-automation-3768
b2c, saas, employment, ai
JobCopilot helps you get more job interviews by automating job applications. Your AI JobCopilot auto-applies up to 1,500 relevant jobs each month, from over 50,000 companies worldwide. No more missing out on job opportunities or applying too late to be considered. Stop stressing about finding newly posted jobs, your copilot finds them for you. Try it today! [https://jobcopilot.com](https://jobcopilot.com)
jobcopilot
1,875,890
Utilizando react-native-calendars na prática
React Native Calendars é um componente de calendário para iOS e Android. Ele oferece uma variedade de...
0
2024-06-03T21:05:43
https://dev.to/marcoswillianr/utilizando-react-native-calendars-na-pratica-2egc
reactnative, uidesign, javascript
React Native Calendars é um componente de calendário para iOS e Android. Ele oferece uma variedade de funcionalidades e é completamente escrito em JavaScript, o que significa que não há necessidade de código nativo. Neste tutorial, vamos recriar no React Native uma tela que encontrei no Dribbble. Este design combina estilo e funcionalidade, e você pode conferir o design original [aqui](https://dribbble.com/shots/17884784-Doctor-Appointment-Medical-Mobile-App-UI). Vamos explorar algumas características do React Native Calendars e ver como podemos usá-lo para criar uma interface de usuário atraente e eficiente. --- #### Pré-requisitos Para me acompanhar nesse projeto não é necessário muito, basta ter o **NodeJS** instalado. #### Iniciando o projeto Nesse projeto vou estar utilizando o [Expo](https://expo.dev/), caso você não conheça, segundo a própria documentação do React Native, ele é um framework de React Native que oferece ferramentas de desenvolvimento que facilitam a criação de aplicativos, como uma biblioteca padrão de módulos nativos e muito mais. Vamos começar criando um projeto React Native utilizando o seguinte comando no terminal: `$ npx create-expo-app --template blank` Caso você receba esse prompt perguntando o nome do seu app, preferencialmente não utilize nenhum acento ou caractere especial. `? What is your app named? calendars-example` Após ter instalado todas as dependências necessárias, vamos instalar a biblioteca **react-native-calendars**: Primeiro, através do terminal, navegue até a pasta onde está seu projeto, e depois digite o comando abaixo: `$ npm install --save react-native-calendars` Com isso já podemos recriar o [design do dribble](https://dribbble.com/shots/17884784-Doctor-Appointment-Medical-Mobile-App-UI). Para estilizar vou estar utilizando o próprio **[StyleSheet](https://reactnative.dev/docs/stylesheet)** do React Native, mas você pode utilizar o que estiver mais acostumado, seja **styled-components** ou **native-wind**. Abra o projeto no seu editor de código favorito, eu vou estar utilizando o [VSCode](https://code.visualstudio.com/). Vou começar removendo todo o código existente no arquivo **App.js** e adicionando apenas um titulo para nosso calendário: ![tela do vscode com código react-native](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/1worxsw8cdz3ct9e6mp9.png) Agora vamos rodar o projeto e ver como está ficando, para rodar basta digitar no terminal o comando abaixo (não esquece q tem que estar na pasta do projeto 😁): `$ npx expo start` Você vai se deparar com um QRCode que irá aparecer no seu terminal, basta escanear ele com o seu celular, mas antes, para rodar o aplicativo você vai precisar instalar o app [Expo Go](https://expo.dev/go) no seu celular, que é um aplicativo do Expo para rodar seus projetos criados com o Framework. Após ter escaneado, e o app ter rodado, você deve estar vendo uma tela parecida com essa abaixo: ![celular iphone mostrando um app no expo go](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/md7trotfgp2babvtplxs.png) Vamos continuar, agora criando a parte mais legal que é o calendário em si: - Primeiro, vamos adicionar o componente de **Calendário** da biblioteca, e fazer pequenas estilizações ```javascript import { StyleSheet, Text, SafeAreaView, View } from 'react-native'; import { Calendar, CalendarUtils } from 'react-native-calendars'; const INITIAL_DATE = CalendarUtils.getCalendarDateString(new Date()); export default function App() {   return (     <>       // ✂️ Código comentado apenas para melhor visualização       <SafeAreaView style={styles.container}>         // ✂️ Código comentado apenas para melhor visualização         <View style={styles.wrapper}>           <Calendar             current={INITIAL_DATE}             style={styles.calendar}           />         </View>       </SafeAreaView>     </>   ); } const styles = StyleSheet.create({ // ✂️ Código comentado apenas para melhor visualização   wrapper: {     paddingHorizontal: 24   },   calendar: {     borderRadius: 24,     overflow: 'hidden',   } }); ``` Caso você esteja se perguntando o que essa linha faz: ```javascript const INITIAL_DATE = CalendarUtils.getCalendarDateString(new Date()); ``` Basicamente eu estou utilizando uma função auxiliar da própria biblioteca que transforma uma data no formato 'YYYY-MM-DD', que é o formato que o componente espera. - Agora vamos terminar de estilizar nosso Calendário, mudando as cores default do tema e adicionando arrows customizadas para ficar mais parecido com o design: ```javascript import { StyleSheet, Text, SafeAreaView, View } from 'react-native'; import { Calendar, CalendarUtils } from 'react-native-calendars'; import { Feather } from '@expo/vector-icons'; const INITIAL_DATE = CalendarUtils.getCalendarDateString(new Date()); export default function App() {   return (     <>       // ✂️ Código comentado apenas para melhor visualização       <SafeAreaView style={styles.container}>         // ✂️ Código comentado apenas para melhor visualização         <View style={styles.wrapper}>           <Calendar             current={INITIAL_DATE}             style={styles.calendar}             theme={{               todayTextColor: '#6567ef',               textMonthFontWeight: 'bold',               textDayHeaderFontWeight: 'bold',               textMonthFontSize: 18,               textDayFontWeight: 'bold',               textDayFontSize: 14,               selectedDayBackgroundColor: '#6567ef',               selectedDayTextColor: '#ffffff',             }}             renderArrow={direction => {               return (                 <View style={styles.calendarButton}>                   <Feather name={`chevron-${direction}`} size={24} color="#6567ef" />                 </View>               )             }}           />         </View>       </SafeAreaView>     </>   ); } const styles = StyleSheet.create({ // ✂️ Código comentado apenas para melhor visualização   wrapper: {     paddingHorizontal: 24   },   calendar: {     borderRadius: 24,     overflow: 'hidden',   }   calendarButton: {     backgroundColor: '#e9e5fe',     padding: 8,     borderRadius: 100,   } }); ``` - Para finalizar nosso calendário, vamos adicionar um estado para salvar a data selecionada e mostrar ela no componente: ```javascript import { useState } from 'react'; // ✂️ Código comentado apenas para melhor visualização export default function App() { const [selected, setSelected] = useState(INITIAL_DATE); function onDayPress(day) {     setSelected(day.dateString);   }   const marked = {     [selected]: {       selected: true,     }   };   return (     <>       // ✂️ Código comentado apenas para melhor visualização       <SafeAreaView style={styles.container}>         // ✂️ Código comentado apenas para melhor visualização         <View style={styles.wrapper}>           <Calendar             // ✂️ Código comentado apenas para melhor visualização             onDayPress={onDayPress}             markedDates={marked}           />         </View>       </SafeAreaView>     </>   ); } // ✂️ Código comentado apenas para melhor visualização ``` Pronto! seu calendário deve estar parecido com esse: ![celular iphone mostrando um app no expo go com um calendário](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/dbhvadgvlnsif0w715n7.png) Agora vamos colocar a parte de "Available Time" e um botão para confirmar o agendamento, o código completo dessa UI você pode ver abaixo: ```javascript import { useState } from 'react'; import { StatusBar } from 'expo-status-bar'; import { StyleSheet, Text, SafeAreaView, View, Pressable, ScrollView } from 'react-native'; import { Calendar, CalendarUtils } from 'react-native-calendars'; import { Feather } from '@expo/vector-icons'; const INITIAL_DATE = CalendarUtils.getCalendarDateString(new Date()); const AVAILABLE_TIMES = [   { id: 1, hour: '07:00 PM', status: 'available' },   { id: 2, hour: '07:15 PM', status: 'unavailable' },   { id: 3, hour: '07:30 PM', status: 'available' },   { id: 4, hour: '08:30 PM', status: 'unavailable' },   { id: 5, hour: '08:45 PM', status: 'available' },   { id: 6, hour: '09:00 PM', status: 'available' }, ] export default function App() {   const [selected, setSelected] = useState(INITIAL_DATE);   const [timeSelected, setTimeSelected] = useState(null);   function onDayPress(day) {     setSelected(day.dateString);   }   const marked = {     [selected]: {       selected: true,     }   };   return (     <>       <StatusBar style="auto" />       <SafeAreaView style={styles.container}>         <ScrollView>           <Text style={styles.title}>Appointment Booking</Text>                 <View style={styles.wrapper}>             <Calendar               theme={{                 todayTextColor: '#6567ef',                 textMonthFontWeight: 'bold',                 textDayHeaderFontWeight: 'bold',                 textMonthFontSize: 18,                 textDayFontWeight: 'bold',                 textDayFontSize: 14,                 selectedDayBackgroundColor: '#6567ef',                 selectedDayTextColor: '#ffffff',               }}               enableSwipeMonths               current={INITIAL_DATE}               minDate={INITIAL_DATE}               style={styles.calendar}               onDayPress={onDayPress}               markedDates={marked}               renderArrow={direction => {                 return (                   <View style={styles.calendarButton}>                     <Feather name={`chevron-${direction}`} size={24} color="#6567ef" />                   </View>                 )               }}             />             <Text style={styles.sectionTitle}>Available Time</Text>                         <View style={styles.availableTimeList}>               {AVAILABLE_TIMES.map(({ id, hour, status }) => {                 const isTimeEnabled = status === 'available'                 const isTimeSelected = timeSelected === hour                 const defaultBg = isTimeEnabled ? '#e9e5fe' : '#ebe9f6'                 const defaultColor = isTimeEnabled ? '#222222' : '#aeaeb0'                 return (                   <Pressable                     key={id}                     style={[                       styles.availableTimeButton,                       { backgroundColor: isTimeSelected ? '#6567ef' : defaultBg }                     ]}                     onPress={() => setTimeSelected(hour)}                     disabled={!isTimeEnabled}                   >                     <Text                       style={[                         styles.availableTimeButtonText,                         { color: isTimeSelected ? '#ffffff' : defaultColor }                       ]}>                       {hour}                     </Text>                   </Pressable>                 )               })}             </View>             <Pressable style={styles.ConfirmScheduleButton}>               <Text style={styles.ConfirmScheduleButtonText}>Confirm Schedule</Text>             </Pressable>           </View>         </ScrollView>       </SafeAreaView>     </>   ); } const styles = StyleSheet.create({   container: {     flex: 1,     backgroundColor: '#f5f6fa',   },   title: {     marginHorizontal: 'auto',     fontWeight: 'bold',     marginVertical: 24,     fontSize: 18,   },   wrapper: {     paddingHorizontal: 24   },   calendar: {     borderRadius: 24,     overflow: 'hidden',   },   calendarButton: {     backgroundColor: '#e9e5fe',     padding: 8,     borderRadius: 100,   },   sectionTitle: {     fontWeight: 'bold',     marginVertical: 24,     fontSize: 16,   },   availableTimeList: {     flexDirection: 'row',     flexWrap: 'wrap',     gap: 12,     marginBottom: 64,   },   availableTimeButton: {     width: '30%',     marginBottom: 6,     paddingVertical: 16,     borderRadius: 999,     alignSelf: 'flex-start',     alignItems: 'center'   },   availableTimeButtonText: {     fontWeight: 'bold',     fontSize: 12   },   ConfirmScheduleButton: {     backgroundColor: '#6567ef',     padding: 22,     borderRadius: 999,     alignItems: 'center'   },   ConfirmScheduleButtonText: {     fontSize: 16,     fontWeight: 'bold',     color: '#ffffff'   } }); ``` Sua tela final deve estar parecida com essa abaixo: ![celular iphone mostrando um app no expo go com um calendário](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/vcutme5k2zzxzr8oj60n.png) Espero que tenha gostado, você pode [acessar aqui](https://github.com/MarcosWillianR/calendars-example) o repositório com o código final caso esteja tendo dificuldades. Sinta-se à vontade para sugerir uma biblioteca especifica para mim construir algo utilizando o Dribble. Obrigado!
marcoswillianr
1,875,885
HOW TO RECOVER CRYPTO SENT TO SCAMMERS // DIGITAL WEB RECOVERY
With a heavy heart and a cautionary tale to share, I recount my harrowing experience of falling...
0
2024-06-03T20:44:02
https://dev.to/sidorela_bogdani_f62ec70c/how-to-recover-crypto-sent-to-scammers-digital-web-recovery-462a
With a heavy heart and a cautionary tale to share, I recount my harrowing experience of falling victim to a cryptocurrency investment hoax that drained me of a staggering sum totaling $157,300. Ensnared by the deceptive promises of soaring asset values, I found myself entangled in a web of deceit spun by cunning scammers who preyed on my trust and financial vulnerability. Their nefarious tactics included imposing exorbitant fees for withdrawals, demanding payment for taxes, verification costs, and other spurious charges before releasing my hard-earned funds, leaving me feeling utterly betrayed and helpless in the face of such treachery. In the depths of despair, with my dreams shattered and my hopes dashed, I sought solace and assistance from the esteemed professionals at Digital Web Recovery. With a heavy heart and a glimmer of hope, I entrusted them with the arduous task of navigating the complex landscape of cryptocurrency recovery, placing my faith in their expertise and dedication to righting the wrongs inflicted upon me. From the moment I engaged their services, I was met with a reassuring sense of professionalism, unwavering commitment, and a genuine desire to help me reclaim what was rightfully mine. The team at Digital Web Recovery exhibited unparalleled skill, diligence, and empathy throughout the intricate process of recovering my lost funds. With meticulous attention to detail and a steadfast resolve to see justice served, they embarked on the journey of unraveling the web of deception that had ensnared me. Despite the challenges and complexities of my case, they maintained open lines of communication, providing regular updates and guidance with transparency and integrity that instilled in me a renewed sense of hope and trust. To my immense relief and gratitude, Digital Web Recovery successfully orchestrated the recovery of all my lost funds in a remarkably swift manner. Their swift and effective actions not only restored my financial security but also reignited my faith in the possibility of justice prevailing against fraudulent schemes. The team's expertise and unwavering dedication shone brightly as they navigated the intricate process of recovering my assets, delivering results that far exceeded my expectations. I endorse Digital Web Recovery to anyone who has fallen victim to cryptocurrency scams or investment hoaxes. Their exceptional skills, unwavering commitment, and genuine compassion for those who have been wronged make them a trusted ally in the fight against digital deception. Trusting in Digital Web Recovery was a decision that transformed my recovery journey, and I am forever grateful for their steadfast support and expertise. If you find yourself in the clutches of nefarious cryptocurrency con artists, do not despair – for Digital Web Recovery stands ready to assist you in reclaiming what is rightfully yours. Website https://digitalwebrecovery.com Email; digitalwebexperts@zohomail.com WhatsApp +14033060588 Their dedication to seeking justice and unwavering support for victims of financial fraud makes them recover their assets. Digital Web Recovery they are a guide for you toward reclaiming your lost assets with skill and compassion. Trust in their expertise and let them lead you on the path to recovery of digital assets. ![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/gcguy2vheyzlx1bsv2tj.jpeg)
sidorela_bogdani_f62ec70c
1,875,884
I'm learning something new!
I've been learning React Native from a tutorial. It's a great tutorial - just slightly fast-paced and...
0
2024-06-03T20:40:50
https://dev.to/cmcrawford2/im-learning-something-new-3kd5
reactnative, ios, fullstack
I've been learning React Native from a tutorial. It's a great tutorial - just slightly fast-paced and a little bit "spoon fed". However I'm getting a feel for what React Native is like. I already know React and have written a bunch of applications in it, so React Native is easy enough. Views and Text instead of divs and h1, p, etc. Also we're using nativewind, which is written on top of tailwind. This is the third time for me using tailwind. I learned frontend first, so I normally code my own CSS. Another benefit is that I didn't have to load xcode onto my laptop. I'm using expo, which is a godsend. My only complaint is that I'm new at this, so every step of the way I introduce a bug. Sometimes it goes unnoticed, like putting a comma in a list of classNames. With React, or JSX, this will work sometimes and not work other times, so when it stops working it's a mystery. Then I compare my code with the instructor's code or ask ChatGPT. Right now I'm stuck playing a video (using expo-av). I'm going to just go on and see if I can play the stored videos that appear in a second FlatList. ChatGPT hasn't actually helped much. It keeps telling me to install the expo cli, to make sure I've installed this or that package, etc., which I have. It did catch one bug where I wrapped the callback function in curly braces when it required parentheses. Nothing worked at all until ChatGPT told me of course it wouldn't do anything until I fixed the error. I was grateful. Here's the link to the video: [React Native Tutorial](https://www.youtube.com/watch?v=ZBCUegTZF7M)
cmcrawford2
1,872,372
Smart contracts privados con Solidity y Circom
ZK nos permite hacer aplicaciones con datos y ejecución privada. Esto abre la puerta a muchos nuevos...
0
2024-06-03T20:35:32
https://dev.to/turupawn/smart-contracts-privados-con-solidity-y-circom-3a8h
--- title: Smart contracts privados con Solidity y Circom published: true description: tags: # cover_image: https://direct_url_to_image.jpg # Use a ratio of 100:42 for best results. # published_at: 2024-05-29 00:02 +0000 --- ZK nos permite hacer aplicaciones con datos y ejecución privada. Esto abre la puerta a muchos nuevos casos de uso, como el que crearemos en esta guía: un sistema de votación anónimo y seguro combinando Circom y Solidity. ## Circom y dependencias Si aún no tienes circom, instálalo con los comandos a continuación. Yo estoy usando node v20 pero debería funcionar con otras versiones. ```bash curl --proto '=https' --tlsv1.2 https://sh.rustup.rs -sSf | sh git clone https://github.com/iden3/circom.git cd circom cargo build --release cargo install --path circom npm install -g snarkjs ``` También vamos a ocupar las librerías de circom donde se encuentra la función de poseidon que vamos a estar usando. ```bash git clone https://github.com/iden3/circomlib.git ``` ## 1. Creación de llaves públicas El método que usaremos para realizar votos anónimos y seguros es comprobando que somos parte de un grupo sin revelar nuestra identidad. Por ejemplo, voy a votar por el presidente de Honduras, demostrando que soy un hondureño pero sin revelar cuál hondureño soy. A esto le llamamos _"prueba de inclusión en un set"_. La manera más práctica de realizar esto en zk y blockchain es por medio de árboles merkle. Vamos a colocar a los votantes como hojas del árbol y vamos a demostrar que somos una de ellas sin revelar cuál. El árbol es público así que usaremos un set de llaves pública-privadas para que cada votante pueda ejecutar su voto una sola vez. Quizás te preguntarás si podemos usar las llaves públicas de nuestra wallet de ethereum (e.g. de metamask). En guías futuras como esta estaré tocando ese tema tal y como [lo hice con noir](https://github.com/Turupawn/EcrecoverInclusionProof). Para llegar a ese punto necesitarás los fundamentos de esta guía. Así que pendientes y suscríbanse! Creemos ahora las llaves públicas para las siguientes llaves privadas a través del circuito `privateKeyHasher.circom` a continuación: * `111` * `222` * `333` * `444` `privateKeyHasher.circom` ```javascript pragma circom 2.0.0; include "circomlib/circuits/poseidon.circom"; template privateKeyHasher() { signal input privateKey; signal output publicKey; component poseidonComponent; poseidonComponent = Poseidon(1); poseidonComponent.inputs[0] <== privateKey; publicKey <== poseidonComponent.out; log(publicKey); } component main = privateKeyHasher(); ``` `input.json` ```json { "privateKey": "111" } ``` Compilamos y computamos el circuito con los comandos a continuación, podrás ver el resultado en la terminal. ```bash circom privateKeyHasher.circom --r1cs --wasm --sym --c node privateKeyHasher_js/generate_witness.js privateKeyHasher_js/privateKeyHasher.wasm input.json witness.wtns ``` El resultado de las 4 llaves privadas debería ser el siguiente: | Llave privada | Llave pública | | -------- | ------- | | 111 | 13377623690824916797327209540443066247715962236839283896963055328700043345550 | | 222 | 3370092681714607727019534888747304108045661953819543369463810453568040251648 | | 333 | 19430878135540641438890585969007029177622584902384053006985767702837167003933 | | 444 | 2288143249026782941992289125994734798520452235369536663078162770881373549221 | ¿Es necesario hacer esto a través de circom? La respuesta es no. Al hacerlo en circom estamos haciendo mucha computación innecesaria, por ahora lo haremos de esta manera para asegurar que la implementación del algoritmo de hasheo poseidon que usaremos más adelate sea compatible. Esto no es recomendado para proyectos en producción. ## 2. Creación del árbol Ahora tenemos las cuatro hojas de nuestro árbol posicionadas de la siguiente manera ``` └─ ??? ├─ ??? │ ├─ 13377623690824916797327209540443066247715962236839283896963055328700043345550 │ └─ 3370092681714607727019534888747304108045661953819543369463810453568040251648 └─ ??? ├─ 19430878135540641438890585969007029177622584902384053006985767702837167003933 └─ 2288143249026782941992289125994734798520452235369536663078162770881373549221 ``` A continuación vamos a generar el árbol merkle rama por rama. Recordemos que los árbol merkle se generan hasheando cada una de sus hojas y ramas en pares hasta llegar a la raíz. Para generar el árbol completo ejecutaremos la siguiente funcion que hashea dos hojas para generar su raíz. Lo haremos un total de 3 veces pues son las necesarias para obtener la raíz de un árbol con 4 hojas: `raíz = hash(hash(A, B), hash(C, D))`. `hashLeaves.circom` ```javascript pragma circom 2.0.0; include "circomlib/circuits/poseidon.circom"; template hashLeaves() { signal input leftLeaf; signal input rightLeaf; signal output root; component poseidonComponent; poseidonComponent = Poseidon(2); poseidonComponent.inputs[0] <== leftLeaf; poseidonComponent.inputs[1] <== rightLeaf; root <== poseidonComponent.out; log(root); } component main = hashLeaves(); ``` Estos son los inputs necesarios para generar la primera rama. De una manera similar puedes generar la otra rama y la raíz. `input.json` ```json { "leftLeaf": "13377623690824916797327209540443066247715962236839283896963055328700043345550", "rightLeaf": "3370092681714607727019534888747304108045661953819543369463810453568040251648" } ``` Similar al paso anterior, con los siguientes comandos se compilará el circuito y se imprimirá el la raíz dada sus dos hojas. ```bash circom hashLeaves.circom --r1cs --wasm --sym --c node hashLeaves_js/generate_witness.js hashLeaves_js/hashLeaves.wasm input.json witness.wtns ``` Así se mira nuestro árbol completo: ``` └─ 172702405816516791996779728912308790882282610188111072512380034048458433129 ├─ 8238706810845716733547504554580992539732197518335350130391048624023669338026 │ ├─ 13377623690824916797327209540443066247715962236839283896963055328700043345550 │ └─ 3370092681714607727019534888747304108045661953819543369463810453568040251648 └─ 11117482755699627218224304590393929490559713427701237904426421590969988571596 ├─ 19430878135540641438890585969007029177622584902384053006985767702837167003933 └─ 2288143249026782941992289125994734798520452235369536663078162770881373549221 ``` ## 3. Generar la prueba de un voto anónimo Para generar un voto ocupamos pasar los siguientes parámetros al circuito: * `privateKey`: La llave privada del usuario. * `root`: La raíz del arbol nos asegura que estamos operando en el conjunto correcto. Adicionalmente, para más claridad, podríamos agregar el contrato y la chain en la que se ejecutará el voto. Esta variable será pública, accesible al smart contract. * `proposalId` y `vote`: El voto elegido por el usuario. * `pathElements` y `pathIndicies`: La información mínima necesaria para reconstruir la raíz, esto incluye los `pathElements`, o sea los nodos hoja o rama, y los `pathIndices`, que nos muestran cuál camino tomar para hashear donde 0 simboliza los nodos de la izquierda y 1 los de la derecha. `proveVote.circom` ```javascript pragma circom 2.0.0; include "circomlib/circuits/poseidon.circom"; template switchPosition() { signal input in[2]; signal input s; signal output out[2]; s * (1 - s) === 0; out[0] <== (in[1] - in[0])*s + in[0]; out[1] <== (in[0] - in[1])*s + in[1]; } template privateKeyHasher() { signal input privateKey; signal output publicKey; component poseidonComponent; poseidonComponent = Poseidon(1); poseidonComponent.inputs[0] <== privateKey; publicKey <== poseidonComponent.out; } template nullifierHasher() { signal input root; signal input privateKey; signal input proposalId; signal output nullifier; component poseidonComponent; poseidonComponent = Poseidon(3); poseidonComponent.inputs[0] <== root; poseidonComponent.inputs[1] <== privateKey; poseidonComponent.inputs[2] <== proposalId; nullifier <== poseidonComponent.out; } template proveVote(levels) { signal input privateKey; signal input root; signal input proposalId; signal input vote; signal input pathElements[levels]; signal input pathIndices[levels]; signal output nullifier; signal leaf; component hasherComponent; hasherComponent = privateKeyHasher(); hasherComponent.privateKey <== privateKey; leaf <== hasherComponent.publicKey; component selectors[levels]; component hashers[levels]; signal computedPath[levels]; for (var i = 0; i < levels; i++) { selectors[i] = switchPosition(); selectors[i].in[0] <== i == 0 ? leaf : computedPath[i - 1]; selectors[i].in[1] <== pathElements[i]; selectors[i].s <== pathIndices[i]; hashers[i] = Poseidon(2); hashers[i].inputs[0] <== selectors[i].out[0]; hashers[i].inputs[1] <== selectors[i].out[1]; computedPath[i] <== hashers[i].out; } root === computedPath[levels - 1]; component nullifierComponent; nullifierComponent = nullifierHasher(); nullifierComponent.root <== root; nullifierComponent.privateKey <== privateKey; nullifierComponent.proposalId <== proposalId; nullifier <== nullifierComponent.nullifier; } component main {public [root, proposalId, vote]} = proveVote(2); ``` `input.json` ```json { "privateKey": "111", "root": "172702405816516791996779728912308790882282610188111072512380034048458433129", "proposalId": "0", "vote": "1", "pathElements": ["3370092681714607727019534888747304108045661953819543369463810453568040251648", "11117482755699627218224304590393929490559713427701237904426421590969988571596"], "pathIndices": ["0","0"] } ``` Probamos si todo funciona bien: ```bash circom proveVote.circom --r1cs --wasm --sym --c node proveVote_js/generate_witness.js proveVote_js/proveVote.wasm input.json witness.wtns ``` Si no hubo ningún problema, no se debería imprimir nada en la terminal. ## 4. Verificar un voto on-chain, desde Solidity Con los siguientes comandos llevamos a cabo la ceremonia inicial también conocida como la _trusted setup_. ``` snarkjs powersoftau new bn128 12 pot12_0000.ptau -v snarkjs powersoftau contribute pot12_0000.ptau pot12_0001.ptau --name="First contribution" -v snarkjs powersoftau prepare phase2 pot12_0001.ptau pot12_final.ptau -v snarkjs groth16 setup proveVote.r1cs pot12_final.ptau proveVote_0000.zkey snarkjs zkey contribute proveVote_0000.zkey proveVote_0001.zkey --name="1st Contributor Name" -v snarkjs zkey export verificationkey proveVote_0001.zkey verification_key.json ``` A continuación generamos el contrato verificador en solidity. ```bash snarkjs zkey export solidityverifier proveVote_0001.zkey verifier.sol ``` Al ejectuar este comando se generará un contrato verificador en el archivo `verifier.sol`. Lánza ahora ese contrato on-chain. A continuación lanza el siguiente contrato on chain que contiene la lógica de la votación y verificación de pruebas. Pásale el address del contrato verificador que recién lanzamos como parámetro en el constructor. ```javascript // SPDX-License-Identifier: MIT pragma solidity >=0.7.0 <0.9.0; interface ICircomVerifier { function verifyProof(uint[2] calldata _pA, uint[2][2] calldata _pB, uint[2] calldata _pC, uint[4] calldata _pubSignals) external view returns (bool); } contract CircomVoter { ICircomVerifier circomVerifier; uint public publicInput; struct Proposal { string description; uint deadline; uint forVotes; uint againstVotes; } uint merkleRoot; uint proposalCount; mapping (uint proposalId => Proposal) public proposals; mapping (uint nullifier => bool isNullified) public nullifiers; constructor(uint _merkleRoot, address circomVeriferAddress) { merkleRoot = _merkleRoot; circomVerifier = ICircomVerifier(circomVeriferAddress); } function propose(string memory description, uint deadline) public { proposals[proposalCount] = Proposal(description, deadline, 0, 0); proposalCount += 1; } function castVote(uint[2] calldata _pA, uint[2][2] calldata _pB, uint[2] calldata _pC, uint[4] calldata _pubSignals) public { circomVerifier.verifyProof(_pA, _pB, _pC, _pubSignals); uint nullifier = _pubSignals[0]; uint merkleRootPublicInput = _pubSignals[1]; uint proposalId = uint(_pubSignals[2]); uint vote = uint(_pubSignals[3]); require(block.timestamp < proposals[proposalId].deadline, "Voting period is over"); require(merkleRoot == merkleRootPublicInput, "Invalid merke root"); require(!nullifiers[nullifier], "Vote already casted"); nullifiers[nullifier] = true; if(vote == 1) proposals[proposalId].forVotes += 1; else if (vote == 2) proposals[proposalId].againstVotes += 1; } } ``` Ahora crea la primera propuesta para votación llamando la función `propose()`. Por ejemplo puedes probar haciendo una votación con `¿Comemos pizza?` como descripción y con `1811799232` como deadline para que venza en 2027. Ahora generamos una prueba en el formato necesario para verificarla en Remix. ```bash snarkjs groth16 prove proveVote_0001.zkey witness.wtns proof.json public.json snarkjs groth16 verify verification_key.json public.json proof.json snarkjs generatecall ``` Pasemos el resultado de la terminal como parámetro en remix y veremos cómo el voto fue ejecutado al obtener la data de la proposal 0 a través del mapping `proposals`. ![Votos anónimos con Circom y Solidity](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/vxtljhmmkyv2zh30i7tz.png) Observamos que nuestro voto fué contado sin revelar quién fué el emisor. Intenta emitir el mismo voto de nuevo y verás que no será posible, la transacción revertirá. Esto porque ya nulificamos el voto para que cada votante solo pueda emitir un solo voto. Fuentes y documentación oficial: * [Documentación oficial de circom](https://docs.circom.io/) * [Ejemplo de merkle inclusion proof](https://github.com/thor314/circuit-examples/blob/main/circom-merkle-proof/verify-merkle-path.circom) * [Votos anónimos en Noir](https://dev.to/turupawn/votos-anonimos-usando-zk-39j) **¡Gracias por leer esta guía!** Sígueme en dev.to y en [Youtube](https://www.youtube.com/channel/UCNRB4tgwp09z4391JRjEsRA) para todo lo relacionado al desarrollo en Blockchain en Español.
turupawn
1,873,628
Managing Architectural Tech Debt
When I think about technical debt, I still remember the first application I created that made me...
0
2024-06-03T20:33:54
https://dev.to/johnjvester/managing-architectural-tech-debt-i82
architecture, webdev, techdebt, shiftleft
![Article Image](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/prqrk8r48n59ub73oy5r.jpg) When I think about technical debt, I still remember the first application I created that made me realize the consequences of an unsuitable architecture. It happened back in the late 1990s, when I was first getting started as a consultant. The client had requested use of the [Lotus Notes](https://en.wikipedia.org/wiki/HCL_Notes) platform to build a procurement system for their customers. Using the Lotus Notes client and a custom application, end-users could make requests that would be tracked by the application and fulfilled by the product owner’s team. In theory, it was a really cool idea – especially since web-developed applications were not prevalent and everyone used Lotus Notes on a daily basis. The core problem is that the data was very relational in design – and Lotus Notes was not a relational database. The solution’s design required schema management within every Lotus Notes document and leaned on a series of multi-value fields to simulate the relationships between data attributes. It was a mess. A great deal of logic in the Lotus Notes application would not have been required if a better platform was recommended. The source code was complicated to support. Enhancements to the data structure resulted in major refactoring of the underlying code – not to mention running server-based jobs to convert the existing data. Don’t get me started on the effort behind report creation. Since I was early in my career I was focused on providing a solution that the client wanted over trying to offer a better solution. This was certainly a lesson I learned early in my career, but in the years since that project I’ve come to realize that the consequence of architectural technical debt is an unfortunate reality we all face. Let’s explore the concept of architecture tech debt a little more at a macro level. ## **Architectural Tech Debt (ATD)** The Architectural Technical Debt (ATD) Library at Carnegie Mellon University provides the following [definition](https://insights.sei.cmu.edu/library/architectural-technical-debt-library/#:~:text=Architectural%20technical%20debt%20is%20a,including%20increased%20cost%20over%20time).) of ATD: > **Architectural technical debt is a design or construction approach that's expedient in the short term, but that creates a technical context in which the same work requires architectural rework and costs more to do later than it would cost to do now (including increased cost over time).** In the “Quick Answer: How to Manage Architecture Technical Debt” (published 09/22/2023), Gartner Group defines ATD as follows: > **Architecture technical debt is that type of technical debt that is caused by architectural drift, suboptimal architectural decisions, violations of defined target product architecture and established industry architectural best practices, and architecture trade-offs made for faster software delivery.** In both cases, benefits that often yield short-term celebrations can be met with long-term challenges. This is similar to my Lotus Notes example mentioned in the introduction. To further complicate matters, tooling to help identify and manage tech debt for software architecture have been missing in comparison to the other aspects of software development: ![Image #1](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/v4is24dcu7tqtmk7yk4g.png) For code quality, observability and SCA, proven tooling exists with products like Sonarqube, Datadog, New Relic, GitHub and Snyk. However, the software architecture segment has lagged behind without any proven solutions. This is unfortunate, given the fact that ATD is consistently the largest – and most damaging – type of technical debt as found in the “[Measure It? Manage It? Ignore It? Software Practitioners and Technical Debt](https://insights.sei.cmu.edu/library/measure-it-manage-it-ignore-it-software-practitioners-and-technical-debt/)” 2015 study published by Carnegie Mellon.   The following illustration summarizes Figure 4 from that report, concluding that bad architecture choices were the clear leader in sources of technical debt. ![Image #2](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/4bail8lco767mys8b6dj.png) If not managed, ATD can continue to grow over time at an increasing rate as demonstrated in this simple illustration: ![Image #3](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/8xo4408zthnwgdusudgy.png) Without mitigation, architecture debt will eventually reach a breaking point for the underlying solution being measured. ### Managing ATD Before we can manage ATD, we must first understand the problem. [Desmond Tutu](https://en.wikipedia.org/wiki/Desmond_Tutu) once wisely said that “there is only one way to eat an elephant: a bite at a time.” The shift-left approach embraces the concept of moving a given aspect closer to the beginning than at the end of a lifecycle. This concept gained popularity with shift-left for testing, where the test phase was moved to part of the development process and not a separate event to be completed after development was finished. Shift-left can be implemented two different ways in managing ATD: * Shift-left for resiliency — identifying sources which have an impact on resiliency, and then fixing them before they manifest in performance. * Shift-left for security — detect and mitigate security issues during the development lifecycle. Just like shift-left for testing, a prioritized focus on resilience and security during the development phase will reduce the potential for unexpected incidents. ### Architectural observability Architectural observability gives engineering teams the ability to incrementally address architectural drift within their services at a macro level. In fact, the Wall Street Journal reported the cost to fix technical debt at $1.52 trillion earlier this year in “The Invisible $1.52 Trillion Problem: Clunky Old Software,” [article](https://www.wsj.com/tech/personal-tech/the-invisible-1-52-trillion-problem-clunky-old-software-f5cbba27). To be successful, engineering leadership must be in full alignment with the following organizational objectives: * Resiliency — to recover swiftly from unexpected incidents. * Scalability — to scale appropriately with customer demand. * Velocity — to deliver features and enhancements inline with product expectations. * Cloud Suitability — transforming legacy solutions into efficient cloud-native service offerings. I recently discovered [vFunction](https://vfunction.com/)’s AI-driven architectural observability platform, which is focused on the following deliverables: * **Discover** the real architecture of solutions via static and dynamic analysis. * **Prevent** architecture drift via real-time views of how services are evolving. * Increase **resiliency** of applications via the elimination of unnecessary dependencies and improvements between application domains and their associated resources. * Manage and **remediate** tech debt via AI-driven observability. Additionally, the vFunction platform provides the side-benefit of providing a migration path to transform from monoliths to cloud-native solutions. Once teams have modernized their platforms, they can continuously observe them for ongoing drift. If companies already have microservices, they can use vFunction to detect complexity in distributed applications and address dependencies that impact resiliency and scalability. In either case, once implemented, engineering teams can mitigate ATD well before reaching the breaking point. ![Image #4](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/2d5kmjb4tbcvo95ayg5n.png) In the illustration above, engineering teams are able to mitigate technical debt as a part of each release, due to implementation of the vFunction platform and an underlying shift-left approach. ## **Conclusion** My readers may recall that I have been focused on the following mission statement, which I feel can apply to any IT professional: > **“Focus your time on delivering features/functionality that extends the value of your intellectual property. Leverage frameworks, products, and services for everything else.”** > > **\- J. Vester** The vFunction platform adheres to my mission statement by helping engineering teams employ a shift-left approach to the resiliency and security of their services at a macro level. This is an important distinction, because without such tooling teams are likely to mitigate at a micro level resolving tech debt that doesn’t really matter from an organization perspective. When I think back to that application that made me realize the challenges with tech debt, I can’t help but think about how that solution yielded more issues than it did benefits with each feature that was introduced. Certainly, the use of shift-left for resiliency alone would have helped surface issues with the underlying architecture at a point where the cost to consider alternatives would be feasible.  If you are interested in learning more about the vFunction solution, you can read more about them [here](https://vfunction.com/platform/). Have a really great day!
johnjvester
1,875,853
Simple "Infinite" Grid Shader
I tried to follow a "recipe" for an infinite grid shader, but after hitting a bug and not being able...
0
2024-06-03T20:25:12
https://dev.to/javiersalcedopuyo/simple-infinite-grid-shader-5fah
graphics, tutorial, shader, metal
I tried to follow a "recipe" for an infinite grid shader, but after hitting a bug and not being able to fix it because I didn't understand the code, I decided to write it from scratch myself so I could understand it properly. In the process I found better implementations than the original one I was following, and better than my own. In the end I came up with a different, simpler approach, although more limited in some aspects, that ticks all my boxes at the moment. You can see the code [here](https://gitlab.com/ludusestars/Talos3D/-/commit/f15d291f764021ec4759a17dd601ad4448430ab1). Here's a detailed step-by-step explanation of how it works. > ⚠️ DISCLAMER 1: > The goal of this article is just to document and organise my thought process while I was trying to understand the code behind another implementation. > If you want something robust / production-worthy, you should read [this](https://bgolus.medium.com/the-best-darn-grid-shader-yet-727f9278b9d8) instead. ![this one is mine](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/4vrcn2unvu187g9ufhsh.png) > ⚠️ DISCLAIMER 2: > I'm using MSL (Metal Shading Language) because I like it and because my toy renderer uses Metal as the graphics API anyway, but it should be pretty straightforward to translate it to GLSL or HLSL. > ⚠️ DISCLAIMER 3: > This article will only focus on the shader part, but the setup in the host (CPU) side should be very simple regardless of API: > - Set everything up to render a quad (2 triangles) > - Enable depth testing > - Disable face culling (we want to be able to see it from bellow too) > - Because it's transparent it should be rendered _after_ the opaque objects --- ## 1. Finite version ### 1.1 Vertex Shader ```C++ static constant auto grid_size = 1.0f; static constant float4 positions[4]{     { -0.5, 0.0,  0.5, 1.0 },     {  0.5, 0.0,  0.5, 1.0 },     { -0.5, 0.0, -0.5, 1.0 },     {  0.5, 0.0, -0.5, 1.0 } }; struct VertexOut {     float4 position [[ position ]] [[ invariant ]];     float2 coords; }; vertex VertexOut main( uint id [[vertex_id]], float4x4 view_proj [[buffer(N)]]) { auto world_pos = positions[id]; world_pos.xyz *= grid_size; return{ .position = view_proj * world_pos, .coords = world_pos.xz }; } ``` This will create a quad of size 1x1 centred at the origin. If we output the normalised coordinates in the fragment shader... ```C++ using FragmentIn = VertexOut; fragment float4 main(FragmentIn frag [[stage_in]]) {     auto c = float4(frag.coords/grid_size + 0.5, 0.0, 1.0);     return c; } ``` ...you'll get something like this: ![quad UVs](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/aedju9jejmspyhrfpbzq.png) ### 1.2 Fragment Shader #### 1.2.0 Modulo > ⚠️ IMPORTANT in case you're using MSL or HLSL [GLSL](https://registry.khronos.org/OpenGL-Refpages/gl4/html/mod.xhtml) defines its modulo function as `x - y * floor(x/y)` which produces this type of repeating pattern: ![GLSL's mod](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/4ct3hsicim821iwvydad.png) However, both [MSL](https://developer.apple.com/metal/Metal-Shading-Language-Specification.pdf) and [HLSL](https://learn.microsoft.com/en-us/windows/win32/direct3dhlsl/dx-graphics-hlsl-fmod) define it as `x - y * trunc(x/y)`, which produces this: ![fmod](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/tppjmz0q6zpac028ttdl.png) Since I'm using MSL, I'll add a template function that mimics GLSL's `mod`: ```C++ template<typename T, typename U> constexpr T mod(T x, U y) { return x - y * floor( x / y ); } ``` For HLSL you'll have to rely on macros: ```C #define mod(x,y) ((x) - (y) * floor((x)/(y))) ``` > EDIT: From HLSL 2021 you can also use templates. #### 1.2.1 Draw the cells We'll subdivide the grid into 2 types of cells: - Big 1x1m cells - Small 0.1x0.1 (sub)cells To make it clearer to see, I'm increasing the plane size to 2x2m ```C++ static constant auto grid_size = 2.0f; static constant auto cell_size = 1.0f; static constant auto half_cell_size = cell_size * 0.5f; static constant auto subcell_size = 0.1f; static constant auto half_subcell_size = subcell_size * 0.5f; ``` We start by calculating the coordinates inside the cells and subcells. 1. First, displace the plane coordinates so the world's origin is in a corner rather than in the middle of the (sub)cell. 2. Then get the coordinates inside the (sub)cell ```C++ auto cell_coords = mod( frag.coords + half_cell_size, cell_size ); auto subcell_coords = mod( frag.coords + half_subcell_size, subcell_size ); ``` If we normalise and output this as a colour, we'll get something like this: | Cell UVs | Subcell UVs | | ------------------------- | -------------------- | | ![Cell UVs](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/by7kljl5g81dl2qinglf.png) | ![Subcell UVs](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/2filpq4k6bibef04gk26.png) | Next we calculate the distances in U and V to the (sub)cell's edge. The coordinates we calculated before are in the [0, (sub)cell_size] range so: 1. First, we transform them into the [-(sub)cell_size/2, (sub)cell_size/2] range so the center of the (sub)cell has the (0,0) coordinates. 2. Then, the distance to the edge is simply the absolute of these new coordinates ```C++ auto distance_to_cell = abs( cell_coords - half_cell_size ); auto distance_to_subcell = abs( subcell_coords - half_subcell_size ); ``` Now it's time to draw the lines. Comparing that distance to the (sub)cell line thickness, we determine if we should draw the line or not: ```C++ static constant auto cell_line_thickness = 0.01f; static constant auto subcell_line_thickness = 0.001f; static constant auto cell_colour = float4( 0.75, 0.75, 0.75, 0.5 ); static constant auto subcell_colour = float4( 0.5, 0.5, 0.5, 0.5 ); ... // In the fragment shader auto color = float4(0); if ( any( distance_to_subcell < subcell_line_thickness * 0.5 ) ) color = subcell_color; if ( any( distance_to_cell < cell_line_thickness * 0.5 ) ) color = cell_color; return color; ``` The line thicknesses are halved because only half the line is within a given (sub)cell, as the other half is in the neighbouring (sub)cell However, this has obvious issues (I made the plane opaque and the lines yellow to make it clearer): ![First Grid](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/lhe798jk5pyr4n22ne94.png) #### 1.2.2 Get uniform lines So the problem here is that, due to perspective, the coordinates can change drastically from one fragment to another, meaning that the exact coordinates that fall within the line might be skipped from one fragment to the next. An easy solution is to increase the line width by how much the coordinates change across fragments. Thankfully, we get a very handy tool to get that change: partial derivatives. If you don't know what they are or how they work, I recommend reading [this article](https://www.aclockworkberry.com/shader-derivative-functions/). ```C++ auto d = fwidth(frag.coords); auto adjusted_cell_line_thickness    = 0.5 * ( cell_line_thickness    + d ); auto adjusted_subcell_line_thickness = 0.5 * ( subcell_line_thickness + d ); auto color = float4(0); if ( any( distance_to_subcell < adjusted_subcell_line_thickness ) ) color = subcell_color; if ( any( distance_to_cell < adjusted_cell_line_thickness ) ) color = cell_color; return color; ``` ![Corrected Grid](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/h9qtev9gs3mflbvmp43k.png) And this is how it looks with dimensions 100x100m and the actual colour: ![Corrected Grid 2](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/9rwc7zalp6bpe4a1k3we.png) ### 1.3 Fade out This already looks pretty good, but you can see issues in the distance: mainly aliasing and [Moiré patterns](https://en.wikipedia.org/wiki/Moir%C3%A9_pattern). There's a lot of literature about how to fix these kind of issues, but I decided to take a different approach... ...just fade out the grid around the camera so you can't see them! ![Lazy Filtering](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/zctd4hc5atzm4ng8jznq.png) First, we need the camera position. Let's make the necessary changes in the vertex shader: ```C++ struct VertexIn { float4x4 view_proj; float4 camera_pos; }; struct VertexOut { float4 position [[ position ]] [[ invariant ]]; float3 camera_pos [[ flat ]]; float2 coords; }; vertex VertexOut main( uint id [[vertex_id]], constant VertexIn& vert_in [[buffer(N)]]) { auto world_pos = positions[id]; world_pos.xyz *= grid_size; return { .position = vert_in.view_proj * world_pos, .camera_pos = vert_in.camera_pos, .coords = world_pos.xz }; } ``` Note the `[[ flat ]]`: this is an attribute that disables interpolation, so we have the same value for all fragments. Of course, in the host you'll need to add the camera position to the buffer too. After that we calculate the horizontal distance to the camera, and use that to interpolate: ```C++ static const auto max_fade_distance = 25.0f; ... // In the fragment shader float opacity_falloff; { auto distance_to_camera = length(frag.coords - frag.camera_pos.xz); opacity_falloff = smoothstep(1.0, 0.0, distance_to_camera / max_fade_distance); } return color * opacity_falloff; ``` I've found that a 25m fade radius works pretty well at a camera height of 1m, but it's too small when the camera is very high, and too big if it's very low. So the fade radius will now be adjusted by height, keeping that 1:25 ratio. ```C++ static constant auto height_to_fade_distance_ratio = 25.0f; ... // In the fragment shader auto fade_distance = abs(frag.camera_pos.y) * height_to_fade_distance_ratio; opacity_falloff = smoothstep(1.0, 0.0, distance_to_camera / fade_distance); ``` However, if the camera gets very close to the plane, that radius will approach zero, so I added a minimum radius. And, if the camera gets very high, you can see the shape of the quad, so I added a maximum. ```C++ static constant auto min_fade_distance = grid_size * 0.05f; static constant auto max_fade_distance = grid_size * 0.5f; ... // In the fragment shader auto fade_distance = abs(frag.camera_pos.y) * height_to_fade_distance_ratio; { fade_distance = max(fade_distance, min_fade_distance); fade_distance = min(fade_distance, max_fade_distance); } opacity_falloff = smoothstep(1.0, 0.0, distance_to_camera / fade_distance); ``` Et voilà! ![Final Grid](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/8fgjioiafly5efjc07rb.png) --- ## 2. Make it "infinite" We're almost done, but at the moment you can (eventually) move outside of the plane. Thankfully, it has a very easy solution, just move the plane *and the UVs* with the camera. Think of it as a moving treadmill. ![Treadmill cat](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/i2p9ruv7lctg6ka1lqyo.gif) In the vertex shader: ```C++ auto world_pos = positions[id]; world_pos.xyz *= grid_size; world_pos.xz += vert_in.camera_pos.xz; } ``` An important detail is to ignore the Y component of the camera position. We only want the grid to move *horizontally*, it shouldn't change when you move vertically. --- ## 3. Conclusions and future work Even though there're objectively better approaches, this solution has scratched my brain itch (for now) and provides a good enough gizmo for my purposes. The process of reinventing the wheel was a bit frustrating at times, but I'm glad I did. I wouldn't be happy having a copy-pasted piece of code that I don't understand and thus can't debug. I learn best by doing so it was a great exercise. Also, the process of writing this article forced me to dissect the code to be able to provide step by step examples. That uncovered a series of bugs and misunderstandings in my renderer and the shader itself. As a result, the version explained here is significantly different from the first one I wrote. In terms of future work, there's still a bunch of stuff to be done: - Fix the fade to black in the distance - Actually filter the grid instead of using that hacky fade - Colour the X/Z axis - Add a Y axis at 0,0? However, at the time of writing this, neither sound very fun, and I have a loong list of other features that do. At the end of the day, this is a toy project and its sole purpose is to have fun while I experiment and learn. ![This one doesn't spark joy](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/mdgo1c05ufhts9rrvk0u.png) So I consider it done (for now). --- ## 📚 References - [The Best Darn Grid Shader (Yet)](https://bgolus.medium.com/the-best-darn-grid-shader-yet-727f9278b9d8) - [An introduction to shader derivative functions](https://www.aclockworkberry.com/shader-derivative-functions/) - [GLSL's mod](https://registry.khronos.org/OpenGL-Refpages/gl4/html/mod.xhtml) - [HLSL's fmod](https://learn.microsoft.com/en-us/windows/win32/direct3dhlsl/dx-graphics-hlsl-fmod) - [MSL spec](https://developer.apple.com/metal/Metal-Shading-Language-Specification.pdf)
javiersalcedopuyo
1,875,883
Exploring Weatherstack API: Pricing, Features, and Alternatives
The demand for accurate and real-time weather data is ever-growing, whether for business...
0
2024-06-03T20:21:41
https://dev.to/ericksmith14/exploring-weatherstack-api-pricing-features-and-alternatives-565m
api, weather
The demand for accurate and real-time weather data is ever-growing, whether for business applications, academic research, or personal use. Weatherstack, a renowned global weather API, has emerged as a popular choice for accessing reliable weather information. In this blog, we will delve into the features, pricing, and alternatives to Weatherstack, offering a comprehensive overview to help you choose the best weather data solution for your needs. ## Features of Weatherstack Weatherstack provides a robust set of features designed to deliver accurate and real-time weather data. This **[weather web API](https://weatherstack.com/)** supports a wide range of applications, from simple weather apps to complex forecasting models. ## Real-Time Weather Data Weatherstack offers real-time weather data, ensuring you get the most current weather conditions. This feature is crucial for applications that require up-to-the-minute weather updates, such as transportation and event planning. ## Global Coverage With global weather API support, Weatherstack covers over 200,000 cities worldwide. This extensive coverage makes it an excellent choice for applications that need weather data from multiple locations around the globe. ## Historical Data The Weatherstack API also provides access to historical weather data. This feature is particularly useful for researchers and businesses that need to analyze weather trends over time. ## Weatherstack Easy Integration Weatherstack is known for its easy integration with various programming languages and platforms. The API supports multiple formats, including JSON, making it a versatile choice for developers. ## Weatherstack Free and Paid Plans Weatherstack offers a range of pricing plans, including a free tier. The free weather API JSON option allows developers to test and integrate weather data without any initial investment, while paid plans offer higher data limits and additional features. - Pricing: Weatherstack’s pricing is flexible, catering to different user needs. Here’s a breakdown of the available plans: - Free Plan: The free plan allows users to access basic features with a limit on the number of requests per month. This plan is ideal for testing and small-scale applications. - Paid Plans: Paid plans start at a modest price and scale up based on the number of API requests and additional features required. These plans are suitable for businesses and applications that need extensive and frequent access to weather data. - Custom Plans: For enterprises with specific needs, Weatherstack offers custom plans. These plans provide tailored solutions with dedicated support and higher request limits. ## Alternatives to Weatherstack While Weatherstack is a strong contender in the weather data space, several alternatives might better suit your needs, especially if you're looking for a free weather forecast API or a weather data API with specific features. - OpenWeatherMap: OpenWeatherMap is a popular alternative, offering a free weather API for testing along with extensive data coverage. It provides current weather data, forecasts, and historical data. - Weatherbit: Weatherbit offers a simple weather API with a focus on accuracy and detailed weather information. It provides real-time data, forecasts, and historical data, making it a solid choice for comprehensive weather applications. - AccuWeather API: AccuWeather is renowned for its accuracy. The API provides a wide range of weather data, including current conditions, forecasts, and severe weather alerts. It is an excellent choice for applications requiring the most accurate weather forecast. - ClimaCell (Tomorrow io): ClimaCell, now known as Tomorrow io, provides high-resolution weather data with a focus on hyperlocal forecasts. It offers both free and paid plans, catering to a wide range of needs. ## Conclusion Choosing the right weather API depends on your specific requirements, such as the need for **[real-time weather data](https://weatherstack.com/documentation)**, historical data, or forecast accuracy. Weatherstack stands out with its comprehensive features and flexible pricing plans, making it a reliable choice for various applications. However, alternatives like OpenWeatherMap, Weatherbit, AccuWeather, and Tomorrow.io offer competitive features that might better suit your needs. By carefully evaluating the features, pricing, and coverage of each option, you can find the best weather API to integrate into your project.
ericksmith14
1,875,876
Investing in Web3 Projects: A Modern Business and Finance Guide
The web3 world is thriving, with over 10,000 companies emerging in the cryptocurrency and blockchain...
0
2024-06-03T20:17:59
https://dev.to/korofetova_mila/investing-in-web3-projects-a-modern-business-and-finance-guide-3jj4
webdev, bitcoin, community, web3
The web3 world is thriving, with over 10,000 companies emerging in the cryptocurrency and blockchain space. Despite the 2022 bear market, investor interest remains high, with $7.1 billion poured into the sector, a 4.5x increase from 2021. Web3 represents the next internet generation, emphasizing decentralization and transparency. This shift allows businesses to control data without intermediaries, transforming how they operate. Key areas of Web3 application include: 1. Web3 Gaming: Blockchain-based games offer players autonomy and rewards, using metrics like active player count, transaction volume per user, and guild partnerships to measure success. Notable examples include Illuvium, a fantasy RPG where players train NFT-represented creatures. 2. Web3 Social Networks: Platforms like Friend.tech and Diamond App use blockchain to enable unique user interactions and data control. These networks offer financial incentives and privacy, allowing users to monetize content and maintain data sovereignty. MINDS, for instance, emphasizes user privacy and rewards engagement with its native currency. 3. Cryptoinvestment: Cryptocurrency investment offers security and efficiency, appealing across political lines in the US. Decentralized exchanges and peer-to-peer trading enhance asset control and reduce risks. Reputable exchanges like Kraken, Gemini, and WhiteBIT offer competitive trading fees. In conclusion, Web3 signifies a transformative era of the internet, providing users with digital ownership and control. Businesses can harness this potential to innovate, build stronger customer relationships, and benefit from a decentralized internet.
korofetova_mila
1,875,875
The Unexpected Uses of Glassine Paper: 12 Ways This Simple Material Shines
With its smooth, shiny feel and see-through sheen, glassine paper is a surprisingly useful material...
0
2024-06-03T20:17:47
https://dev.to/davidrsk/the-unexpected-uses-of-glassine-paper-12-ways-this-simple-material-shines-51el
With its smooth, shiny feel and see-through sheen, [glassine paper](https://elixirpackaging.com/what-is-glassine-paper/) is a surprisingly useful material that has been used for a long time. While it might seem like a simple sheet of paper, its unique properties make it a valuable tool in many different applications. ## 12 Ways for Glassine Paper Here are 12 unusual things you can do with glassine paper: ## 1. The Original Food Wrapper: Before plastic wrap became common, glassine paper was the most common way to package food. Because it doesn't stick to grease, it's great for wrapping up burgers, sandwiches, and other sticky treats. While letting air flow, it keeps wetness in, which keeps the bread from getting mushy and keeps it fresh. Some shops still use glassine boxes for fragile desserts or to show off flaky croissants. ## 2. Keeping your culinary creations safe: You can use glassine for more than just packing. You can also line bake pans with it. Cakes and cookies won't stick to the pan because of this thin sheet. It also makes cleanup a breeze. When making candy, it can be used to line trays so that chocolates and sweets don't stick together while they dry. ## 3. The Craft Corner Book Partner: Crafters love glassine because it can be used in many ways. Because it is see-through, it is perfect for making sewing project models or drawing patterns. The smooth surface is great for decoupage, which is the process of putting paper cutouts on top of something else. You can also make paper things out of it or fold it into pretty boxes. ## 4. Keeping Treasured Memories Safe: Surprisingly, glassine paper is good for photos and art. Because it doesn't contain acid, it's safe to store pictures for a long time without worrying about them sticking together or breaking down. It is often used by museums and libraries to protect fragile papers, fabric, and other valuable items from damage and wetness. ## 5. How to Keep Hardware Shiny: Because it doesn't stick to grease, glassine paper is great for keeping metal tools safe and in storage. You can keep tools and small machine parts from rusting or turning black by wrapping them in glassine. This is a great way to store holiday things that you won't need for a while. ## 6. Superhero Who Saves Seeds: If you grow your own food, folding paper into glassine boxes can be a useful way to store seeds after you gather them. The paper lets air flow through while keeping the seeds dry and out of the light. This makes sure that they will germinate well when it's time to plant them. ## 7. The eco-friendly gift wrap: More and more people are worried about how their actions affect the earth. Glassine is an environmentally friendly option to traditional gift wrap. Its simple beauty can make a gift look more classy, and unlike plastic wrapping paper, it breaks down naturally. To add a personal touch, you can even design basic glassine with stamps, bows, or natural things like dried flowers. ## 8. How to Make Clothes Look Their Best: Glassine paper is a good way to store delicate clothes like scarves and underwear. The paper keeps dust and dirt away while letting the cloth breathe. It can also be used to keep scarves and other knits from getting caught on other clothes while they are being stored. ## 9. The Secret Weapon in the Science Lab: Glassine paper can be used for many different kinds of projects in science classes. Because it is clear, it can be used to cover beakers or flasks while still letting people see what's inside. It can also be lined drying trays or used as a filter for easy projects. ## 10. The Best Kite Tail: Glassine makes a great tail for a homemade kite that will take you back in time. The kite is easy to catch the wind because it is light, and its smooth surface makes it easier to fly. For a more unique touch, you can use colored pencils or paints to decorate the paper. ## 11. How to Keep Your Cards Safe: Card fans can keep their valuable decks of cards clean and scratch-free by putting them in glassine cases. The paper keeps the cards safe from damage while still letting you see the cards. ## 12. How to Keep Your Pressed Flowers Looking New: Glassine paper, which used to be very popular, can be used for a lot of different things. It can be used for a lot of different things, from science studies and craft projects to seed bags and food wraps. Besides being useful, it's also a supporter of the environment and keeping valuable things safe. The next time you see this simple sheet, think of what it could be used for. It's a great example of how powerful simple things can be. [Packaging manufacturers](https://elixirpackaging.com/) recognize its versatility in various applications. ## Finally, For flower lovers who want to keep their beauty, glassine paper can be used to make lovely pressed flower arrangements. The flowers can dry flat on the paper and keep their color and shape. After the flowers are dry, they can be put together and held in place between sheets of glassine to make a one-of-a-kind show that will last.
davidrsk
1,875,872
Confidently Incorrect - Recipe Collection App : So far...
Confidently Incorrect since 1987 The set-up So I have been continuing to code...
0
2024-06-03T20:10:50
https://dev.to/bradley-hill/confidently-incorrect-recipe-collection-app-so-far-604
vue, python, mongodb, beginners
####_Confidently Incorrect since 1987_ ##**The set-up** So I have been continuing to code whilst looking for my first Apprenticeship (Alternance, here in France) job as a software dev, as I have said previously I have been continuing following [The Odin Project](https://www.theodinproject.com/) curriculum, but have recently had my focus switched onto a personal side-project that I had been toying with whilst I was studying at [Ada Tech School](https://adatechschool.fr/), a website where people could curate their own collection of recipes from a variety of different, well known, recipe/cooking websites. The initial inspiration was seeded when I stumbled across a web-scraping library made in Python for the express purpose of scraping from these popular recipe resources, [recipe-scrapers](https://github.com/hhursev/recipe-scrapers). My initial, now long abandoned, plan was to use Next/Nuxt to create the front-end and have the back-end be in Python, to allow me to use the recipe-scrapers library, and to use [Supabase](https://supabase.com/) to organise the database of users and their collection of recipes, and allow the users to enter a list of ingredients and be presented with a selection of recipes from their own curated collection that contained those recipes, allowing people to get some inspiration on what to cook based on the ingredients available to them at the time. Using the recipe-scrapers library, I would have allowed them to enter a URL to add a recipe into their collection, as well as a page displaying all the recipes currently stored in the collection and allow them to delete any they no longer wished to be included. Nothing too crazy, a pretty sweet simple idea, which I would make sure was responsive enough to look good when viewing on a phone. A week or two of work, and it'll be done.... ![Sweet Summer child meme](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/2homdpmkz8hx70rx9mbq.jpg) --- ##**The ==real== beginning** So with all the confidence of someone about to discovery how incorrect he was, I went about setting up a [Nuxt](https://nuxt.com/) project in my frontend directory, and very quickly got lost in the bells and whistles and functionalities included, all of them very useful and baked in, but quickly realising that, in reality, all I really wanted was to practice using [Vue](https://vuejs.org/), so with a quick back track and a quick [Vite](https://vitejs.dev/) install of Vue3, I was back to square one, albeit with a tiny sliver more of understanding of where and when to use Nuxt, namely, in a bigger and more complex project and in the **future** when I had a touch more experience. The next step then was to get my backend directory set-up, that should be a bit simpler, I've used python a little bit before, no need to dive into [Django](https://www.djangoproject.com/), I knew that [Flask](https://flask.palletsprojects.com/en/3.0.x/) was a relatively lightweight framework that I could use for my backend, and I was pretty certain it would have the essentials that I needed for my project...and at least so far I was correct. But boy did I not anticipate virtual environments and dependency issues.... ![Dilbert cartoon setting up a development environment](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/hze06437izmuyr4jihob.png) --- ##**Virtually environmentally dependent** My previous experience with Python had been pretty shallow, just writing little scripts and following a few tutorials, making simple console based games and such. Setting up a virtual environment wasn't necessarily difficult, although not the simplest thing I have done since starting to learn coding, it is obviously very useful. Creating a customisable environment, where I define the version of Python I want to use and install the needed libraries in a local environment, stopping me from polluting my global python environment with relatively specialised and particular libraries. The real issue was after setting up my virtual environment and installed the recipe-scrapers library and it's dependencies.....it didn't work. Now, it had been a couple of months since the last time I had tried using the recipe-scrapers library, but I couldn't see why it wasn't working. My initial instinct was that I had made a mistake in my code, but eventually after verifying it was correctly implemented, I thought perhaps I had made a mistake with setting up my venv (virtual environment), that being the most recent technology that I had implemented, but after removing it and setting it up again, and no obvious issues... I was stumped....for at least 3 days (more like a full week, if I am being honest...) Eventually I went back to the GitHub for the library and checked out the raised Issues, and lo-and-behold, right there at the top is someone pointing out that : > Adding lxml>=5.0.0,<5.1.0 to requirements-dev.txt and reinstalling via pip resolved this issue for me. Ahah! Sweet relief, it wasn't my own stupidity causing issues, but some dependency for the recipe-scrapers library having a breaking update! And the solution is right there, thank god for [disconsented](https://github.com/disconsented)! This sent off on a short detour exploring the use and usefulness of a requirements.txt file (A pythonesque json.lock file which lists all the necessary libraries and the version required), and solved my issue. Finally, a working recipe-scraper! ![It works Meme](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/xcsjlp3f1by0fkc6jrw5.jpg) --- ##**Preparations Complete....now what?** So finally I had everything in place. My root directory had backend and frontend directories, with a Python virtual environment set up with Flask framework structure in place, and a working recipe-scraper library, and a vite-Vue project set up in my frontend directory. The next step is planning the architecture of the site and figuring out what routes I would need to define, what kind of different pages I would need, what functionality I want to include for the MVP....wait, I'm forgetting something.... ##**Basic Databasing** The final part of my set-up tripod, a database! So my initial thought was to use a SQL based database with tables everywhere, with the help of a colleague I had sketched out a fairly basic schema for my relational database....but with a bit of reflection, and realising that recipe-scrapers was returning a JSON, I decided to look into [MongoDB](https://www.mongodb.com/), knowing that it's document based system might not be more suitable to my application, with storing recipes as documents in a collection for recipes and the relevant information (Title, Image, Time to cook, Ingredients, Cooking Instructions) and having a separate collection for Users (Username, email, password). So using the MongoDB Atlas online set-up, I created a basic database, and using the connection string provided, I will be able to connect from my backend to my database! --- ##**The End of the Beginning** So for now I have all the pieces in place and ready, and will need to give some thought to sketching out the architecture of the site itself, and roughly sketching out the API routes. In my next article, I will detail the next steps I have taken and how the structure of the actual site began to take form and evolve, as well as more of the details of the actual code being used in the front and back ends. Until next time, be safe and stay happy, thank you for taking the time to read my little side project introduction and set-up.
bradley-hill
1,875,870
How to Boost Your Brand and Sales of Smoking a Pre-Roll
In the ever-developing hashish enterprise, status out of the gang is vital for success. One way to do...
0
2024-06-03T20:06:55
https://dev.to/davidrsk/how-to-boost-your-brand-and-sales-of-smoking-a-pre-roll-1ngp
In the ever-developing hashish enterprise, status out of the gang is vital for success. One way to do that is by effectively boosting your logo and income from smoking [pre-roll](https://premiumcbdpackaging.com/how-to-smoke-a-pre-roll/). Pre-rolls, or pre-rolled joints, have become famous among hashish customers because of their comfort and simplicity. In this guide, we can discover ten techniques that will help you beautify your logo and increase the income from pre-rolls. ## Understanding Your Audience Before imposing any advertising and marketing techniques, it is essential to recognize your target market. Who are they? What are their preferences? Understanding your target market will help you tailor your branding, advertising, and marketing efforts to resonate more with them. ## Quality Matters One of the most critical elements in constructing a hit pre-roll logo is the taste of your product. Ensure that your pre-rolls are crafted from excellent hashish flowers and rolled to perfection. Consistency in pleasant will assist construct agree with together along with your clients and preserve them coming returned for greater. ## Differentiation With several Smoking a Pre-Roll manufacturer saturating the market, locating methods to distinguish yourself is key. Whether it is through precise packaging, revolutionary flavors, or unique promotions, discover something that sets your logo apart from the competition. ## Brand Storytelling Every logo has a story, and sharing yours can help forge a deeper connection with your clients. Whether it is the adventure of the way your logo got here or the muse in the back of your merchandise, storytelling humanizes your logo and makes it more relatable. ## Social media marketing Utilize the strength of social media to reach a broader target market and interact with your clients. Share charming content material, behind-the-scenes glimpses, and user-generated content material to keep your target market fascinated and worried, along with your logo. ## Influencer Collaborations Partnering with influencers within the hashish area can help expand your logo's reach and credibility. Look for influencers whose values align with your logo and collaborate with them to create genuine content material that resonates with their followers. ## Education and Awareness Many customers are getting to know approximately hashish, so offering academic assets may be quite valuable. Whether it is facts about approximately exceptional strains, intake methods, or the advantages of pre-rolls, instructing your target market can help construct agreement and loyalty. ## Customer Experience Offering tremendous customer support and a continuing shopping experience can have a long-lasting effect on your clients. From clean online ordering to rapid and discreet shipping, prioritize the desires and delight of your clients at each touchpoint. Providing [premium CBD packaging](https://premiumcbdpackaging.com/) enhances the overall customer experience, ensuring satisfaction from purchase to product enjoyment. ## Community Engagement Building a sense of network around your logo can foster loyalty and word-of-mouth referrals. Host events, sponsor neighborhood initiatives, and interact with your target market both online and offline to create a sturdy network around your logo. ## Adaptability and Innovation The hashish enterprise is continuously evolving, so it is vital to be adaptable and revolutionary. Keep an eye fixed on enterprise trends, pay attention to patron feedback, and be inclined to conform and iterate your logo and merchandise accordingly. ## Conclusion Boosting your logo and income from Smoking a Pre-Roll calls for a mixture of strategic branding, advertising, and marketing efforts, as well as a dedication to pleasant patron delight. By informing your target market, differentiating your logo, and leveraging numerous advertising and marketing channels, you could raise your logo and stand out within the aggressive hashish market.
davidrsk
1,875,869
How to build any recursive component (using element path)
I have created a package that gives your freedom to create any recursive component using path based...
0
2024-06-03T20:04:17
https://dev.to/pappijx/how-to-build-any-recursive-component-3ni4
javascript, webdev, programming, recursion
I have created a package that gives your freedom to create any recursive component using path based access to component. {% embed https://www.npmjs.com/package/wiz-ui %} ## Why we need a recursive component Ofcourse to create UI that look similar and to render complex nested data structures. > Recursive components in React are like Russian nesting dolls: perfect for handling infinite layers of hierarchical data, with simplicity! Examples: > **1. Side Navigation** : Where menu items look almost similar and may have nested elements under them. > **2. File directory listing** : Similar to a vscode nested directory/file listing > **3. Comment section** : You use reddit/X([Twitter](https://x.com/theayushpapnai)) right, Comments under comments. > **4. Rendering UI from Backend** : Creating dynamic UI on the go. (This may become tedious but your can try ofcourse). ## Why should you learn it Most asked interview question for machine coding round. ahemmm, actually its very helpful in understanding how recursion works and how to manipulate(update/edit/delete) array element recursively. But, traditional recursive way is a bit heavy in terms of time complexity. Time complexity of normal recursive function that calls itself k times is O(k^N) ## Whats new in this article Meri mehnat (My hardwork) This article is not the usual way to create and manipulate recursive component, we will use path based access. > **Path based access** : Access elements in nested arrays using a sequence of indices. Example ``` Lets take below object as sample { id: 1, name: "Root", children: [ { id: 2, name: "Child 1", children: [ { id: 3, name: "Grandchild 1", }, { id: 4, name: "Grandchild 2", }, ], }, { id: 5, name: "Child 2", children: [ { id: 6, name: "Grandchild 3", }, ], }, ], } ``` In the above array, if you recursively access **Grandchild 3**, you will need to parse all the elements before it (waste of time). The recursive approach will have high time complexity. **Solution** Now, what if I tell you that you can access each element just in O(K) times, K is the number of nesting the element is in. This is an old approach but very fast and useful. **Approach** So, the idea is to associate a path to each element as we start rendering. > **Path** : Its is a string or array of indices of each element to reach the final element. So with above example, I will add path to each node **Example** ``` { id: 1, path: [], name: "Root", children: [ { id: 2, path: [0], name: "Child 1", children: [ { id: 3, path: [0, 0], name: "Grandchild 1", }, { id: 4, path: [0, 1], name: "Grandchild 2", }, ], }, { id: 5, path: [1], name: "Child 2", children: [ { id: 6, path: [1, 0], name: "Grandchild 3", }, ], }, ], } ``` Now to access these elements you can easily run a for loop and access the element and delete in just path length. **Conclusion** Recursive components in React efficiently handle and render hierarchical data structures, simplifying the creation of similar-pattern UI elements with nested components. However, traditional recursion suffers from high time complexity, as exponential growth occurs when a function repeatedly calls itself, making it inefficient for deep, complex structures.
pappijx
1,875,868
The this Reference
The keyword this refers to the object itself. It can also be used inside a constructor to invoke...
0
2024-06-03T20:04:00
https://dev.to/paulike/the-this-reference-22h8
java, programming, learning, beginners
The keyword **this** refers to the object itself. It can also be used inside a constructor to invoke another constructor of the same class. The **this** _keyword_ is the name of a reference that an object can use to refer to itself. You can use the **this** keyword to reference the object’s instance members. For example, the following code in (a) uses **this** to reference the object’s **radius** and invokes its **getArea()** method explicitly. The **this** reference is normally omitted, as shown in (b). However, the **this** reference is needed to reference hidden data fields or invoke an overloaded constructor. ![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/ops3ishzmpd6hg4gxrzh.png) ## Using **this** to Reference Hidden Data Fields The **this** keyword can be used to reference a class’s _hidden data fields_. For example, a datafield name is often used as the parameter name in a setter method for the data field. In this case, the data field is hidden in the setter method. You need to reference the hidden data-field name in the method in order to set a new value to it. A hidden static variable can be accessed simply by using the **ClassName.staticVariable** reference. A hidden instance variable can be accessed by using the keyword **this**, as shown in Figure below (a). ![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/83o8lmabatbv6lgdjitq.png) The **this** keyword gives us a way to reference the object that invokes an instance method. To invoke **f1.setI(10), this.i = i** is executed, which assigns the value of parameter **i** to the data field **i** of this calling object **f1**. The keyword **this** refers to the object that invokes the instance method **setI**, as shown in Figure above (b). The line **F.k = k** means that the value in parameter **k** is assigned to the static data field **k** of the class, which is shared by all the objects of the class. ## Using **this** to Invoke a Constructor The **this** keyword can be used to invoke another constructor of the same class. For example, you can rewrite the **Circle** class as follows: ![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/zs6bxa2h5e2p2ve75qdb.png) The line **this(1.0)** in the second constructor invokes the first constructor with a **double** value argument. Java requires that the **this(arg-list)** statement appear first in the constructor before any other executable statements. If a class has multiple constructors, it is better to implement them using **this(arg-list)** as much as possible. In general, a constructor with no or fewer arguments can invoke a constructor with more arguments using **this(arg-list)**. This syntax often simplifies coding and makes the class easier to read and to maintain.
paulike
1,875,867
M&S International is a leader in the field of leather handbag manufacturers, achieving excellence in craftsmanship.
When it comes to the realm of fashion, leather handbag manufacturers have a position of distinction...
0
2024-06-03T20:03:32
https://dev.to/ms_international_d35f40b/ms-international-is-a-leader-in-the-field-of-leather-handbag-manufacturers-achieving-excellence-in-craftsmanship-5edi
When it comes to the realm of fashion, leather handbag manufacturers have a position of distinction due to the fact that they are enduringly elegant, long-lasting, and versatile. The makers of leather handbags, who are responsible for producing these highly sought-after products, are coming under increased scrutiny as the demand for these high-end accessories continues to climb consistently. When compared to them, M&S International stands out due to its unparalleled quality, forward-thinking designs, and unrelenting dedication to ensuring the complete happiness of its customers. The purpose of this essay is to provide a comprehensive analysis of the detailed procedures and standards that distinguish premier leather handbag makers, with a particular emphasis on the practices that are excellent at M&S International. ![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/x6frl0oyjppwj26559be.png) An Examination of the Craftsmanship Involved in the Production of Leather Handbags The production of leather handbags is a labor-intensive skill that requires a combination of time-honored artistry and cutting-edge technology. The procedure is exhaustive, and it guarantees that every handbag is of the greatest possible quality and fits the most fashionable requirements. An in-depth look at the phases that are involved is as follows: *SSelection of Leather*: The leather that is used is the most important factor in determining the quality of a handbag. M&S International and other leading producers of leather handbags get their leather from tanneries of the highest caliber,whicho provide premium hides that are free of any flaws for their customers. Because of this meticulous selection, the finished product will have texture, look, and durability characteristics. Design and prototyping: First and foremost, the creative process starts with the development of an original design. M&S International's team of designers consistently pushes the limits of fashion by designing handbag designs that are both one-of-a-kind and useful. These concepts are then transformed into prototypes, which are put through rigorous testing to ensure that every aspect is perfected, as well as to guarantee that they are both functional and appealing to the eye. *Cutting and Stitching*: It is essential to be precise when cutting leather in order to get the most of the material and to keep the quality of each individual piece intact. M&S International is a company that employs trained craftsmen that utilize cutting technology that is both sophisticated and conventional, as well as traditional hand-cutting processes. In addition to being an essential step, the stitching process makes use of threads of superior quality in order to improve the handbag's longevity and overall appearance. In the fourth step, which is called "Assembly and Finishing," the parts that have been cut and stitched are precisely assembled, and this stage also includes the addition of components like handles, zippers, and linings. At M&S International, the process of assembly is carried out with a great deal of attention to detail in order to guarantee that every handbag is both structurally solid and of aesthetically pleasing appearance. A refined appearance may be achieved by applying finishing touches such as edge painting and polishing. Quality Control: In the production process, it is very necessary to do stringent quality monitoring. In order to guarantee that each and every handbag is up to the company's stringent requirements, leading manufacturers of leather handbags, such as M&S International, conduct exhaustive inspections at each and every step of manufacturing. This dedication to quality ensures that each and every product that is delivered to the client is of the highest possible standard. A Discussion on the Importance of Quality in the Production of Leather Handbags When it comes to leather handbag manufacturers, quality is the distinguishing characteristic of every respected company. In addition to affecting the product's total worth, it also affects its durability and look. Throughout the whole of its production process, M&S International puts an extremely high priority on customer satisfaction. M&S International guarantees that each handbag emanates elegance and delivers longevity by procuring only the best leather. This is what we mean by "material excellence." M&S International's handbags are crafted by artists that possess a high level of expertise and offer a high level of accuracy and creativity to each and every one of their creations. Innovation: M&S International is able to maintain a competitive advantage in the industry by continuously investing in innovative design approaches and technology. When it comes to leather handbag manufacturers, M&S International is at the forefront of the pack. A number of important aspects identify M&S International as a prominent maker of leather handbags, including the following: "Unwavering Commitment to Quality": Each and every handbag that is sold by M&S International is a demonstration of the company's commitment to providing exceptional workmanship. Each and every product is guaranteed to be flawless thanks to stringent quality control procedures. "Sustainable Practices": M&S International is dedicated to the implementation of environmentally responsible production procedures. The business places an emphasis on environmentally responsible practices and obtains its leather from tanneries that are in full compliance with stringent environmental requirements. Trendsetting Designs: The design team at M&S International continuously creates handbags that are the epitome of both fashion and timelessness. In the sector of producing leather handbags, the company's capacity to innovate and adapt to shifting fashion trends helps it maintain its position at the forefront of development. **Customization and Personalization**: M&S International recognizes that clients have distinct preferences, and as a result, they provide customization services. When it comes to creating personalized handbags that are a reflection of their own style, customers have the ability to choose from a wide range of leather kinds, colors, and hardware. **Global Reach and Recognition**: M&S International's handbags are highly sought after all over the globe due to their reputation for quality. The fact that the company's items are well-liked in major fashion capitals such as New York, Paris, and Tokyo is evidence of the company's appeal on a global scale. An Approach That Is Focused on the Customer: When it comes to success, M&S International places a strong emphasis on providing excellent service to its customers. In order to maintain a consumer base that is both loyal and content, the brand makes it a priority to surpass expectations with each and every handbag. ** Concluding Remarks When it comes to the highly competitive industry of leather handbag manufacturers, M&S International is a shining example of quality, creativity, and the happiness of its customers. The thorough approach that the firm takes to every stage of manufacturing, from the selection of leather to the final quality checks, guarantees that each and every handbag is a marvel of workmanship. M&S International provides items that include a seamless combination of luxury, practicality, and classic style. These products are aimed at fashion fans and merchants who are looking for top-tier leather handbags. Explore the wonderful assortment that M&S International has to offer, and you will find the leather handbag manufacturers that are specifically tailored to your preferences and requirements. Spend some time with M&S International and experience the creativity and craftsmanship that have made them the industry leader in leather handbag manufacturing.
ms_international_d35f40b
1,875,866
Discover Elegance at Elitaae: The Best Arab Abaya Shop in Dubai, UAE
If you're in Dubai and on the hunt for the perfect abaya, look no further than Elitaae. Nestled in...
0
2024-06-03T19:55:46
https://dev.to/elitaae/discover-elegance-at-elitaae-the-best-arab-abaya-shop-in-dubai-uae-1m1c
abaya, design, dubaiabayadesign, arababayadesign
If you're in Dubai and on the hunt for the perfect abaya, look no further than Elitaae. Nestled in the heart of the UAE's fashion capital, Elitaae has earned its reputation as the best Arab abaya shop in Dubai. Let's explore why this boutique stands out among the rest. Stepping into Elitaae is like entering a world where tradition meets contemporary style. The shop boasts a stunning array of abayas, each designed with meticulous attention to detail. From classic black abayas to more modern designs featuring bold colors and unique cuts, Elitaae offers something for every taste. Their collection perfectly balances modesty with high fashion, making it a go-to destination for women who want to look elegant while honoring their cultural roots. One of the standout features of Elitaae is its commitment to quality. The fabrics used are nothing short of luxurious, ranging from soft chiffons to rich silks. Each abaya is crafted with precision, ensuring that it not only looks beautiful but also feels comfortable to wear. The intricate embroidery and embellishments add a touch of sophistication, making every piece a work of art. Elitaae's designs are not just about aesthetics—they're also about making a statement. The boutique regularly collaborates with top designers to create exclusive collections that reflect the latest trends while staying true to traditional elements. Whether you're attending a special event or just looking to add a stylish piece to your wardrobe, you'll find something that fits the bill at Elitaae. The shopping experience at Elitaae is another reason it’s the best in Dubai. The friendly and knowledgeable staff are always ready to assist, providing personalized recommendations to help you find the perfect abaya. Their customer service is top-notch, ensuring that every visit is enjoyable and memorable. Moreover, Elitaae understands that fashion is personal. They offer customization services, allowing you to tweak designs to suit your preferences. This level of personalization ensures that every customer leaves with a piece that feels uniquely their own. In conclusion, Elitaae is not just an [abaya shop](https://elitaae.com/collections/abaya)—it's a destination for elegance and tradition. With its exceptional quality, stunning designs, and impeccable service, it’s no wonder that Elitaae is hailed as the best Arab abaya shop in Dubai. So, if you find yourself in the UAE and in need of an exquisite abaya, make sure to visit Elitaae and experience the magic for yourself.
elitaae
1,875,863
The Scope of Variables
The scope of instance and static variables is the entire class, regardless of where the variables are...
0
2024-06-03T19:52:57
https://dev.to/paulike/the-scope-of-variables-2h0m
java, programming, learning, beginners
The scope of instance and static variables is the entire class, regardless of where the variables are declared. Local variables are declared and used inside a method locally. This section discusses the scope rules of all the variables in the context of a class. Instance and static variables in a class are referred to as the _class’s variables_ or _data fields_. A variable defined inside a method is referred to as a _local variable_. The scope of a class’s variables is the entire class, regardless of where the variables are declared. A class’s variables and methods can appear in any order in the class, as shown in Figure below (a). The exception is when a data field is initialized based on a reference to another data field. In such cases, the other data field must be declared first, as shown in Figure below (b). For consistency, this book declares data fields at the beginning of the class. ![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/cr3fpekh38ol7mmmr46b.png) You can declare a class’s variable only once, but you can declare the same variable name in a method many times in different nonnesting blocks. If a local variable has the same name as a class’s variable, the local variable takes precedence and the class’s variable with the same name is _hidden_. For example, in the following program, **x** is defined both as an instance variable and as a local variable in the method. ``` public class F { private int x = 0; // Instance variable private int y = 0; public F() { } public void p() { int x = 1; // Local variable System.out.println("x = " + x); System.out.println("y = " + y); } } ``` What is the output for **f.p()**, where **f** is an instance of **F**? The output for **f.p()** is **1** for **x** and **0** for **y**. Here is why: - **x** is declared as a data field with the initial value of **0** in the class, but it is also declared in the method **p()** with an initial value of **1**. The latter **x** is referenced in the **System.out.println** statement. - **y** is declared outside the method **p()**, but **y** is accessible inside the method To avoid confusion and mistakes, do not use the names of instance or static variables as local variable names, except for method parameters
paulike
1,875,860
Vunax
A post by Derrick Wamalwa
0
2024-06-03T19:49:14
https://dev.to/derrick_wamalwa_d74fda81e/vunax-1ma4
webdev, beginners, tutorial, python
![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/mu6j3y9xr65il53p1ayt.jpeg)
derrick_wamalwa_d74fda81e
1,875,858
Immutable Objects and Classes
You can define immutable classes to create immutable objects. The contents of immutable objects...
0
2024-06-03T19:45:17
https://dev.to/paulike/immutable-objects-and-classes-31gj
java, programming, learning, beginners
You can define immutable classes to create immutable objects. The contents of immutable objects cannot be changed. Normally, you create an object and allow its contents to be changed later. However, occasionally it is desirable to create an object whose contents cannot be changed once the object has been created. We call such an object as _immutable object_ and its class as _immutable class_. The **String** class, for example, is immutable. If you deleted the setter method in the **CircleWithPrivateDataFields** class, the class would be immutable, because radius is private and cannot be changed without a setter method. If a class is immutable, then all its data fields must be private and it cannot contain public setter methods for any data fields. A class with all private data fields and no mutators is not necessarily immutable. For example, the following **Student** class has all private data fields and no setter methods, but it is not an immutable class. ``` public class Student { private int id; private String name; private java.util.Date dateCreated; public Student(int ssn, String newName) { id = ssn; name = newName; dateCreated = new java.util.Date(); } public int getId() { return id; } public String getName() { return name; } public java.util.Date getDateCreated() { return dateCreated; } } ``` As shown in the following code, the data field **dateCreated** is returned using the **getDateCreated()** method. This is a reference to a **Date** object. Through this reference, the content for **dateCreated** can be changed. `public class Test { public static void main(String[] args) { Student student = new Student(111223333, "John"); java.util.Date dateCreated = student.getDateCreated(); dateCreated.setTime(200000); // Now dateCreated field is changed! } }` For a class to be immutable, it must meet the following requirements: - All data fields must be private. - There can’t be any mutator methods for data fields. - No accessor methods can return a reference to a data field that is mutable
paulike
1,875,857
Comparing C++ range libraries for filter+reverse case with non-trivial lambda
EDIT 2024-06-04: Fixed issue with flux implementation, thanks to tcbrindle for catching this. EDIT...
0
2024-06-03T19:42:42
https://hive.blog/cplusplus/@serpent7776/comparing-c-range-libraries-for-filter-reverse-case-with-non-trivial-lambda
cpp, performance, benchmark, programming
EDIT 2024-06-04: Fixed issue with flux implementation, thanks to [tcbrindle](https://github.com/tcbrindle) for catching this. EDIT 2024-06-24: Removed extra allocation from ranges libraries implementations. Thanks again to [tcbrindle](https://github.com/tcbrindle) for suggesting this. This only affected the 'every other item' test. C++ ranges are awesome as they often make the code simpler and easier to reason about. But how they compare against each other? To check that I did a micro-benchmark of c++ ranges for one particular use case I encountered in practice. The scenario I tested was as follows: - I have an input data set that needs to be filtered based on non-trivial lambda. - Only a subset of this data is needed. - Then an index is added to the elements. - The last step is to reverse the sequence. The repo with source code is here https://github.com/serpent7776/cpp-ranges-bench It's basically filter+take+enumerate+reverse, but there are two tricky things here: - The non-triviality of the lambda being used for filtering. In the example code, such a lambda is often a trivial function. What happens when the cost of invoking such lambda is not not negligible? - Filter+reverse is a tricky combination. Filtering yields a result set of unknown size, which means that subsequent reverse cannot be done easily in the general case. The ranges library needs to take both of these situations into account, otherwise it might introduce noticeable overhead. Let's check it out. The code uses [catch2](https://github.com/catchorg/Catch2/) to test for correctness and performance. Catch2 is a unit testing framework for C++, but it also provides basic micro-benchmarking features. Unfortunately, it doesn't provide any way to visualise the results, so I created a script and submitted [PR adding plotting capabilities to Catch](https://github.com/catchorg/Catch2/pull/2869). ## Tested implementations I have reviewed the following implementations: - clike - a simple C-like implementation. This still uses c++ `vector` and its methods, but it's just a for loop with if statements. It collects the result in a vector and when it's done, it reverses it in-place. - algorithms - Manual implementation using STL algorithms. Instead of operating on the elements themselves, it allocates an extra vector with indices and operates on that. It only copies the elements in the last step. - boost_adaptors - Uses boost::adaptors. It provides very minimal feature set, but it's surprisingly capable. Due to the limitations of adaptors library, it allocates an extra vector of filtered elements and operates on that. - rangesv3 - Uses [ranges-v3](https://github.com/ericniebler/range-v3) - range library for C++14/17/20. Very similar to the implementation using std::ranges. - stdranges - Uses C++23 ranges. This is the shortest and cleanest implementation. The compiler I was using didn't have `to` implemented, so I used equivalent function from `rangesv3` library. This may have affected the results. - fluxranges - Uses [flux](https://github.com/tcbrindle/flux), a C++20 library for sequence-oriented programming. A bit more noisy compared to other range implementations. I used the following versions of the libraries: - ranges-v3 0.12 - fluxranges faf2e0f8b9f616001890a87b613f47313443f8e5 - g++ stdlib, g++ (GCC) 13.2.1 20230801 All compiled in C++23 mode with the `-O2` flag. ## Test cases I have generated some random data using the [faker](https://pypi.org/project/Faker/) python library. The data is a set of usernames with an id and a set of connected names. I will search for usernames that match some criteria which involves looking through the connected names. This should be enough to consider the filter criteria as non-trivial. To do the comparisons I have generated 10 000 rows of data. The test cases I will check are: - all ismiths - select all items that have "ismith" as connection. There are 15 such entries in total. - 5 ismiths - select at most 5 items that have "ismith" as connection. - empty result set - searches for an item that doesn't exist, yielding no results. - early single item - searches for all items that have "henry79" as connection. There's only one such item, early in the sequence. - late single item - search for all items that have "emilymclaughlin" as connection. There's only one such item, late in the sequence. - every other item - accept every other item, while also performing some operation on the input data. ## Results ![all_ismiths](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/jv4wvct2bgcfdcl5lbop.png) ![5_ismiths](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/hde7a0ut407mx7wjnxw2.png) ![empty_result_set](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/le4dqrqjcpdqjacx01di.png) ![late_single_item](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/bsz0m123ef81lga6e1qp.png) ![every_other_item](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/4mvvp6s2b3hyiwt4lhxt.png) - Flux and std::ranges are very similar with very good results. The only exceptions are 'early single item' and 'every other item' cases. - Ranges-v3 was generally on par with other solutions. There are two cases where it's slower: 'all ismiths' and 'early single item'. - boost adaptors are overall quite good. In 'all ismiths', 'empty result set' and 'late single item' are on par with fastest implementation and just slightly slower in other cases. - C-like solution was always on par or better than other solutions. ## Some more details Let's try to see some more details. I will look at the 'early single item' test. This case is interesting, because there are big differences between the implementations. First, let's run the test case for a few more times. I'll make the test cases run 1000 times by adding this code to each implementation section. `auto _ = GENERATE(range(1, 1000));` This uses Catch2 [data generator](https://github.com/catchorg/Catch2/blob/devel/docs/generators.md) to execute the section multiple times, each time with a different value. In this case I'm not interested in the value itself, I'm only doing this to run the section again. Now let's run `perf stat` on it. To collect the data I'll will only run this single test case and only one implementation at a time, ignoring the benchmarks. I do this by invoking the compiled binary with the test-case name, the `-c` option with a section name that specifies which implementation to use and the `--skip-benchmarks` option so that no benchmarks are run. You can read more about [Catch2 command line usage](https://github.com/catchorg/Catch2/blob/devel/docs/command-line.md). `perf stat` is invoked with `-o stats --append`, which appends the perf data to `stats` file. Read more about [perf stat usage](https://www.man7.org/linux/man-pages/man1/perf-stat.1.html). ```sh : > stats # truncate stats file for t in clike algorithms boost_adaptors rangesv3 stdranges fluxranges; do perf stat -o stats --append ./read "early single item" -c $t --skip-benchmarks ; done ``` I will then convert the `stats` file with a [perf-stat-to-sc](https://github.com/serpent7776/bits/blob/master/perf-stat-to-sc/perf-stat-to-sc.pl) script I wrote. It will create a [sc-im spreadsheet](https://github.com/andmarti1424/sc-im), which will make it easier to compare the results. | command | context_switches | cpu_migrations | page_faults | cycles | instructions | insn_per_cycle | branches | branch_misses | backend_bound | bad_speculation | frontend_bound | retiring | real | user | sys | |-------------------------------------------------------------:|-------------------:|-------------------:|-------------------:|-------------------:|-------------------:|-------------------:|-------------------:|-------------------:|-------------------:|-------------------:|-------------------:|-------------------:|-------------------:|-------------------:|-------------------:| | clike | 0 | 0 | 1,417 | 9,763,699,969 | 27,310,955,366 | 27,310,955,366 | 6,611,235,612 | 84,103,168 | 7.2 | 22.2 | 21.2 | 49.4 | 3.573872222 | 3.437020000 | 0.119355000 | | rangesv3 | 0 | 0 | 1,399 | 11,634,561,888 | 29,211,691,985 | 29,211,691,985 | 7,103,602,542 | 123,617,995 | 8.1 | 22.9 | 22.8 | 46.2 | 4.132017782 | 4.001041000 | 0.116310000 | | boost_adaptors | 0 | 0 | 1,394 | 10,715,252,768 | 28,262,420,566 | 28,262,420,566 | 6,857,638,043 | 104,769,454 | 7.0 | 24.6 | 21.7 | 46.7 | 3.909084680 | 3.807669000 | 0.083028000 | | fluxranges | 0 | 0 | 1,394 | 10,775,098,223 | 28,262,194,528 | 28,262,194,528 | 6,857,615,031 | 104,014,045 | 7.6 | 25.1 | 21.4 | 46.0 | 3.965913088 | 3.814496000 | 0.132746000 | | stdranges | 0 | 0 | 1,413 | 10,731,793,760 | 28,251,095,766 | 28,251,095,766 | 6,857,354,712 | 104,070,967 | 7.6 | 23.0 | 21.7 | 47.7 | 3.955925504 | 3.844894000 | 0.092972000 | | algorithms | 0 | 0 | 7,623 | 10,706,979,451 | 28,341,604,071 | 28,341,604,071 | 6,867,444,605 | 104,582,547 | 6.9 | 25.5 | 21.5 | 46.1 | 3.911286798 | 3.801366000 | 0.089797000 | The first thing to notice is the difference in the number of page faults. Most implementations had about 1400 faults. The exceptions are custom algorithms with ~7600 faults. The differences in cycles and instructions are quite small. It's a bit bigger for rangesv3 and smaller for C-like though. The number of branches is also similar, slightly higher for rangesv3 and slightly lower for C-like. There are bigger differences in branch misses. The C-like implementation has the least number of misses. Rangesv3 have the most misses. But this collects stats from the entire program run. The issue is that most of the time is spent on reading and parsing the input file, which is the same in all cases. I want to collect stats only for the single implementation function. For this I can use `valgrind`'s `cachegrind` with additional code instrumentation. I will add `CACHEGRIND_START_INSTRUMENTATION` and `CACHEGRIND_STOP_INSTRUMENTATION` just before and after the implementation function I'm interested in and then run the binary with `--instr-at-start=no` which will disable instrumentation at startup and will wait for the first `CACHEGRIND_START_INSTRUMENTATION` to enable it. Read more about [cachegrind usage](https://www.man7.org/linux/man-pages/man1/valgrind.1.html). ```cpp SECTION("clike") { auto _ = GENERATE(range(1, 1000)); CACHEGRIND_START_INSTRUMENTATION; const std::vector<Out> found = clike(data, accept, max_items); CACHEGRIND_STOP_INSTRUMENTATION; REQUIRE(found == expected); } ``` ```sh valgrind --tool=cachegrind --instr-at-start=no ./read 'early single item' -c fluxranges ``` This is the data I got: | implementation | instructions executed | |:- | -: | | clike | 128 871 | | algorithms | 274 757 967 | | boost_adaptors | 274 757 967 | | rangesv3 | 549 464 985 | | stdranges | 274 757 967 | | fluxranges | 274 757 967 | It's a bit strange that all the results except for clike and rangesv3 are the same. But this confirms that C-like executes far fever instructions than other implementations and rangesv3, the most. ## Conclusions Ranges are really cool. They often make the code easier to read and reason about. But they do not always fit all the use cases. Sometimes, in some very specific cases, a for loop might give more control that is needed to get some better results. In general though, it's usually better to start with a ranges, as they will be good enough in most cases.
serpent7776
1,875,856
How to Install and Configure Cloudflared on Linux
To install the cloudflared package on a Linux system, follow these steps: Step 1: Update...
0
2024-06-03T19:41:15
https://dev.to/sh20raj/how-to-install-and-configure-cloudflared-on-linux-4l3
webdev, javascript, beginners, programming
To install the `cloudflared` package on a Linux system, follow these steps: ### Step 1: Update Your Package List First, make sure your package list is up to date: ```sh sudo apt-get update ``` ### Step 2: Download the Cloudflared Package Go to the Cloudflare download page to get the latest version of `cloudflared` for your architecture. Alternatively, you can use the following command to download it directly (assuming you are using a 64-bit system): ```sh wget https://github.com/cloudflare/cloudflared/releases/latest/download/cloudflared-linux-amd64.deb ``` ### Step 3: Install the Package Install the downloaded package using the `dpkg` command: ```sh sudo dpkg -i cloudflared-linux-amd64.deb ``` If there are any missing dependencies, fix them with: ```sh sudo apt-get install -f ``` ### Step 4: Verify the Installation Check if `cloudflared` is installed correctly by running: ```sh cloudflared --version ``` ### Optional: Configuring Cloudflared as a Service To set up `cloudflared` as a system service, follow these steps: 1. **Create a configuration file:** Create a directory for the configuration file if it doesn't exist: ```sh sudo mkdir -p /etc/cloudflared ``` Create a configuration file `/etc/cloudflared/config.yml` with your desired settings. For example: ```yml tunnel: your-tunnel-id credentials-file: /path/to/your/credentials-file.json ingress: - hostname: example.com service: http://localhost:8000 - service: http_status:404 ``` 2. **Create a systemd Service Unit File:** Create a file at `/etc/systemd/system/cloudflared.service` with the following content: ```ini [Unit] Description=cloudflared Tunnel After=network.target [Service] TimeoutStartSec=0 Type=notify ExecStart=/usr/local/bin/cloudflared --config /etc/cloudflared/config.yml run Restart=on-failure RestartSec=5s [Install] WantedBy=multi-user.target ``` 3. **Enable and Start the Service:** Enable the service so that it starts on boot: ```sh sudo systemctl enable cloudflared ``` Start the service: ```sh sudo systemctl start cloudflared ``` 4. **Check the Service Status:** Verify that the service is running correctly: ```sh sudo systemctl status cloudflared ``` This setup should ensure that `cloudflared` is installed and running on your Linux system.
sh20raj
1,875,855
Burn It All! Tired of Sweepers, Monitor and Watch Each Block Burn 🔥
A touch of magic in the dark forest of the blockchain. While blockchain is often described...
0
2024-06-03T19:40:29
https://dev.to/wolfcito/burn-it-all-tired-of-sweepers-monitor-and-watch-each-block-burn-12d0
## A touch of magic in the dark forest of the blockchain. While blockchain is often described as a battlefield, MEV represents an even greater challenge... It's a dark and uncertain territory. We'll explore this shadowy realm and learn how to tackle its challenges on our journey towards clarity and fairness in blockchain transactions. ![magic in the dark forest of the blockchain](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/fzhf1g6tpqkatx5l3y1s.png) Recently, I faced a challenging security situation. An unexpected error caused significant losses in one of my most cherished awards, earned after dedicated hours in a hackathon. It was a stark reminder of the importance of security in any project and of taking personal responsibility at all times. After overcoming feelings of frustration and anger, I realized there was an opportunity for growth and learning amidst adversity. I decided to tackle the problem with determination and seek innovative solutions. During my quest for answers, I came across a small script that promised to be the key to addressing security threats. Without hesitation, I immersed myself in the coding process, facing new challenges and learning concepts that were previously unknown to me. It is for this reason that I learned a bit about the concepts of MEV and how monitoring blocks could help us burn it ALL down!!! every block 🔥. Next, I'll share some of the resources I used to build a small shielding system for those who wish, while not recovering their ERC20 tokens, at least to protect what is already in that compromised safe. Firstly, I created an RPC URL access point to interact with Mode, following the [official documentation](https://docs.mode.network/tools/rpc#blast-api-decentralized-web3-infra-archival-node) meticulously. I also discovered a valuable tool in the [Blast API](https://blastapi.io/chains/mode). As part of my strategy, I chose an ERC20 token, such as USDC on the test network, to conduct comprehensive tests of the script. I identified the ABI and meticulously adjusted it to the code, ensuring every detail was correct. To send ERC-20 tokens instead of ETH, you need to interact with the corresponding ERC-20 token contract. This involves calling the `transfer` method of the token contract to transfer tokens to another address. Below, I'll show you how you can create your `burn` function to send ERC-20 tokens: ### Steps: 1. **Import the ERC-20 token ABI**: You need the ABI of the ERC-20 token contract. You can obtain it from Etherscan or the token contract repository. 2. **Create an instance of the ERC-20 token contract**: Use the `ethers.js` library to create an instance of the token contract. 3. **Call the `transfer` method**: Call the `transfer` method of the token contract to transfer the tokens to another address. ### Code to 'BURN' ERC-20 tokens: ```typescript import { utils, Wallet, BigNumber, Contract } from 'ethers' import args from './args' const { formatEther, parseUnits } = utils const flashbotsBeerFund = args.beerFund const erc20Abi = [ "function balanceOf(address owner) view returns (uint256)", "function transfer(address to, uint256 value) returns (bool)", ] const tokenAddress = "0xYourTokenAddressHere" // Replace with the ERC-20 token contract address const gasLimit = 100000 // Estimated gas limit for ERC-20 token transfers const burn = async (burnWallet: Wallet) => { const tokenContract = new Contract(tokenAddress, erc20Abi, burnWallet) // Get the balance of the ERC-20 token const balance = await tokenContract.balanceOf(burnWallet.address) if (balance.isZero()) { console.log(`Token balance is zero`) return } // Get the gas price const gasPrice = await burnWallet.provider.getGasPrice() console.log(`Gas price: ${utils.formatUnits(gasPrice, "gwei")} gwei`) // Calculate the gas cost const gasCost = gasPrice.mul(gasLimit) console.log(`Estimated gas cost: ${formatEther(gasCost)} ETH`) // Check if there are enough funds to cover the gas cost in ETH const ethBalance = await burnWallet.getBalance() if (ethBalance.lt(gasCost)) { console.log(`Insufficient ETH balance for gas (balance=${formatEther(ethBalance)} ETH, gasCost=${formatEther(gasCost)} ETH)`) return } try { console.log(`Burning ${utils.formatUnits(balance, 18)} tokens`) const tx = await tokenContract.transfer(flashbotsBeerFund, balance, { gasLimit, gasPrice, }) await tx.wait() // Wait for the transaction to be confirmed console.log( `Sent tx with hash ${tx.hash} burning ${utils.formatUnits( balance, 18 )} tokens at gas price ${utils.formatUnits(gasPrice, "gwei")} gwei` ) console.log( `Beer fund token balance: ${utils.formatUnits( await tokenContract.balanceOf(flashbotsBeerFund), 18 )} tokens` ) } catch (err: any) { console.log(`Error sending tx: ${err.message ?? err}`) } } export default burn ``` ### Explanation of the most important parts: 1. **Importing and configuring the ERC-20 token contract**: ```typescript const erc20Abi = [ "function balanceOf(address owner) view returns (uint256)", "function transfer(address to, uint256 value) returns (bool)", ] const tokenAddress = "0xYourTokenAddressHere" // Address of the ERC-20 token contract const tokenContract = new Contract(tokenAddress, erc20Abi, burnWallet) ``` 2. **Getting the balance of the ERC-20 token**: ```typescript const balance = await tokenContract.balanceOf(burnWallet.address) ``` 3. **Calculating the gas cost**: ```typescript const gasCost = gasPrice.mul(gasLimit) ``` 4. **Verifying sufficient ETH funds to cover the gas**: ```typescript const ethBalance = await burnWallet.getBalance() if (ethBalance.lt(gasCost)) { console.log(`Insufficient ETH balance for gas (balance=${formatEther(ethBalance)} ETH, gasCost=${formatEther(gasCost)} ETH)`) return } ``` 5. **BURNING the ERC-20 tokens**: ```typescript const tx = await tokenContract.transfer(flashbotsBeerFund, balance, { gasLimit, gasPrice, }) await tx.wait() // Wait for the transaction to be confirmed ``` This code burns the ERC-20 tokens after verifying that there is enough ETH to cover the gas cost. "It doesn't actually burn them ;) but I hope to deter many bad actors with that keyword." If you want to conduct a small test, you could create your own ERC20 token to play with. Here's one that I used for testing. [View on Explorer](https://sepolia.explorer.mode.network/token/0xd7dE2D2525A81A007FdFc8004DD8dbE7d60AF0c6) ![ERC20 token to play](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/k7pnr3midc2rfoyo3hfd.png) You'll likely have the question: > Can you use it on mainnet? The answer is yes, but at your own risk. Remember, you should never trust a stranger 100%, even if that stranger is the great and powerful Wolfcito. Although the experience was challenging and emotionally draining, I found a glimmer of hope amidst adversity: knowledge and a piece of code that could help others protect against similar threats in the future. While this code is simple in its design, its impact could be significant in the right hands. In conclusion, this experience taught me the hard way about the importance of security and the need to always be prepared to face unexpected challenges. Although the journey was difficult, each obstacle overcome represented an opportunity for growth and strengthening. I bid you farewell, but not before leaving you with this small tip to keep yourself a bit safer. Go and check that smart contracts don't have too many permissions over your assets at [revoke.cash](https://revoke.cash/). ![revoke.cash](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/5yvk8d4zrvbgwcrqpstr.png)
wolfcito
1,875,854
Array of Objects
An array can hold objects as well as primitive type values. Single-Dimensional Arrays, described how...
0
2024-06-03T19:39:14
https://dev.to/paulike/array-of-objects-3j1l
java, programming, learning, beginners
An array can hold objects as well as primitive type values. Single-Dimensional Arrays, described how to create arrays of primitive type elements. You can also create arrays of objects. For example, the following statement declares and creates an array of ten **Circle** objects: `Circle[] circleArray = new Circle[10];` To initialize **circleArray**, you can use a **for** loop like this one: `for (int i = 0; i < circleArray.length; i++) { circleArray[i] = new Circle(); }` An array of objects is actually an _array of reference variables_. So, invoking **circleArray[1].getArea()** involves two levels of referencing, as shown in Figure below. **circleArray** references the entire array; **circleArray[1]** references a **Circle** object. When an array of objects is created using the **new** operator, each element in the array is a reference variable with a default value of **null**. ![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/klxzknvlw4njxy2w38b5.png) The program below gives an example that demonstrates how to use an array of objects. The program summarizes the areas of an array of circles. The program creates **circleArray**, an array composed of five **Circle** objects; it then initializes circle radii with random values and displays the total area of the circles in the array. ``` package demo; public class TotalArea { public static void main(String[] args) { // Declare circleArray CircleWithPrivateDataFields[] circleArray; // Create circleArray circleArray = createCircleArray(); // Print circleArray and total areas of the circles printCircleArray(circleArray); } /** Create an array of Circle objects */ public static CircleWithPrivateDataFields[] createCircleArray() { CircleWithPrivateDataFields[] circleArray = new CircleWithPrivateDataFields[5]; for(int i = 0; i < circleArray.length; i++) { circleArray[i] = new CircleWithPrivateDataFields(Math.random() * 100); } // Return Circle array return circleArray; } /** Print an array of circles and their total area */ public static void printCircleArray(CircleWithPrivateDataFields[] circleArray) { System.out.printf("%-30s%-15s\n", "Radius", "Area"); for(int i = 0; i < circleArray.length; i++) { System.out.printf("%-30f%-15f\n", circleArray[i].getRadius(), circleArray[i].getArea()); } System.out.println("------------------------------------------"); // Compute and display the result System.out.printf("%-30s%-15f\n", "The total area of circles is", sum(circleArray) ); } /** Add circle areas */ public static double sum(CircleWithPrivateDataFields[] circleArray) { // Initialize sum double sum = 0; // Add areas to sum for(int i = 0; i < circleArray.length; i++) sum += circleArray[i].getArea(); return sum; } } ``` `Radius Area 70.577708 15649.941866 44.152266 6124.291736 24.867853 1942.792644 5.680718 101.380949 36.734246 4239.280350 —————————————————————————————————————————————- The total area of circles is 28056.687544` The program invokes **createCircleArray()** (line 10) to create an array of five circle objects. The circle radii are randomly generated using the **Math.random()** method (line 21). The **createCircleArray** method returns an array of **CircleWithPrivateDataFields** objects (line 25). The array is passed to the **printCircleArray** method, which displays the radius and area of each circle and the total area of the circles. The sum of the circle areas is computed by invoking the **sum** method (line 38), which takes the array of **CircleWithPrivateDataFields** objects as the argument and returns a **double** value for the total area.
paulike
1,875,851
Completing a Full-stack Coding Bootcamp - My Experience Attending Flatiron School and a Phase by Phase Breakdown
Overview and Picking a Bootcamp Schedule Phase breakdown Phase 1 Phase 2 Phase 3 Phase 4 Phase...
0
2024-06-03T19:33:28
https://dev.to/khamerling-potts/completing-a-full-stack-coding-bootcamp-my-experience-attending-flatiron-school-and-a-phase-by-phase-breakdown-5531
webdev, codingbootcamp, beginners, programming
{%- # TOC start -%} - [Overview and Picking a Bootcamp Schedule](#overview-and-picking-a-bootcamp-schedule) - [Phase breakdown](#phase-breakdown) - [Phase 1](#phase-1) - [Phase 2](#phase-2) - [Phase 3](#phase-3) - [Phase 4](#phase-4) - [Phase 5](#phase-5) Over the past couple of days, I put the finishing touches on my Capstone project for Flatiron School, thus marking the end of my coding bootcamp journey. Whether you’re considering bootcamps or simply curious, I hope to provide insight into the curriculum and my overall experience as a career-transitioner and aspiring software engineer. ## Overview and Picking a Bootcamp Schedule Coding bootcamps are educational programs that aim to teach you the foundations of full-stack software engineering. My program, Flatiron School, offers live full-time (both in-person and virtual) as well as virtual self-paced instruction. Here are some factors to consider when deciding whether to do a live or self-paced bootcamp: ### Live, full-time bootcamp (approx 15 weeks) is great for people who… * Can commit to a full-time weekly schedule in addition to outside work after class and on weekends. This likely means no job or large personal commitments on the side for the duration of bootcamp. * Want to complete bootcamp, and therefore begin job hunting, sooner rather than later * Desire or benefit from live classes with instructors and peers. This can strengthen your sense of accountability, community, and ability to maintain a strict schedule. ### Self-paced, asynchronous bootcamp is great for people who… * Have outside commitments, whether personal or work-related, and cannot dedicate 60 hours/week to bootcamp * Excel in time management and enjoy creating their own schedules * Want flexibility in the amount of time to complete coursework, study for assessments, and complete projects I opted for Flatiron’s self-paced, 40-week schedule and had a wonderful experience. Although the content is the same across instruction modes, the self-paced program was much more hands-off in its approach. Course content is administered on Canvas and includes a mix of readings, videos, and engaging labs that solidify your understanding of the material. However, I never felt as though help was unreachable. I had 4 excellent instructors who were available to meet for technical help, advice, and leading review sessions with other classmates. Taking advantage of those resources played a huge part in feeling like I was part of a structured learning community. For the majority of my journey, I decided to treat this as a full-time job and use the flexibility to spend more time doing outside learning and refining my projects. I completed earlier phases at a faster rate, giving me more time to focus on larger projects during phases 4 and 5. ## Phase Breakdown ### Phase 1 Phase 1 of bootcamp focused on introducing JavaScript and front-end web development. We learned about functions, working with common data structures (such as arrays and objects), and algorithms. We used our new JS knowledge to create the structure of web pages, make them interactive through event-handling, and communicate with external APIs as sources of data. My final project for this phase was a distance-based, [adoptable pet browser](https://github.com/khamerling-potts/AdoptAPet) that fetches real data from Petfinder’s database. ### Phase 2 Phase 2 maintained a focus on JavaScript and front end development while introducing a key new concept - React. We first learned React basics, including an overview of how it works/setup, components, props, state, and events. In my personal experience, once I felt completely comfortable with state, the rest of the phase was smooth sailing. (Check out my [blog post](https://dev.to/khamerling-potts/intro-to-state-in-react-example-walkthrough-1gnn) for more on state!) We moved on from fundamentals to data fetching (touched on in phase 1), side effects, and client-side routing. This allowed us to create multi-page interactive websites (and with much more efficiency than using vanilla JS). [My project](https://github.com/khamerling-potts/SongSaver) was a song library tool allowing users to search spotify tracks and save music. ### Phase 3 Phase 3 is where the curriculum switched tracks and I experienced the steepest learning curve. We didn’t use JavaScript or build websites. Instead, we learned Python and how to use this new language to create a backend API. This phase gave us more control over future projects by teaching us how to persist and manage data in a database. Specifically, this curriculum taught SQL (Structured Query Language), a language for creating and manipulating databases. We spent a significant amount of time learning bare SQL commands and how to implement them using Python. Although I may not need to continue handwriting SQL commands in future projects, I developed a stronger understanding of the tools used in Phase 4 with this knowledge. We don’t shy away from using helpful extensions and libraries when applicable, but experiencing how they work behind the scenes is critical to using them correctly and deeply understanding your code. A strong emphasis of this phase was object-oriented programming, which is a principle I will likely use in any future full-stack application I build. I delve deeper into objects and their relationships in [this blog post](https://dev.to/khamerling-potts/object-relationships-modeling-real-world-relationships-in-python-k28). [My project for Phase 3](https://github.com/khamerling-potts/rdm) was a command line interface (i.e. accessed in terminal/command shell) used for managing research sites, projects, and investigators. This was inspired by my previous role as a clinical psychology research coordinator in a hospital setting. ### Phase 4 Phase 4 built on the skills gained in Phase 3 and taught Flask, a web microframework that uses Python to assist with web application development. We also learned how to use Flask-SQLAlchemy, an extension used to create databases and configure database models with relationships, as well as use version control with our databases. In Phase 3, we essentially created our own object-relational mappers using Python and SQL. The tools taught in Phase 4 simplify this task for us while relying on our knowledge built in Phase 3. This phase also taught us how to build RESTful APIs, a critical step in developing our first full-stack applications. We used our APIs to handle requests from the front end of our applications (e.g. when we submit forms), process corresponding back end actions (e.g. modifying data in a database), and returning a response to the front end. [This blog post](https://dev.to/khamerling-potts/intro-to-flask-restful-walkthrough-in-python-2p6o) explains this process in more detail and how it’s used in full-stack development. My [final project for Phase 4](https://github.com/khamerling-potts/lendz) was a full-stack application similar to a Buy Nothing group, where users can post listings for free items or services from their own accounts and rate each other. ### Phase 5 The final phase of Flatiron’s bootcamp does not introduce any new content and is a dedicated time to work on our capstone projects. Our capstones had similar requirements to our Phase 4 projects but are more robust and incorporate new, self-taught content. I decided to spend more time on my capstone and teach myself mobile app development using React Native. [My project](https://github.com/khamerling-potts/healthseed-client) is an organizational app for managing health information, serving as a central place to track providers, medications, routines, and appointments. It combines knowledge from all phases and includes a mobile front end, Flask API, and deployed database built with Python and Flask-SQLAlchemy. I will continue making improvements post-graduation! If you made it to this point and have any lingering questions or simply want to connect, please reach out to me on [Linkedin](https://www.linkedin.com/in/kyra-hamerling-potts/) and I’d love to chat!
khamerling-potts
1,875,848
React's useReducer Hook
I am working on creating a customer intake form for a local bicycle repair shop. The form includes...
0
2024-06-03T19:32:33
https://dev.to/saandre0217/reacts-usereducer-hook-1pno
react, tutorial, javascript, usereducer
I am working on creating a customer intake form for a local bicycle repair shop. The form includes sections where the customer can input their contact information, details about the bike, and check off which services they need to schedule. The primary goal is to ensure all of the components I create are as reusable and customizable as possible. In this post I will explain how I set up this form so that there is no need to make any changes to the components if a question on the form needs to be updated or added. The only aspect that will need to be updated is the data imported into the components. While planning, I determined the contact and bike information would need text inputs, and the services would need checkbox inputs. Because the checkbox input would produce a boolean value and the text would produce a string, their event handling functionality would be different, so I planned to create a component for each input type. I realized there would be many state changes occurring through events in the child components, but I needed state to be managed at the parent most component. At first, I was not exactly sure how to handle this, but after some research I found the React hook, useReducer. This hook allows you to add a reducer function to your component which helps to consolidate the state update logic outside of your component in a single function. Just like when initializing useState, you would call the hook at the top level of your parent component. In this example, that is Form.jsx. useReducer takes in 2 parameters: a reducer function and the initial state of the component. It returns the updated state and a dispatch function that uses the reducer to make updates to the state. ``` export const Parent = () => { const [state, dispatch] = useReducer(reducer, initialState) ... } ``` ## useReducer Arguments Let’s look a little closer at what this reducer argument is made up of. The reducer function takes in the current state and an action object. The action object typically has a property named ‘type’ that is used to define the action that is taken on the state. Additionally, the action object can have additional properties. In the example below, it also has a ‘key’ property and a newValue property. The reducer function is often made up of a switch case that is dependent on the type property on the action object. Based on the type that is being passed in, a defined action is taken on the state. In the example below, if the type is ‘add_text’, then the state is returned with a new value at the key defined by the action object. The reducer function can be defined within your component or outside and imported in. In this example it is defined as follows: ``` const reducer = (state, action) => { switch(action.type) { case 'add_text': { return { ...state, [action.key]: action.newValue } } case 'change_boolean': { return { ...state, [action.key]: !state[action.key] } } } } ``` In this example the initial state is an object named allQuestions which is defined outside of the component and imported in. It is in the exact shape the backend expects so that all of the data points can be added to the database on submission. ## What useReducer Returns Now that we understand what arguments need to be passed into the useReducer, let’s look at what the hook returns and how it is used to help manage the state. useReducer returns the dispatch function which allows you to update state and trigger a rerender. An action object is the only argument that needs to be passed into the dispatch function. This object will include the properties that were used in the reducer function, for example: ``` dispatch({ type:'add_text', key: someKeyName, newValue: someNewValueName }) ``` This would be similar to the setState function that is returned when using useState. Also similar to useState, the new state with the appropriate updates made is returned when dispatch is called. ##In Action Now let’s see this in action! First, I defined two event handling functions that wrap the dispatch function. The reason for this is to be able to pass in values to the action object. This is important for reusability. This way I can pass in the state property that needs to be updated, as well as, the new value of that property when the type is ‘add_text’ ``` const handleAddedText = (e, key) => { dispatch({ type:'add_text', key: key, newValue: e.target.value }) } const handleCheckBoxChange = (key) => { dispatch({ type:'change_boolean', key: key }) } ``` These functions are then passed down to `TextInputList.jsx` and `CheckboxInputList.jsx` from `From.jsx`. To manage the questions that will make up the form, I created an array of objects with the necessary question information for each input. I imported the respective question data arrays into each List component to map through and return the Input component which takes the event handler function passed down originally from Form.jsx, as well as the question data. Let’s look at the CheckboxInputList component for example: ``` import React from 'react'; import { CheckBoxInput } from './checkboxInput'; import { checkBoxLabels as cbLabelObjArr } from '../formQuestionData'; export const CheckBoxForm = ({ handleCheckBoxChange }) => { return ( <div>{cbLabelObjArr.map((obj, i) => ( <CheckBoxInput key={i} label={obj.label} dbName={obj.dbName} handleCheckBoxChange={handleCheckBoxChange} /> ))}</div> ) } ``` Now let’s check out how the CheckBoxInput component is set up: ``` import React from 'react'; export const CheckBoxInput = ({ key, label, dbName, handleCheckBoxChange }) => { return ( <div > <div>{label}</div> <input type='checkbox' onChange={() => handleCheckBoxChange(dbName)} /> </div> ) } ``` And that's it! Now, we have successfully utilized the useReducer hook to organize event handling across multiple components, and created highly flexible components. Throughout this process I became very familiar and confident in using the useReducer hook and created highly reusable components that will ensure the client has flexibility to update their form as needed. For more information and details check out [React's useReducer documentation](https://react.dev/reference/react/useReducer).
saandre0217
1,875,847
How to Find the Second Largest Element in an Array
Finding the second largest element in an array can be approached in multiple ways. Here, we'll...
27,580
2024-06-03T19:28:41
https://blog.masum.dev/how-to-find-the-second-largest-element-in-an-array
Finding the second largest element in an array can be approached in multiple ways. Here, we'll discuss three methods: using **sorting**, a better approach with **two linear traversals** and an optimal **single-pass approach**. ### Solution 1: Sorting One straightforward method to find the second largest element in an array is by sorting the array in ascending order and then traversing the sorted array from the end to find the second largest unique element. **Implementation:** ```cpp // Solution-1: Sorting // Time Complexity: O(n log n) // Space Complexity: O(1) int secondLargestElement(vector<int> &arr) { sort(arr.begin(), arr.end()); int large = arr[arr.size() - 1]; int secondLarge = large; for (int i = arr.size() - 2; i >= 0; i--) { if (arr[i] != large) { secondLarge = arr[i]; break; } } return secondLarge; } ``` **Logic**: **1. Sort the array**: Use the `sort` function to sort the array in ascending order. **2. Find the second largest element**: Traverse the sorted array from the end to find the first element that is not equal to the largest element. **Time Complexity**: O(n log n) * **Explanation**: The time complexity is dominated by the sorting algorithm. **Space Complexity**: O(1) * **Explanation**: Sorting is done in place, so no additional space is used. **Example**: * **Input**: `arr = [10, 20, 5, 3, 100]` * **Output**: `20` * **Explanation**: The sorted array is `[3, 5, 10, 20, 100]`. The second largest element is `20`. --- ### Solution 2: Better Approach A more efficient method is to use two linear traversals of the array. First, find the **largest** element and then find the **second largest** element excluding the largest one. **Implementation:** ```cpp // Solution-2: Better Approach // Time Complexity: O(n), We do two linear traversals in our array // Space Complexity: O(1) int secondLargestElement(vector<int> &arr, int n) { // Find the largest element in the array int large = arr[0]; for (int i = 0; i < n; i++) { if (arr[i] > large) { large = arr[i]; } } // Find the second largest element excluding the largest one int secondLarge = INT_MIN; for (int i = 0; i < n; i++) { if (arr[i] > secondLarge && arr[i] != large) { secondLarge = arr[i]; } } return secondLarge; } ``` **Logic**: **1. Find the largest element**: Traverse the array to find the largest element. **2. Find the second largest element**: Traverse the array again to find the largest element excluding the previously found largest element. **Time Complexity**: O(n) * **Explanation**: Two separate linear traversals of the array. **Space Complexity**: O(1) * **Explanation**: Only a constant amount of extra space is used. **Example**: * **Input**: `arr = [10, 20, 5, 3, 100]` * **Output**: `20` * **Explanation**: The largest element is `100`. The second largest element found during the second traversal is `20`. --- ### Solution 3: Optimal Approach The most efficient method is a single-pass solution where we keep track of both the **largest** and **second largest** elements during one traversal of the array. **Implementation:** ```cpp // Solution-3: Optimal Approach // Time Complexity: O(n), Single-pass solution // Space Complexity: O(1) int secondLargestElement(vector<int> &arr, int n) { int large = INT_MIN; int secondLarge = INT_MIN; for (int i = 0; i < n; i++) { if (arr[i] > large) { secondLarge = large; large = arr[i]; } else if (arr[i] > secondLarge && arr[i] != large) { secondLarge = arr[i]; } } return secondLarge; } ``` **Logic**: **1. Initialize** `large` **and** `secondLarge`: Set them to the smallest possible integer values `INT_MIN`. **2. Single-pass traversal**: During one traversal of the array, update `large` and `secondLarge` accordingly. **3. Update logic**: If the current element is greater than `large`, update `secondLarge` to be `large` and then update `large`. Otherwise, if the current element is greater than `secondLarge` and not equal to `large`, update `secondLarge`. **Time Complexity**: O(n) * **Explanation**: Single linear traversal of the array. **Space Complexity**: O(1) * **Explanation**: Only a constant amount of extra space is used. **Example**: * **Input**: `arr = [10, 20, 5, 3, 100]` * **Output**: `20` * **Explanation**: The traversal updates `large` to `100` and `secondLarge` to `20`. --- ### Comparison * **Sorting Method**: * **Pros**: Simple and easy to implement. * **Cons**: Less efficient due to the O(n log n) time complexity. * **Use Case**: Suitable when sorting the array is required for other purposes. * **Better Approach**: * **Pros**: More efficient with O(n) time complexity using two passes. * **Cons**: Requires two traversals of the array. * **Use Case**: Useful when you want a more efficient solution than sorting but don’t mind two passes. * **Optimal Approach**: * **Pros**: Most efficient with O(n) time complexity using a single pass. * **Cons**: Slightly more complex logic. * **Use Case**: Ideal for finding the second largest element in large datasets efficiently. ### Edge Cases * **Empty Array**: If the array is empty, the function should handle it by returning an appropriate value or throwing an exception. * **Single Element Array**: If the array contains only one element, there is no second largest element, so the function should handle this case appropriately. * **All Elements Same**: If all elements in the array are the same, there is no distinct second largest element, so the function should handle this case appropriately. ### Additional Notes * **Stability**: Since we are only finding the second largest element, stability (preserving the order of equal elements) is not relevant. * **Efficiency**: The optimal approach is the most efficient for large datasets due to its single-pass solution. * **Use Cases**: The optimal method is generally preferred for its O(n) time complexity and O(1) space complexity, making it suitable for large datasets. ### Conclusion Finding the second largest element in an array can be done efficiently using various methods. The sorting approach is simple but less efficient, while the better and optimal approaches provide more efficient solutions with linear time complexity. Understanding these approaches provides valuable insights into different problem-solving strategies and their trade-offs. ---
masum-dev
1,875,934
Cursos Sobre Educação Midiática Gratuitos Do MEC
O Ministério da Educação (MEC), em colaboração com organizações da sociedade civil, está com...
0
2024-06-23T13:51:27
https://guiadeti.com.br/cursos-educacao-midiatica-gratuitos-mec/
cursogratuito, cursosgratuitos, midiasdigitais, seguranca
--- title: Cursos Sobre Educação Midiática Gratuitos Do MEC published: true date: 2024-06-03 19:28:34 UTC tags: CursoGratuito,cursosgratuitos,midiasdigitais,seguranca canonical_url: https://guiadeti.com.br/cursos-educacao-midiatica-gratuitos-mec/ --- O Ministério da Educação (MEC), em colaboração com organizações da sociedade civil, está com inscrições abertas para uma série de cursos gratuitos focados em Educação Midiática. Disponíveis através do Ambiente Virtual de Aprendizagem do MEC (Avamec), esses cursos autoinstrucionais são especialmente projetados para a formação continuada de professores e outros profissionais da educação. Os participantes terão a oportunidade de explorar aspectos fundamentais da educação midiática essenciais para a cidadania digital, incluindo o enfrentamento à desinformação, segurança online, promoção dos direitos humanos e fortalecimento da democracia. Essa iniciativa tem o objetivo de equipar os educadores com as ferramentas necessárias para navegar e ensinar efetivamente no crescente universo digital. ## Cursos Educação Midiática O Ministério da Educação (MEC), em uma colaboração significativa com organizações da sociedade civil, anuncia a abertura das inscrições para uma nova série de cursos gratuitos disponíveis através do Ambiente Virtual de Aprendizagem do MEC (Avamec). ![](https://guiadeti.com.br/wp-content/uploads/2024/06/image-4.png) _Imagem da página do curso_ Os cursos são dedicados à formação continuada de educadores e profissionais do setor educacional, focando em competências vitais para a era digital. As inscrições estão abertas até o dia 7 de junho. ### Conteúdo e Objetivos dos Cursos Os cursos autoinstrucionais lançados pelo MEC procuram equipar os participantes com habilidades essenciais para enfrentar desafios modernos na educação. Tendo temas que vão desde o enfrentamento à desinformação até a promoção dos direitos humanos e a segurança online, os cursos procuram fortalecer a democracia através de uma educação midiática eficaz. Os participantes aprenderão a implementar práticas que contribuam para uma cidadania digital mais informada e engajada. Confira a ementa: #### Atividades complementares de educação midiática - Como identificar um conteúdo impostor; - Como reagir a boatos sobre ataques a escolas; - A importância das histórias orais para a educação midiática; - Falando sobre ataques online e trolls; - Guia de orientações para construir uma internet sem fake news; - Guia infanto-juvenil para uma influência responsável; - Guia para medir o impacto de ações de educação midiática; - Guia para o enfrentamento da violência política de gênero; - O papel da educação midiática em situações de pânico; - Qual o papel da polarização no debate público. #### Educação midiática para adolescentes e jovens – Cidadão Digital - O que são informações?; - Prejuízos da desinformação à sociedade e política; - 7 tipos de desinformação; - Educação midiática; - Agências de checagem; - Responsabilidade das plataformas; - Quiz. #### Fake Dói: verificação de conteúdo na internet com técnicas abertas - Introdução à desinformação: aprenda conceitos básicos sobre os tipos de desinformação; - Busca Avançada na Web: aprenda a usar métodos de pesquisa sofisticados para encontrar informações precisas e relevantes; - Desvendando Sites e Mídias Sociais: métodos para analisar a credibilidade de websites e perfis de mídias sociais; - Investigações Visuais: técnicas para verificar a autenticidade de imagens e vídeos online; - Máquina do Tempo na Internet: utilização de ferramentas como o Wayback Machine para verificar o histórico e a evolução de páginas na internet. ### Materiais e Recursos Didáticos Os cursos são enriquecidos com uma variedade de materiais didáticos desenvolvidos pelo Redes Cordiais, incluindo guias práticos para a divulgação em sala de aula e estratégias para entender e lidar com os desafios da nova era digital. Estes recursos são feitos para ampliar o conhecimento dos educadores, fornecendo-lhes ferramentas práticas para melhorar a entrega educacional no contexto atual. <aside> <div>Você pode gostar</div> <div> <div> <div> <div> <span><img decoding="async" width="280" height="210" src="https://guiadeti.com.br/wp-content/uploads/2024/06/Cursos-Educacao-Midiatica-280x210.png" alt="Cursos Educação Midiática" title="Cursos Educação Midiática"></span> </div> <span>Cursos Sobre Educação Midiática Gratuitos Do MEC</span> <a href="https://guiadeti.com.br/cursos-educacao-midiatica-gratuitos-mec/" title="Cursos Sobre Educação Midiática Gratuitos Do MEC"></a> </div> </div> <div> <div> <div> <span><img decoding="async" width="280" height="210" src="https://guiadeti.com.br/wp-content/uploads/2024/06/Bootcamp-Java-E-IA-280x210.png" alt="Bootcamp Java E IA" title="Bootcamp Java E IA"></span> </div> <span>Bootcamp De Java com IA Gratuito: Desenvolva Seu Portifólio</span> <a href="https://guiadeti.com.br/bootcamp-desenvolvimento-java-ia-gratuito/" title="Bootcamp De Java com IA Gratuito: Desenvolva Seu Portifólio"></a> </div> </div> <div> <div> <div> <span><img decoding="async" width="280" height="210" src="https://guiadeti.com.br/wp-content/uploads/2024/05/Certificacao-GitHub-280x210.png" alt="Certificação GitHub" title="Certificação GitHub"></span> </div> <span>Certificação GitHub Foundations: Concorra A Voucher Para Exame</span> <a href="https://guiadeti.com.br/certificacao-github-foundations-voucher-para-exame/" title="Certificação GitHub Foundations: Concorra A Voucher Para Exame"></a> </div> </div> <div> <div> <div> <span><img decoding="async" width="280" height="210" src="https://guiadeti.com.br/wp-content/uploads/2024/05/Masterclass-De-Inteligencia-Artificial-280x210.png" alt="Masterclass De Inteligência Artificial" title="Masterclass De Inteligência Artificial"></span> </div> <span>Masterclass De Inteligência Artificial: Aprenda Do Zero Gratuitamente</span> <a href="https://guiadeti.com.br/masterclass-inteligencia-artificial-gratuita-2/" title="Masterclass De Inteligência Artificial: Aprenda Do Zero Gratuitamente"></a> </div> </div> </div> </aside> ## Educação Midiática A educação midiática é um campo de estudo e prática que objetiva equipar cidadãos de todas as idades com as habilidades necessárias para compreender, analisar, avaliar e criar mídia em diversas formas. Diante do aumento do consumo de informação digital e a prevalência das redes sociais, torna-se essencial que indivíduos desenvolvam a capacidade de discernir entre informações autênticas e enganosas e utilizem as ferramentas de mídia de maneira responsável e ética. ### Importância da Educação Midiática A educação midiática fortalece o pensamento crítico, permitindo que os indivíduos questionem a veracidade e o propósito das informações que recebem. Em um mundo onde as notícias falsas e a desinformação são prevalentes, essas habilidades são indispensáveis para a formação de uma sociedade bem informada e participativa. ### Desenvolvimento de Habilidades de Comunicação A educação midiática também envolve a criação de conteúdo. Isso inclui escrever artigos, produzir vídeos e utilizar plataformas digitais de maneira eficaz e responsável. Essas habilidades são cruciais não apenas para comunicações pessoais e profissionais, mas também para a participação ativa na sociedade digital. ### Componentes Principais da Educação Midiática Ensina os estudantes a entenderem como os textos de mídia são construídos e quais técnicas são usadas para persuadir e informar o público, o que envolve o estudo de diferentes gêneros de mídia, incluindo notícias, publicidade, filmes, e mídia digital. ### Produção de Mídia Foca no ensino de habilidades práticas necessárias para produzir diferentes tipos de conteúdo midiático. Os estudantes aprendem sobre técnicas de redação, fotografia, filmagem e edição, bem como sobre a ética da publicação e distribuição de conteúdo. ### Desafios e Oportunidades na Educação Midiática A rápida evolução da tecnologia apresenta tanto desafios quanto oportunidades para a educação midiática. Educadores precisam se manter atualizados com as últimas ferramentas e plataformas para ensinar efetivamente as habilidades relevantes. Ao mesmo tempo, a tecnologia oferece novos meios e métodos para ensinar, aprender e criar conteúdo de mídia. ## MEC O Ministério da Educação (MEC) é uma das principais instituições governamentais do Brasil, responsável por coordenar e desenvolver políticas públicas de educação em todo o país. A missão é garantir o acesso à educação de qualidade para todos os brasileiros, supervisionando desde a educação básica até o ensino superior. O MEC atua no desenvolvimento de programas educacionais, na distribuição de recursos e na definição de padrões e diretrizes para o sistema educacional brasileiro. ### Estrutura e Funções do MEC O MEC é responsável por formular e implementar políticas educacionais que promovam a educação em todos os níveis, incluindo a elaboração de planos nacionais de educação, a coordenação de esforços para melhorar a qualidade do ensino e a administração de fundos federais destinados à educação. ### Supervisão do Ensino O ministério supervisiona diversas áreas do ensino no Brasil, incluindo educação básica, técnica, tecnológica e superior. O MEC também é encarregado da avaliação da qualidade do ensino através de exames nacionais, como o ENEM (Exame Nacional do Ensino Médio), que é crucial para o acesso ao ensino superior no país. ## Aproveite a oportunidade de expandir seus conhecimentos — inscreva-se nos cursos gratuitos do MEC agora mesmo! As [inscrições para o curso Atividades complementares de educação midiática](https://avamec.mec.gov.br/#/instituicao/redescordiais/curso/16015/informacoes) devem ser realizadas no portal Avamec. As [inscrições para o curso Educação midiática para adolescentes e jovens – Cidadão Digital](https://avamec.mec.gov.br/#/instituicao/safernetbrasil/curso/16012/informacoes) devem ser realizadas no portal Avamec. As [inscrições para o curso Fake Dói: verificação de conteúdo na internet com técnicas abertas](https://avamec.mec.gov.br/#/instituicao/institutovero/curso/16014/informacoes)devem ser realizadas no portal Avamec. ## Ajude a disseminar educação de qualidade! Compartilhe os cursos gratuitos do MEC com sua rede! Gostou do conteúdo sobre os cursos gratuitos do MEC? Então compartilhe com a galera! O post [Cursos Sobre Educação Midiática Gratuitos Do MEC](https://guiadeti.com.br/cursos-educacao-midiatica-gratuitos-mec/) apareceu primeiro em [Guia de TI](https://guiadeti.com.br).
guiadeti
1,875,846
https://www.aiflow.ltd/
A post by Granger Aj
0
2024-06-03T19:28:33
https://dev.to/granger_aj_1109fd18d64004/httpswwwaiflowltd-3bpa
granger_aj_1109fd18d64004
1,875,845
Passing Objects to Methods
Passing an object to a method is to pass the reference of the object. You can pass objects to...
0
2024-06-03T19:27:52
https://dev.to/paulike/passing-objects-to-methods-2ooj
java, programming, learning, beginners
Passing an object to a method is to pass the reference of the object. You can pass objects to methods. Like passing an array, passing an object is actually passing the reference of the object. The following code passes the **myCircle** object as an argument to the **printCircle** method: ``` public class Test { public static void main(String[] args) { // CircleWithPrivateDataFields is defined in Listing 9.8 CircleWithPrivateDataFields myCircle = new CircleWithPrivateDataFields(5.0); printCircle(myCircle); } public static void printCircle(CircleWithPrivateDataFields c) { System.out.println("The area of the circle of radius " + c.getRadius() + " is " + c.getArea()); } } ``` Java uses exactly one mode of passing arguments: pass-by-value. In the preceding code, the value of **myCircle** is passed to the **printCircle** method. This value is a reference to a **Circle** object. The program below demonstrates the difference between passing a primitive type value and passing a reference value. ![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/tgzcz3gsbdskvdhfd9v1.png) `Radius Area 1.0 3.141592653589793 2.0 12.566370614359172 3.0 29.274333882308138 4.0 50.26548245743669 5.0 79.53981633974483 Radius is 6.0 n is 5` The **CircleWithPrivateDataFields** class is defined in the previous post. The program passes a **CircleWithPrivateDataFields** object **myCircle** and an integer value from **n** to invoke **printAreas(myCircle, n)** (line 11), which prints a table of areas for radii **1**, **2**, **3**, **4**, **5**, as shown in the sample output. ![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/ekdnju2ctfbf8h3i78es.png) Figure above shows the call stack for executing the methods in the program. Note that the objects are stored in a heap. When passing an argument of a primitive data type, the value of the argument is passed. In this case, the value of **n** (**5**) is passed to **times**. Inside the **printAreas** method, the content of **times** is changed; this does not affect the content of **n**. When passing an argument of a reference type, the reference of the object is passed. In this case, **c** contains a reference for the object that is also referenced via **myCircle**. Therefore, changing the properties of the object through **c** inside the **printAreas** method has the same effect as doing so outside the method through the variable **myCircle**. Pass-by-value on references can be best described semantically as _pass-by-sharing_; that is, the object referenced in the method is the same as the object being passed.
paulike
1,875,844
Creating a Single Bundle Configuration for Create React App
Creating a Single Bundle Configuration for Create React App In this guide, I'll walk you...
0
2024-06-03T19:25:36
https://dev.to/issamboutissante/creating-a-single-bundle-configuration-for-create-react-app-4m6i
react, javascript, webdev, reactsinglebundle
## Creating a Single Bundle Configuration for Create React App In this guide, I'll walk you through the process of configuring a Create React App (CRA) based project to generate a single JavaScript file and inline all CSS and JavaScript directly into the `index.html`. This is particularly useful when the application needs to be embedded in environments that do not support multiple file references, such as certain mobile application frameworks. ## Background By default, CRA splits the application code into various chunks to optimize load performance. However, this default behavior can be altered to bundle the entire application code into a single file. Additionally, Gulp is used to inline all the assets into `index.html`, creating a self-contained application. ## Steps The configuration involves two main steps: 1. **Disabling Code Splitting in CRA.** 2. **Inlining all assets into `index.html` using Gulp.** ### Step 1: Disabling Code Splitting To prevent CRA from splitting the code into chunks, we use `react-app-rewired` along with `customize-cra`. These tools allow us to modify the internal webpack configuration without ejecting. 1. Install `react-app-rewired` and `customize-cra`: ```bash npm install react-app-rewired customize-cra --save-dev ``` 2. Create a `config-overrides.js` file in the root directory with the following content: ```javascript // config-overrides.js const { override } = require("customize-cra"); module.exports = override((config) => { config.optimization.splitChunks = { cacheGroups: { default: false, }, }; config.optimization.runtimeChunk = false; return config; }); ``` ### Step 2: Inlining Assets with Gulp Gulp automates the inlining of CSS and JS into `index.html`. 1. Install Gulp and related plugins: ```bash npm install gulp gulp-inline-source gulp-replace gulp-cheerio --save-dev ``` 2. Set up the `gulpfile.js`: ```javascript // gulpfile.js const gulp = require("gulp"); const inlineSource = require("gulp-inline-source"); const replace = require("gulp-replace"); const cheerio = require("gulp-cheerio"); gulp.task("default", () => { return gulp .src("./build/*.html") .pipe( cheerio(($) => { const scriptTag = $("script[defer]"); $("body").append(scriptTag); }) ) .pipe(replace('.js"></script>', '.js" inline></script>')) .pipe(replace('rel="stylesheet">', 'rel="stylesheet" inline>')) .pipe( inlineSource({ compress: false, ignore: ["png"], }) ) .pipe(gulp.dest("./build")); }); ``` ### Step 3: Environment Variables Use a `.env` file to set environment variables for the build process: ```plaintext INLINE_RUNTIME_CHUNK=false GENERATE_SOURCEMAP=false SKIP_PREFLIGHT_CHECK=true ``` ### Step 4: Modifying package.json Update the package.json to use `react-app-rewired`: ```json "scripts": { "start": "react-app-rewired start", "build": "react-app-rewired build && npx gulp", "test": "react-app-rewired test", "eject": "react-scripts eject" }, ``` **Note:** Ensure that you remove any code that forces chunks, such as the following, from your application: ```javascript // If you want to start measuring performance in your app, pass a function // to log results (for example: reportWebVitals(console.log)) // or send to an analytics endpoint. Learn more: https://bit.ly/CRA-vitals reportWebVitals(); ``` ### Step 5: Running the Build After setting up, run the build command to generate the single bundle and inline assets: ```bash npm run build ``` The build script will create a production build with a single JavaScript file, and the Gulp command will inline all resources into the `index.html`. ## Conclusion Following this configuration allows you to package a CRA application into a single `index.html` file with all assets inlined. This setup is suitable for use cases that require a standalone file for the entire application. It is recommended to thoroughly test the application after these modifications to ensure functionality remains intact. Feel free to reach out if you have any questions or run into issues. Happy coding!
issamboutissante
1,875,838
Building PDF Open Source Services with Angular & GCP - Architecture Overview
Welcome to the first part of the journey in building open source PDF service using Angular...
0
2024-06-03T19:20:37
https://dev.to/dalenguyen/building-pdf-open-source-services-with-angular-gcp-part-1-4pi3
angular, webdev, gcp, firebase
Welcome to the first part of the journey in building open source PDF service using Angular (Analogjs), Firestore, Cloud Storage, and CloudRun. This project serves as a platform for sharing my knowledge, continually learning best practices, and simultaneously contributing to the community. **Part 1: [Architecture Overview](https://dev.to/dalenguyen/building-pdf-open-source-services-with-angular-gcp-part-1-4pi3)** Part 2: [Deploy services to Cloud Run](https://dev.to/dalenguyen/building-pdf-open-source-services-with-angular-gcp-deploy-services-to-cloud-run-56i) Demo: https://pdfun.xyz  GitHub: https://github.com/dalenguyen/pdfun ## The First Feature: Upload and Resize PDF Files (Unsecured - kind of) Our first feature is all about simplicity and functionality. It allows you to upload and resize PDF files. This feature is designed with a user-friendly interface that makes it easy for anyone to use, regardless of their technical background. ![Resize PDF file UI](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/1owro0exr6vt9bh62abb.png) There is no security in place if you don't log in the application. Anyone know how Firebase works, can access the file that you uploaded. The only security measure for publicly is that all files will be deleted in 1 day. ## Technology Stack The technology stack we've chosen for this project includes Angular (Analgojs), Firestore, Cloud Storage, and CloudRun. These technologies were chosen for their robustness, scalability, and ease of use. They work together seamlessly to provide a smooth user experience. Here is the flow: ![PDF processing event flow](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/3b48s9wh9dmd8mhzu067.png) - First, you upload their PDF file - The UI will upload their file to Cloud Storage + a record in Firestore - Created event from Firestore will trigger a service from Cloud Run - Cloud Run retrieve data from Firestore & file from Cloud Storage - Cloud Run start to resize the PDF, then upload it back to Cloud Storage and Firestore - The updated record will reflect on the UI with link for users to download the resized file - All PDF files / records will be delete after 1 day based on the TTL policy ## Try It Out I encourage you to try out our service. You can support me by starring the GitHub repository or sponsoring the project. Your support helps the project continue to improve and add new features. ## Questions? If you have any questions or run into any issues, please don't hesitate to [create an issue](https://github.com/dalenguyen/pdfun/issues) on our GitHub repository. Alternatively, you can chat with me. I'm here to help and would love to hear your feedback. Stay tuned for **Part 2** where I will show you how to secure your uploaded files. Until then, happy coding!
dalenguyen
1,872,436
Running Django Application On Kubernetes
Imagine your Django application running in Kubernetes equipped with features of Kubernetes building a...
0
2024-06-03T19:16:31
https://dev.to/deepcodr/running-django-application-on-kubernetes-53ah
docker, kubernetes, django, deepcodr
Imagine your Django application running in Kubernetes equipped with features of Kubernetes building a strong scalable and highly available application. In this post let's see how to dockerize and deploy a Django application on Kubernetes. Deployment of an application always starts with having a nice and error-free application. To begin with, we will use a sample Django application with a sample view to provide Hello World! response. <-- You can use your application or To follow along you can refer to the code from the below repo --> {% embed https://github.com/Deepcodr/django-hello-world %} <hr> Now that the application is ready, start with dockerizing and building an image. For this, we will create a requirements.txt of required modules. ``` pip freeze > "requirements.txt" ``` <br/> Lets write a recipe for our docker image in Dockerfile. The minimal configuration for Dockerfile is provided below you can modify it accordingly. ``` FROM python:3.9.19-alpine RUN mkdir /DjangoHelloWorld WORKDIR /DjangoHelloWorld COPY / . RUN pip install -r requirements.txt EXPOSE 8000 CMD python manage.py runserver 0.0.0.0:8000 ``` > _To use SQLite database you can simply add migrations and make migration commands in CMD at the last line_ ``` CMD python manage.py makemigrations && python manage.py migrate && python manage.py runserver 0.0.0.0:8000 ``` <br/> Done!✅ Build the docker image using below using Docker. ``` docker build -t deepcodr/node-hello-world . ``` That should create image for our application. Spin up a container if you want to test the application. ``` docker run -dp 8000:8000 deepcodr/node-hello-world ``` Test the application thoroughly and then we are ready for deployment. <br/> Lets provide YAML configuration for Kubernetes Deployment and Service. ``` apiVersion : v1 kind : Service metadata : name : djangohelloworld spec : selector : app : djangohelloworld type : LoadBalancer ports : - port : 8000 targetPort : 8000 --- apiVersion : apps/v1 kind : Deployment metadata : name : djangohelloworld spec : replicas : 1 selector : matchLabels : app : djangohelloworld template : metadata : labels : app : djangohelloworld spec : containers : - name : djangohelloworld image : deepcodr/django-hello-world ports : - containerPort : 8000 imagePullPolicy : Always ``` The above configuration is sufficient to run our application with minimal configuration. Save the configuration and apply it with kubectl ``` kubectl apply -f nodehelloworld.yaml ``` This should create a service and deployment in Kubernetes.Lets view running pods and services in cluster. ``` kubectl get svc kubectl get pods ``` ![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/hht7lrjbqpdemjpp170h.png) If you see a service and pods running. Your application should work 🎉 <br/> Test the application by hitting URL in browser. You will see your homepage. ![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/0bu32sf620obmcusf7d5.png) Now that you know how to deploy Django application on Kubernetes 🗿, You are ready to build and configure more complex scenarios for Django with Kubernetes and explore Kubernetes in depth.
deepcodr
1,875,788
L&T Personal Loan: Everything You Need to Know
A Personal Loan is an unsecured form of loan that can be used for multiple reasons, like education,...
0
2024-06-03T19:15:59
https://dev.to/idealmarketingagency/lt-personal-loan-everything-you-need-to-know-1gig
l, t, loan
A Personal Loan is an unsecured form of loan that can be used for multiple reasons, like education, home renovation, weddings, travel purposes, medical arrangements, or general purposes. It is considered to be one of the [Best Banks for Personal Loan](https://www.mymoneymantra.com/which-bank-is-best-for-personal-loan) facilities that provides a completely digital process, quick disbursal, transparency, no collateral required, and minimal documentation. One can avail of a personal loan of up to INR 7 lakhs at an interest rate of 12% with flexible loan tenures of 12 to 48 months. **## Processing Fees and Charges** Mentioned below are the processing fees and charges in order to apply for L&T Finance Personal Loans: ![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/pp6s7kli7bznywhccd6q.png) **## Eligibility Criteria** Mentioned below are the eligibility parameters to be met in order to apply for L&T Finance Personal Loan: ## In the case of Consumer Loans: - An applicant must be an Indian citizen with valid proof of ID. - The minimum age of an applicant should not be less than 23 years. - The maximum age of an applicant should not exceed 57 years. - This loan can be availed across all major towns and cities in India. **## In the case of Micro Loans:** An applicant must be a woman borrower. The minimum age of an applicant should be 20 years. The maximum age of an applicant should be 60 years. This loan can be availed across India. **## Documentation Required** Mentioned below is the list of documents required to be provided while applying for [L&T Personal Loan](https://www.mymoneymantra.com/personal-loans/lnt-finance): ![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/6ew4lrxy5gt6w3drhc3c.png) **## L&T Personal Loan Interest Rates** The L&T Finance personal loan interest rates start from 12% p.a. onwards. The NBFC provides consumer loans at a fixed interest rate. The interest rates depend on multiple factors, such as the applicant’s credit score, age, and loan amount. ![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/c8esdoxyzlnu9yu0h6vl.png) **## How do you check L&T Personal Loan Application Status?** Mentioned below are the different ways to check the L&T Personal Loan Application Status: **Through L&T Website: ** - Visit the L & T Financial Services webpage. - At the bottom of the page, click the tab “Self-Help” option. - Now, click on the loan details. - Now, provide the loan agreement number provided at the time of applying for the loan. - Next, click “Get OTP”. - You will get an OTP on the registered mobile number. - After which, you can check the loan status along with the other details. **Through SMS:** - Below is the format of the message that is to be sent to 9212025555 from the registered mobile number to know the loan status: - 'INST' for the number of instalments paid and the number of future instalments - 'OSB' for the outstanding balance of your loan - 'SANC' for the loan sanctioned amount and tenure - 'BRN' space ‘first three letters of your city’ to know the nearest LTFS branch locations in your city - 'EMI' to get your next EMI amount and due date - 'POS' to get the outstanding principal amount on the loan - ‘LAN’ to find out your loan account number, which is linked to your registered mobile number **##By Calling Customer Care:** You can also check the L&T Loan Status by calling customer care at 7264888777 or by sending an e-mail to customer@ltfs.com from your registered e-mail address. **## How do you apply for an L&T Finance Personal Loan?** ** Step 1:** The official webpage of the lender bank, i.e. L&T Bank, should be opened. **Step 2:** Under the tab “Our Products”, choose the option “Personal Loans”. **Step 3:** Check eligibility and then click “Apply Now” once all the eligibility parameters are met. **Step 4:** Provide your personal and professional details as required. **Step 5:** Choose “L&T Finance” from the list of loan providers. **Step 6:** Fill out the loan amount and tenure along with it. Click “Submit”. **Step 7:** You can also apply for an L&T Personal loan by visiting the nearest branch or calling. **## How to Use L&T Personal Loan EMI Calculator?** L&T Personal Loan EMI Calculator is an online personal financial tool that can help customers plan their long-term and short-term financial needs in an easy and hassle-free manner. It is designed to make the process of EMI calculation easy and eliminate errors that occur during manual calculation. The financial tools that take into account parameters like - - Loan amount - Tenure of the loan - Rate of interest applied to the loan. The L&T First Bank personal loan calculator has a pre-set formula, which is: **E = P x r x (1+r) ^ n / ((1+r) ^ n-1)** Where: E = EMI amount P = Principal R = Rate of interest N = Tenure of the loan The following are the benefits of the ICICI bank EMI calculator - It will help customers to properly determine their EMI. - It will help to determine the loan tenure. - It will make the calculation process very easy. - It will eradicate any error that can happen in any calculation. - It will help customer to plan their budget effectively. **## L&T Finance Personal Loan Customer Care Numbers** ![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/qg4ujxo7535kcrpc9tem.png)
idealmarketingagency
1,875,787
How to Find the Largest Element in an Array
Finding the largest element in an array is a common problem that can be approached in different ways....
27,580
2024-06-03T19:15:41
https://blog.masum.dev/how-to-find-the-largest-element-in-an-array
algorithms, computerscience, cpp, tutorial
Finding the largest element in an array is a common problem that can be approached in different ways. Here, we'll discuss two methods: one using **sorting** and the other using an **iterative approach**. ### Solution 1: Sorting One straightforward method to find the largest element in an array is by sorting the array in ascending order and then selecting the last element. **Implementation**: ```cpp // Solution-1: Sorting // (Sort the array in ascending order & get the last element) // Time Complexity: O(nlogn) // Space Complexity: O(1) int findLargestElement(vector<int> &arr) { sort(arr.begin(), arr.end()); // Return the last element of the sorted array return arr[arr.size() - 1]; } ``` **Logic:** **1. Sort the array**: Use the `sort` function to sort the array in ascending order. **2. Return the last element**: The largest element will be the last element in the sorted array. **Time Complexity**: O(n log n) * **Explanation**: The time complexity is dominated by the sorting algorithm. **Space Complexity**: O(1) * **Explanation**: Sorting is done in place, so no additional space is used. **Example**: * **Input**: `arr = [10, 20, 5, 3, 100]` * **Output**: `100` * **Explanation**: The sorted array is `[3, 5, 10, 20, 100]` and the last element is `100`. --- ### Solution 2: Iterative Approach A more efficient method is to iterate through the array while keeping track of the maximum element found so far. **Implementation**: ```cpp // Solution-2: Iterative Approach // (Using a max variable) // Time Complexity: O(n) // Space Complexity: O(1) int findLargestElement(vector<int> &arr, int n) { int max = arr[0]; for (int i = 0; i < n; i++) { if (arr[i] > max) { max = arr[i]; } } return max; } ``` **Logic**: **1. Initialize** `max` **variable**: Set `max` to the first element of the array. **2. Iterate through the array**: Compare each element with `max`. **3. Update** `max`: If the current element is greater than `max`, update `max` with the current element. **4. Return** `max`: After completing the iteration, `max` holds the largest element. **Time Complexity**: O(n) * **Explanation**: The array is traversed once. **Space Complexity**: O(1) * **Explanation**: Only a constant amount of extra space is used. **Example**: * **Input**: `arr = [10, 20, 5, 3, 100]` * **Output**: `100` * **Explanation**: The largest element found during the iteration is `100`. --- ### Comparison * **Sorting Method**: * **Pros**: Simple and easy to implement. * **Cons**: Less efficient due to the O(n log n) time complexity. * **Use Case**: Suitable when sorting the array is required for other purposes. * **Iterative Method**: * **Pros**: More efficient with O(n) time complexity. * **Cons**: Slightly more complex logic. * **Use Case**: Ideal for finding the largest element when sorting is not needed. ### Edge Cases * **Empty Array**: If the array is empty, the function should handle it by returning an appropriate value or throwing an exception. * **Single Element Array**: If the array contains only one element, that element is the largest by default. * **All Elements Same**: If all elements in the array are the same, the function should correctly return that element as the largest. ### Additional Notes * **Stability**: Since we are only finding the largest element, stability (preserving the order of equal elements) is not relevant. * **Efficiency**: The iterative approach is more efficient for large datasets compared to the sorting method. * **Use Cases**: The iterative method is generally preferred for its O(n) time complexity and O(1) space complexity, making it suitable for large datasets. ### Conclusion Both methods are effective for finding the largest element in an array but the iterative approach is more efficient in terms of time complexity. Understanding both approaches provides valuable insights into different problem-solving strategies and their trade-offs. ---
masum-dev