Posted on Leave a comment

ChatGPT 50 News Not to Miss (March 2023)

5/5 – (1 vote)

Anything new about ChatGPT this week (end of March 2023)? Not much. Only these 50 stories… ๐Ÿคฏ

๐Ÿ‘‰ Recommended: Free Download ChatGPT Prompting Cheat Sheet

Petition Against AI Research

Some big-time celebs (๐ŸคฉMusk, Wozniak, and more) have signed a petition๐Ÿ“ to put a hold on the development of AI systems stronger than GPT-4. I’m really curious to hear what other people think about this. On the one hand, I get where they’re coming from, but even if it did happen, would it really make any difference? I kinda doubt it, to be honest.

๐Ÿ‘‰ Link

Google Brain’s 2006 Concept

Google Brain had an incredible concept back in 2006! ๐Ÿคฏ You could chat with Google and use it to search for things and even pay for them. Just imagine if they had implemented this incredible idea back then! It’s mind-blowing to think about! ๐Ÿคฏ

๐Ÿ‘‰ Link

OpenAI Invests in Humanoid Robot

OpenAI has put their money into NEO, a humanoid robot from 1X. ๐Ÿค– They are confident it will have a great influence on the future of work. ChatGPT and robots could be arriving sooner than expected. Their goal is to construct robots with human-level dexterity. ๐Ÿค

๐Ÿ‘‰ Link, Link

ChatGPT: A Code Interpreter for Data Analysis

ChatGPT is an incredible code interpreter that can help you complete university assignments in no time! ๐Ÿคฉ It can scan databases and analyze the data, create visualizations, and even allow you to play with data using plain English! ๐Ÿ’ฏ It also supports file uploads and downloads. ๐Ÿ“ This would have been a lifesaver during my university days! ๐Ÿค”

๐Ÿ‘‰ Link

AI Comes to Webflow – Get Your Website Built!

Webflow is taking a leap forward with AI! Now you can quickly build components using Artificial Intelligence. ๐Ÿค– I’m especially excited about this since I use Webflow to design websites for people.

๐Ÿ‘‰ Link

ChatGPT Plugin: Your Personal Recipe and Shopping Assistant

ChatGPT Plugin ๐Ÿค– is your personal assistant to help you find the perfect restaurant, recommend delicious recipes, compile all the necessary ingredients, and even purchase them using Instacart! ๐Ÿ›’

๐Ÿ‘‰ Link

Expedia Plugin is the Best for Booking Flights ๐Ÿ›ซ๐Ÿ›ฌ

Expedia has outdone themselves with their new plugin โ€“ it’s already better than any website out there for booking flights! It can help you find flights, resorts, and activities to do! ๐Ÿ˜„

๐Ÿ‘‰ Link

Writing to Create with Plugins

The plugin speaks English plainly and simply. We’re at a stage now where if you know how to write, you can create amazing things with plugins! ๐Ÿ˜ƒ

๐Ÿ‘‰ Link

Unlock the Power of ChatGPT with the Retrieval Plugin

The Retrieval plugin provides ChatGPT with an incredible memory ๐Ÿคฏ! All you need to do is wear a microphone throughout the day, transcribe the audio, and give it to ChatGPT – it will remember all the information you said. With the Retrieval plugin, you can instantly recall anything you need! There are countless useful applications for this revolutionary technology. ๐Ÿš€

๐Ÿ‘‰ Link

ChadCode Plugin: Revolutionizing Coding!

The ChadCode plugin is revolutionizing coding! ๐Ÿคฉ It allows you to quickly search across your files and create GitHub issues in an instant. The possibilities are endless, and it truly changes coding for the better! ๐Ÿคฉ

๐Ÿ‘‰ Link

AI-Built iOS Game on App Store

The first GPT-4-generated ๐ŸŽฎ iOS game is now available on the App Store! ๐Ÿ“ฑ Mate had no experience with Swift; all code was completely AI-generated. It won’t be long until the App Store is flooded with AI-built games โ€“ it’s only a matter of time! ๐Ÿ•’

๐Ÿ‘‰ Link

Real-time Emotion Detection with AI – Endless Possibilities ๐Ÿค–๐Ÿ˜€๐Ÿ˜”?

Real-time emotion detection with AI is now possible! While I’m not entirely sure of its use cases, I can imagine people coming up with some crazy ideas for this technology. ๐Ÿค–๐Ÿ˜€๐Ÿ˜”

๐Ÿ‘‰ Link

Voice Chat with Llamas on Macbooks

Stay connected with your furry friends through voice chat on your Macbook Pro! ๐Ÿช We won’t have to type anymore, as we can just chat with Artificial Intelligence (AI) like Jarvis. ๐Ÿค– I wrote about this in my newsletter – no need to type out your messages anymore!

๐Ÿ‘‰ Link

Earthquake Imagery in Midjourney Subreddit

People in the Midjourney subreddit have been creating realistic-looking images of an earthquake that never occurred – ๐Ÿคฏ it’s unbelievable! ๐Ÿค”

๐Ÿ‘‰ Link

Mark Cuban Proposes Training AI Models with Liberal Arts Majors – ๐Ÿค”๐Ÿ’ก๐Ÿ’ฐ

Mark Cuban made an interesting comment suggesting that people with liberal arts or other non-engineering degrees could train AI models for specific use cases and tasks. This idea could potentially lead to significant financial gains if successful. What do you all think about this proposal? ๐Ÿค”๐Ÿ’ก๐Ÿ’ฐ

๐Ÿ‘‰ Link

Investing in AI: Emad Mostaque on GPT-4 Competitor

Emad Mostaque, CEO of Stability AI, estimates that building a GPT-4 competitor could cost anywhere between ๐Ÿ’ฐ200-300 million, provided the right people are in place. He also noted that it would take a minimum of 12 months to build an open-source GPT-4, and an immense amount of focus and hard work. ๐Ÿ’ช

๐Ÿ‘‰ Link, Link

The Impact of Midjourney on 3D Artists

A 3D artist opened up about how their job has been transformed since the release of Midjourney. ๐Ÿค” They can now create a character in only two to three days, compared to the weeks it would take before. Though they don’t necessarily love it, they even admit that Midjourney does a better job than they can do. ๐Ÿคฏ It’s sadly thought-provoking to read, as one can imagine how enjoyable it used to be for them to make art. This change is going to have a significant impact on many people in various creative fields. ๐Ÿค”

๐Ÿ‘‰ Link

Developer Builds iOS App in a Few Hours

This lad built an entire iOS app ๐Ÿ“ฑ, including payments ๐Ÿ’ฐ, in a few hours! ๐Ÿ‘ It was a relatively simple app, but had sooo many use cases, enabling him to get proof of concepts out in a single day. Crazy times ahead! ๐Ÿคฏ

๐Ÿ‘‰ Link

AI-Powered 3D Animations – The Future of Design? ๐Ÿค–๐ŸŽฌ๐Ÿ’ฐ

Someone is currently learning how to create 3D animations using AI. As this technology gets refined, I can imagine it becoming a streamlined process and making a lot of people some serious money. ๐Ÿค–๐ŸŽฌ๐Ÿ’ฐ

๐Ÿ‘‰ Link

New Innovation: Conversation Enhancing Earpiece

These folks are constructing an earpiece that will provide you with conversation topics and questions when speaking to someone. Just imagine taking this along to a job interview or a date ๐Ÿคฉ!

๐Ÿ‘‰ Link

AI-Powered Website Building is Here!

Have you ever dreamed of having a website that’s exactly what you want without having to do any of the work? ๐Ÿค” Well, now it’s possible with AI-powered website building! ๐Ÿคฉ This demo looks so amazing – website building is going to be so much easier and it’s crazy! ๐Ÿคฏ

๐Ÿ‘‰ Link

The Future of AI-Assisted Conversations

Put on your ๐Ÿค“ glasses and let AI take the reins! As technology advances, it’s becoming increasingly difficult to tell when someone is being assisted by AI in conversations. So get ready for a whole new world of AI-assisted conversations!

๐Ÿ‘‰ Link

Pope Drip: The Laughable Image

The Pope is drippin’ ๐Ÿ’ง๐Ÿคฃ I’ve been dying of laughter for days because I genuinely thought it was real the first time I saw it!

๐Ÿ‘‰ Link

AI Generators Replacing Models: Levi’s Diversity Move

Levi’s is striving for greater diversity in their advertising by turning to AI image generators instead of hiring diverse models. ๐Ÿค– It’s likely that this kind of technology will become more and more common, and could potentially spell trouble for models in the long run, as AI image generators are getting increasingly realistic. ๐Ÿ’ป

๐Ÿ‘‰ Link

AI Model Agency Creates 100% AI-Generated Images ๐Ÿค–

Someone created an AI model agency to create images of models wearing custom outfitsโ€”all 100% AI generated! ๐Ÿค–

๐Ÿ‘‰ Link

ChatGPT Launches Stylish Landing Page

ChatGPT has launched a sleek and stylish landing page, and it looks ๐Ÿ‘Œ! It’s sure to impress all visitors. ๐Ÿคฉ

๐Ÿ‘‰ Link

Investor Shares Hilarious AI Story

This investor recounts a funny story about how he spoke to a founder who took all of his advice and fed it to GPT-4, an advanced natural language processing algorithm. ๐Ÿคฏ They even used Eleven Labs’ AI-generated answers! ๐Ÿ˜† Hilarious stuff! ๐Ÿคฃ

๐Ÿ‘‰ Link

Artificial Intelligence & Blender ๐Ÿคฏ

Someone hooked up the GPT-4 artificial intelligence to Blender 3D animation and the results are unbelievable! ๐Ÿคฏ The combination of AI and 3D animation is pushing the boundaries of creativity.

๐Ÿ‘‰ Link

Kanye Raps Freestyle for Guy

This guy had the honor of getting Kanye West to rap one of his verses! ๐ŸŽ™๐Ÿ˜Ž

๐Ÿ‘‰ Link

๐ŸถGPT4 Saves the Day: A Dog’s Miraculous Recovery!๐Ÿถ

When doctors were unable to diagnose what was ailing the pup, GPT4 came to the rescue and proved to be spot-on with its suggested causes. Who would’ve thought it was possible?! It’s truly amazing!

๐Ÿ‘‰ Link

GPT-4 Learns at Lightning Speed

A research paper suggests that GPT-4 can improve its performance by up to 30% simply by having it consider โ€œwhy were you wrong.โ€ ๐Ÿค” Taking this feedback into account, the AI is capable of generating new prompts for itself, propelling the pace of its learning to lightning-fast speeds. ๐Ÿคฏ

๐Ÿ‘‰ Link

GPT-4 and Replit: Breaking Down the Technological Barrier

You can literally ask GPT-4 ๐Ÿค–for a plugin idea, have it code it, and then watch it go live on Replit! ๐Ÿ’ปIt’s gonna be so unbelievably easy to create new types of single-use apps soon, especially if you have a niche use-case. ๐Ÿค”And you can do this with practically no coding knowledge โ€“ the technological barrier to solving problems using code is vanishing before our eyes! ๐Ÿคฉ

๐Ÿ‘‰ Link

Open-Source AI Form Builder Coming Soon!

Say goodbye to tedious form-building by hand! ๐ŸคฉWe’re excited to announce that a new open-source AI form builder is coming soon! This state-of-the-art technology will make it easier and faster than ever to create forms. It’s gonna be pretty neat! ๐Ÿคฉ

๐Ÿ‘‰ Link

AI Videos That Look Real

Create entire videos of talking AI people: ๐Ÿค– โœจ When this technology gets better, we won’t be able to tell the difference between what’s real and what’s AI! ๐Ÿค”

๐Ÿ‘‰ Link

The Cityscape of Dreams ๐Ÿคฉ

Someone created a cityscape using AI and then asked Chatbot GPT-3 to write the code to port it into virtual reality. From words to wondrous virtual worlds!

๐Ÿ‘‰ Link

The Power of GPT-4: Writing an Entire Book ๐Ÿ“–

Someone managed to get GPT-4 to write an entire book โ€“ and while it may not be amazing, it’s still quite impressive! With the advent of helpful plugins and progress to GPT-5 and GPT-6, this accomplishment will likely become even easier and of higher quality in the future.

๐Ÿ‘‰ Link

Request an App with a Single Prompt – The Future of App Development? ๐Ÿ“ฑ๐Ÿš€

Have you heard about Replit’s new software that allows you to literally request an app and have it built for you? It’s unbelievable! As AI continues to improve, we may see whole functioning apps being built with a single prompt. This could be world-changing! ๐Ÿ“ฑ๐Ÿš€

๐Ÿ‘‰ Link

๐Ÿคฉ OSS AI: Langchain’s Open-Source Achievements ๐Ÿคฉ

Langchain is really knocking it out of the park with their open-source AI plugins. I’m so excited to see what the future holds!

๐Ÿ‘‰ Link

๐Ÿ”จBuilding with Langchain Just Got Easier!๐Ÿ’ช

Langchain makes it easy and powerful to develop on their platform. Whether you’re a beginner or an experienced engineer, you’ll find that building with Langchain is fast, reliable, and easy. So, why not give it a try? ๐Ÿค”

๐Ÿ‘‰ Link

Create 3D Scenes with Text in Real Time

๐Ÿ’ป Create stunning 3D scenes in no time with the power of text! With this revolutionary editing technique, making complex 3D scenes is easier than ever before. ๐Ÿคฉ

๐Ÿ‘‰ Link

GPT-4’s Emotional Genius: An Entrepreneur’s Opportunity for Fortune

GPT-4 is proving to be incredibly adept at recognizing the many nuances of human emotions and states of mind โ€“ it’s so effective that it can even help to resolve conflicts between couples ๐Ÿค. Reports have been cropping up about its effectiveness as a therapeutic tool – good, ethical or otherwise โ€“ and there is undeniably great potential to help many people without breaking the bank. All that’s needed now is for an ambitious entrepreneur to seize the opportunity and create a successful business around GPT-4 to make a fortune ๐Ÿ’ฐ.

๐Ÿ‘‰ Link

GPT-4: The AI Emotion Wizard ๐Ÿค–

You can use plugins to process video clips, so many websites instantly becoming obsolete

๐Ÿ‘‰ Link, Link

Writing Plugins with ChatGPT

Writing plugins for ChatGPT is a breeze! Just describe the API you want in plain English, and ChatGPT will take care of the rest ๐Ÿค–

๐Ÿ‘‰ Link, Link

Replacing Siri with ChatGPT – A Clever iOS Shortcut ๐Ÿ”๐Ÿค–๐Ÿ“ฑ

Check out this clever lad who created an iOS shortcut that replaces Siri with ChatGPT! With this shortcut, users can interact with ChatGPT instead of Siri, adding a unique twist to their virtual assistant experience. ๐Ÿ”๐Ÿค–๐Ÿ“ฑ

๐Ÿ‘‰ Link

We (Finxter) also have an interesting article (+video) on the topic:

๐Ÿ‘ฉโ€๐Ÿ’ป Recommended: Create a Siri Alternative with ChatGPT (No Code!)

Integrate Chatbot and Zapier for Endless Possibilities ๐Ÿค–โœ…

Zapier allows you to integrate more than 5000 apps, turning your possibilities into an infinite playground. By combining Chatbot and Zapier, you can create an array of unique use cases that can be further enhanced with other apps. ๐Ÿคฉ

๐Ÿ‘‰ Link

๐Ÿ‘€๐Ÿค” A Glimpse of AGI?

We’ve likely already seen the paper discussing how GPT-4 displays signs of artificial general intelligence (AGI), but here’s a link just in case. It states, “We believe that it could reasonably be viewed as an early (yet still incomplete) version of an AGI system.”

๐Ÿ‘‰ Link

Also check out our full guide on AGI:

๐Ÿ‘ฉโ€๐Ÿ’ป Recommended: Artificial General Intelligence (AGI) – Is ChatGPT It?

๐ŸคฏMind-blowing AI Agent Creates Subtasks and Solutions๐Ÿคฏ

This guy made an AI agent that can break down a task into sub-tasks and come up with solutions for each part. It’s totally insane to watch it in action – I highly suggest catching the clip below. Here’s the link to the “paper” and his summary of how it all works.

๐Ÿ‘‰ Link, Link

Make Remote Job Interviews a Breeze with This Clever Tool! ๐Ÿค”โœจ

There’s now an awesome tool that can help you ace remote job interviews with ease. It listens in to the interview and provides you with suggestions on what to say – making those nerve-wracking virtual interviews a piece of cake! ๐Ÿฐ

๐Ÿ‘‰ Link

๐Ÿ“ฑPerplexity Launches New Mobile App: A ChatGPT Alternative for Instant Answers with Cited Sources ๐Ÿ”Ž

Perplexity has just released their new mobile app โ€“ a cutting-edge ChatGPT alternative featuring instant answers and cited sources. Get the app now and access on-the-go answers in a flash! ๐Ÿ’ซ

๐Ÿ‘‰ Link


Download your ChatGPT cheat sheet here:

๐Ÿ‘‰ Recommended: Free Download ChatGPT Prompting Cheat Sheet

These news items were collected from this Reddit thread. Shoutout to /u/lostlifon!

Posted on Leave a comment

How I Built an English Dictionary App with Django

5/5 – (1 vote)

As we all know, Django is a Python framework used for building complex web applications. Yet, it can also be used for building simple ones. In this tutorial, I’m going to show you ๐Ÿ“– how I built an English dictionary app, a simple Django project for beginners.

It takes time for a beginner to fully understand how Django works. But the key is consistency. If you keep building projects, you will gradually know enough to be dangerous with Django.

๐Ÿ‘‡ Scroll to the end to see the full code on GitHub!

A Dictionary App? ๐Ÿ“–

A dictionary is an application used to get a particular word’s meaning. No matter how proficient we are in English, some words are far beyond our understanding. There are also words we may not know how to pronounce efficiently, especially those originating from a different language.

Furthermore, we may want to know a synonym or antonym of a given word. This is where a dictionary comes in handy. With a dictionary, we get to know not only the meaning of a word but how it is pronounced, what parts of speech it belongs to, and how it is used in a sentence. Students, no doubt, appreciate the importance of having a dictionary.

How Will We Get The Data?

How will we build this dictionary app so that when users search for a particular word, they get the meaning?

We have two options. Either we use PyDictionary, a Python module and an API that scrapes an online dictionary website or we perform the web scraping ourselves. None of these methods comes without a drawback.

๐Ÿ’ก Recommended: Is Web Scraping Legal?

The drawback is the challenge that comes with web scraping. Many websites sometimes change their HTML structures to prevent people or bots from accessing their content. So, if an API is not actively maintained, it can quickly become useless. This is the case with PyDictionary. Therefore, we are going to perform web scraping.

Doing so will undoubtedly gain some valuable experience in web scraping, a very broad concept in Python programming. Still, we are at the mercy of website owners. They can change the HTML structures of their websites unexpectedly.

Prerequisites

This tutorial assumes you are familiar with Python, HTML, and Bootstrap. If not, please you are required to have at least a basic knowledge before attempting this project. Basic knowledge of Django, though not required, can speed up the learning process.

Getting started

Create a new folder for this project. Then you do the following:

  1. Create a virtual environment
    python3 -m venv .venv
  2. Activate the virtual environment
    source .venv/bin/activate
  3. Install the required libraries in the virtual environment
    pip install django tzdata requests bs4
  4. Create a requirements.txt file to keep a record of the module versions.
    pip freeze > requirements.txt

Creating Django Project and Application

i. Creating the project
django-admin startproject project .
This creates a folder called project in the current directory.

ii. Creating the application
python3 manage.py startapp dictionary
The manage.py file is an executable file used to run Django commands

iii. Applying migrations
python3 manage.py migrate

iv. Checking to see if the installation was successful
python3 mange.py runserver

Once you see the above image, you are good to go.

Registering the App

  1. In settings.py file
    This step is important whenever an app is created. Navigate to the project folder. Open the settings.py file and scroll down to the INSTALLED_APPS section.
 # Application definition INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', # custom app 'dictionary', ]

We have registered the app in the settings.py file. The settings.py file is used to configure the whole project.

  1. In the urls.py file
    Open the urls.py file in the project folder and add this:
 from django.contrib import admin from django.urls import path, include urlpatterns = [ path('admin/', admin.site.urls), path('', include('dictionary.urls')), ]

We have registered the app-level URL. Let’s now create it.

Creating the App URL

This will be done inside the dictionary folder. Create a urls.py file inside the folder and add this:

from django.urls import path
from . import views urlpatterns = [ path('', views.homeView, name='home'), path('search', views.searchView, name='search'),
]

from . import views” tells Django to import the views.py file residing in the dictionary folder.

The empty string indicates the home page URL which is http://127.0.0.1:8000/ if you are using the local server.

This is where users will be directed when the web page is opened.

For the 'search' string, the URL will be http://127.0.0.1:8000/search. We will be creating two functions in the views.py file as indicated.

Notice the name argument in the path() function, this is another way to refer to the URLs in the template files without using the exact URLs.

Creating Views

In this file, we are going to perform the web scraping we mentioned earlier. The first function, the homeView() is fairly simple. We just render the index.html page once the app is opened.

from django.shortcuts import render
import requests
from bs4 import BeautifulSoup as bs # Create your views here. def homeView(request): return render(request, 'index.html')

But the searchView() function is a little bit complex. We want to display three things when a user searches for the meaning of a word: meaning, synonyms, and antonyms.

So, we perform web scraping on two online dictionary websites. The first will display the meaning and the second will display the synonyms and antonyms.

def searchView(request): word = request.GET['search'] response = requests.get(f'https://dictionary.com/browse/{word}') response2 = requests.get(f'https://thesaurus.com/browse/{word}') if response: soup_1 = bs(response.text, 'html.parser') meaning = soup_1.find_all('div', {'value': '1'}) meaning_1 = meaning[0].getText() else: word = f'Sorry, we couldn\'t find your word {word} in our records.' meaning = '' meaning_ = '' if response2: soup_2 = bs(response2.text, 'html.parser') synonyms = soup_2.find_all('a', {'class': 'css-1kg1yv8 eh475bn0'}) synonym_list = [] for i in range(len(synonyms)): synonym_list.append(synonyms[i].text.strip()) antonyms = soup_2.find_all('a', {'class': 'css-15bafsg eh475bn0'}) antonym_list = [] for i in range(len(antonyms)): antonym_list.append(antonyms[i].text.strip()) else: synonym_list = '' antonym_list = '' results = { 'word': word, 'meaning': meaning_1, 'synonyms': synonym_list, 'antonyms': antonym_list } return render(request, 'search.html', results)

We import the requests module which uses the get() method to scrape the contents of the two websites.

๐Ÿ’ก Recommended: My First Python Get Request

The result is a cruel HTML code staring at you. BeautifulSoup, invaluable for web scraping does its job well to pull the data out of the HTML content. This now makes it possible to search the parsed data.

For our first search using the find_all() method from BeautifulSoup, we want a text wrapped in a div tag with the value 1. This is where the website owners kept the meaning of a particular word on the dictionary.com website.

So, we use the getText() method to get the text.

The second and third searches look similar to the first but instead of a div, we search in a tag. The words were kept in a tag to make it easy for visitors to be redirected to that particular word if they want to find the definition.

Instead of searching for a value, we search for a CSS class. We then append the results to their respective variables. If you are new to web scraping, you may wonder how we know where those particular words reside.

The answer is found in a browser’s developer tools, preferably Chrome Developer Tools. This is the reason I suggest familiarizing yourself with HTML before attempting this project.

Finally, we render the results on the search.html page. Notice the else statements. This is run if the word is not found on the website. Let’s now create the HTML files.

Creating Templates

Create a folder named templates in the current directory (not in the project or app folder). Then go to the settings.py file to let Django know of this development. In the file, import the os module. Then scroll to the TEMPLATES section and add this:

TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [os.path.join(BASE_DIR, 'templates')], # add these 'APP_DIRS': True, 'OPTIONS': { 'context_processors': [ 'django.template.context_processors.debug', 'django.template.context_processors.request', 'django.contrib.auth.context_processors.auth', 'django.contrib.messages.context_processors.messages', ], }, },
]

Then create three files in the templates folder:

  • base.html,
  • index.html, and
  • search.html.

The main HTML files will inherit from the base.html file. Open the base.html file and add the following:

<!DOCTYPE html>
<html lang="en"> <head> <meta charset="UTF-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Dictionary App</title> <!-- CSS only --> <!-- we are getting bootstrap5 from the CDN --> <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.2.0-beta1/dist/css/bootstrap.min.css" rel="stylesheet">
</head> <body> <div class="container mt-4"> <div class="row"> <div class="mt-4 p-5 bg-success text-white rounded mb-3"> <h1>Django English Dictionary</h1> </div> <div class="col-md-12"> {% block content %} <!-- here we will inject the content of every page that inherits from the base page --> {% endblock %} </div> </div> </div>
</body> </html>

Then, in the index.html add the following:

<!-- the index page is inheriting from the base page -->
<!-- the extends tags are used for inheriting from the base page -->
{% extends 'base.html' %} <!-- the block content tags for containing content of the page -->
{% block content %} <form action="search"> <div class="input-group"> <input type="text" required class="form-control" name="search" placeholder="Search your favorite word......."> <div class="input-group-append"> <button class="btn btn-success" type="submit"> Search </button> </div> </div> </form> {% endblock %}

Recall in the searchView() function, we send a GET request to get the word input by our user from a form that bears the name 'search.' Can you now see it in the form?

There will be a problem if you use it otherwise. Finally, add the following to the search.html file.

<!-- SEARCH.HTML -->
{% extends 'base.html' %}
{% block content %} <div> <h2 align="center"> {{ word | title }} </h2> <br> <p> <b>Meaning: </b>{{meaning}} </p> <br> <p> <b>Synonyms: </b> {{ synonyms }}
</p>
<br>
<p> <b>Antonyms: </b> {{ antonyms }} </p> <p><a href="{% url 'home' %}>Home</a></p> </div>
{% endblock %}

We use Django templating language to render the results of the searchView() function to the HTML. Alright, we are done. Run the server once again and you should see something similar to the images below.

That is the index.html web page. Once you search for a word, the search.html page is displayed as you can see below.

Do you see how each of the pages inherits everything in the base.html file?

Conclusion

We have successfully come to the end of this project. I strongly believe you have learned a lot of things you can apply to your projects. If certain things arenโ€™t clear you may wish to read other project articles.

The full code can be found on my GitHub page https://github.com/finxter/django_dictionary. Have a wonderful day.

๐Ÿ’ก Recommended: How I Built a Weather App Using Three Python Frameworks

Posted on Leave a comment

PHP QR Code Generator with phpqrcode Library

by Vincy. Last modified on March 28th, 2023.

QR code (Quick Response code) is a machine-readable pictorial format containing black and white squares. It is used for storing information like URLs, product ID, etc. It is a type of matrix barcode or a two-dimensional barcode.

It is a convenient form of storing and retrieving simple data and has become even more popular with the advent of smartphones. The camera in the smartphone can act as a reader and read the QR code and help to decipher the data stored in it.

This article gives many examples if you want a solution to generate QR codes in PHP. There are a lot of PHP libraries available to generate QR codes. This article uses the PHP QR code library.

1. Quick example

This quick example returns the QR code to the browser in one line. It produces the output as a PNG stream.

<?php
require_once __DIR__ . '/vendor/phpqrcode/qrlib.php'; // Displays QR Code image to the browser
QRcode::png('PHP QR Code :)');

Installing PHP QR code library

Download the latest library version and extract it into your application vendor folder. The source code downloadable in this article has the library.

All the examples in this article have the code to include the suitable library file to use its feature.

In a previous article, we have seen code for a PHP QR code generator using the tc-lib-barcode library.

qr code data

2. Display the QR code using an HTML image

To display the QR code using an HTML image tag, link the HTML image source to the PHP file that returns the QR code PNG data.

The generate.php file returns the QR code in the below code using the PHP QrCode library. The HTML image refers to this file to show the QR code in the browser.

show-qr-code-in-HTML-img/generate.php

<?php
require_once __DIR__ . '/vendor/phpqrcode/qrlib.php'; // Displays QR Code image to the browser
QRcode::png('PHP QR Code :)');
<?php
require_once __DIR__ . '/../vendor/phpqrcode/qrlib.php'; // outputs image as PNG that can be refered to a HTML image 'src'
QRcode::png('PHP QR Code :)');
?>

show-qr-code-in-HTML-img/view.php

<img src="generate.php" />

2. Passing arguments to the QR code generator

Passing parameters to a QR code generator helps to perform dynamic processing about the parameter.

For example, we can pass a contact id to retrieve contact information to bundle it with the QR code output.

This example shows how to send parameters and process them in the QR generator.

The view.php file prepares the QR code parameter in PHP. Then, it sends it to the generate.php in query. This URL with the QR code parameter is specified to an HTML image source.

show-qr-code-in-html-img/view.php

<?php
// initialize PHP parameter to send to the QR code generator
$QRParameter = 1234;
?>
<img src="generate.php?id=<?php echo $QRParameter; ?>" />

In this generate.php file, it does simple manipulation to the passed argument. It prefixes a string with the GET parameter received and bundles the manipulated line to the QR code PNG.

show-qr-code-in-html-img/generate.php

<?php
if (empty($_GET['id'])) { echo "<b>ERROR:</b> Bad request. Required parameters are missing."; exit;
} else { require_once __DIR__ . '/../vendor/phpqrcode/qrlib.php'; $inputString = $_GET['id']; // Do not return anything to the browser ob_start("callback"); // Process the input string $codeText = 'DEMO - ' . $inputString; // end of processing $debugLog = ob_get_contents(); ob_end_clean(); // outputs QR code as a PNG data QRcode::png($codeText);
}
?>

3. Save the QR code on the server

This example saves the generated QR code on the server.

It defines the QR code data and the png file name suffix in an array. Then, it uses them while creating the target to save the QR code.

save-qr-code-in-server.php

<?php
require_once __DIR__ . '/vendor/phpqrcode/qrlib.php'; // how to configure silent zone (frame) size
$qrContent = array('content' => 'Contact information', 'slug' => 'contact-info'); $target = "uploads/qr-code-dir/";
$filePath = $target . 'ouput-qr-code-' . $qrContent['slug'] . '.png'; if (!file_exists($filePath)) { QRcode::png($qrContent['content'], $filePath);
}
?>
<img src="<?php echo $filePath; ?>" />

4. Configure QR code ECC Level, Zoom factor, and Frame size

The PHP QRCode Library defines constants for different ECC levels, Zoom factor, and Frame size. These factors are used for the following purposes when generating a QR code.

This program creates QR codes in L, M, Q, and H levels with appropriate QR constants.

  • ECC level is the allowed percentage of damage without affecting reading data.
  • Zoom factor is the allowed resolution that can be changed based on the use cases.
  • Silent zone Frame size โ€“ The silent or quiet zone frame size varies based on different matrices. Setting the QR code above or equal to 4 blocks is recommended.

qr-code-ecc-level.php

<?php
require_once __DIR__ . '/vendor/phpqrcode/qrlib.php';
require_once __DIR__ . '/vendor/phpqrcode/qrconst.php'; $qrContent = 'Demo data to bundle into a QR code'; $target = "uploads/ecc-level/"; // generating QR code in the 4 ECC level
QRcode::png($qrContent, $target . 'l.png', QR_ECLEVEL_L);
QRcode::png($qrContent, $target . 'm.png', QR_ECLEVEL_M);
QRcode::png($qrContent, $target . 'q.png', QR_ECLEVEL_Q);
QRcode::png($qrContent, $target . 'h.png', QR_ECLEVEL_H); ?>
<img src="<?php echo $target; ?>l.png" />
<img src="<?php echo $target; ?>m.png" />
<img src="<?php echo $target; ?>q.png" />
<img src="<?php echo $target; ?>h.png" />

This program adds the zoom factor 1 to 4 with the QR_ECLEVEL_L ECC constant.

qr-code-pixel-zoom-factor.php

<?php
require_once __DIR__ . '/vendor/phpqrcode/qrlib.php'; $qrContent = 'Demo data to bundle into a QR code with zoom factor'; $target = "uploads/pixel-zoom-qr-code/"; // generating QR code with 4 ECC level and zoom factor
QRcode::png($qrContent, $target . 'l_1.png', QR_ECLEVEL_L, 1);
QRcode::png($qrContent, $target . 'l_2.png', QR_ECLEVEL_L, 2);
QRcode::png($qrContent, $target . 'l_3.png', QR_ECLEVEL_L, 3);
QRcode::png($qrContent, $target . 'l_4.png', QR_ECLEVEL_L, 4); ?>
<img src="<?php echo $target; ?>l_1.png" />
<img src="<?php echo $target; ?>l_2.png" />
<img src="<?php echo $target; ?>l_3.png" />
<img src="<?php echo $target; ?>l_4.png" />

This program creates QR codes with all these factors ECC, Zoom, and Frame constants of the library.

silent-zone-frame-size.php

<?php
require_once __DIR__ . '/vendor/phpqrcode/qrlib.php'; $qrContent = 'Demo data to bundle into a QR code with frame size'; $target = "uploads/pixel-zoom-qr-code/"; // generating // frame config values below 4 are not recommended !!!
QRcode::png($qrContent, $target . 'l_3_4.png', QR_ECLEVEL_L, 3, 4);
QRcode::png($qrContent, $target . 'l_3_6.png', QR_ECLEVEL_L, 3, 6);
QRcode::png($qrContent, $target . 'l_3_10.png', QR_ECLEVEL_L, 3, 10); // displaying
?>
<img src="<?php echo $target; ?>l_3_4.png" />
<img src="<?php echo $target; ?>l_3_6.png" />
<img src="<?php echo $target; ?>l_3_10.png" />

5. Add phone, email, and contact info to a QR code

This section has PHP examples to create QR codes to attach contact information.  It prepares the QR code content with the โ€œtel:โ€. โ€œsms:โ€ and โ€œmail:โ€ links and attaches it to the QR code.

add-phone-to-call.php

<?php
require_once __DIR__ . '/vendor/phpqrcode/qrlib.php';
$target = "uploads/qr-code-phone/";
$phone = '(091)700-001-710';
// attache phone to call
$qrContent = 'tel:' . $phone;
QRcode::png($qrContent, $target . 'phone-to-call.png', QR_ECLEVEL_L, 3);
?>
<img src="<?php echo $target; ?>phone-to-call.png" /> 

add-phone-to-text.php

<?php
require_once __DIR__ . '/vendor/phpqrcode/qrlib.php';
$target = "uploads/qr-code-phone/";
$phone = '(091)700-001-710';
// Attach the phone to text
$qrContent = 'sms:' . $phone;
// generating
QRcode::png($qrContent, $target. 'phone-to-text.png', QR_ECLEVEL_L, 3);
?>
<img src="<?php echo $target; ?>phone-to-text.png" />

Attaching an email adds the mail subject and body as part of the mail recipient data. But the subject and the body parameters are optional.

add-recipient-to-send-mail.php

<?php
require_once __DIR__ . '/vendor/phpqrcode/qrlib.php';
$target = "uploads/qr-code-phone/";
$recipient = 'vincy@example.com';
$mailSubject = 'Enquiry';
$mailBody = 'Post enquiry content';
// Prepare QR content with email recipient, subject and body
$qrContent = 'mailto:' . $recipient . '?subject=' . urlencode($mailSubject) . '&body=' . urlencode($mailBody);
// Attach maileto link to the QRCode
QRcode::png($qrContent, $target. 'mail.png', QR_ECLEVEL_L, 3);
?>
<img src="<?php echo $target; ?>mail.png" /> 

This QR code example creates a v-card to bundle with the QR code. It includes basic details with the v-card.

This library allows adding more details to the QR code. For example, it can attach a contact avatar to a QR code.

In a previous article, we have seen how to generate and download a v-card for contact information.

save-vcard-to-qr-code.php

<?php
require_once __DIR__ . '/vendor/phpqrcode/qrlib.php';
$target = "uploads/qr-code-phone/";
// Contact details
$name = 'Example1';
$phone = '(091)700-001-711';
// QR code content with VACARD
$qrCode = 'BEGIN:VCARD' . "\n";
$qrCode .= 'FN:' . $name . "\n";
$qrCode .= 'TEL;WORK;VOICE:' . $phone . "\n";
$qrCode .= 'END:VCARD';
// Attaching VCARD to QR code
QRcode::png($qrCode, $target. 'vcard-qr-code.png', QR_ECLEVEL_L, 3);
?>
<img src="<?php echo $target; ?>vcard-qr-code.png" /> 

Download

โ†‘ Back to Top

Posted on Leave a comment

F-String Python Hex, Oct, and Bin: Efficient Number Conversions

5/5 – (1 vote)

As a Python developer, I’ve always been fascinated by the simplicity and versatility of the language. Python has always been my go-to language for all my programming needs, from its clean syntax to the vast array of libraries available. I recently had to work on a project requiring me to convert numbers to their hexadecimal, octal, and binary representations. While there are several ways to do this in Python, I discovered the f-string Python Hex, Oct, and Bin methods, which turned out to be the most efficient and straightforward approach. In this blog post, I’ll share my personal experience with this method and show you how to use it to convert numbers efficiently.


A Short Overview (Promised) ๐Ÿ‘‡

Python’s f-strings, also known as “formatted string literals”, have been introduced in Python 3.6 and offer a more efficient and readable way to format strings. They improve upon the older string formatting methods, such as using %-formatting and the str.format() method.

One of the key advantages of f-strings is their ability to handle various numeric representations, such as hexadecimal (hex), octal (oct), and binary (bin).

Handling hex, oct, and bin values in Python with f-strings is quite simple, thanks to the built-in support for these number systems. These can easily be incorporated into f-strings by using specific format specifiers within curly braces that contain the expressions to be evaluated and formatted at runtime. This allows you to seamlessly integrate hexadecimal, octal, and binary values into their strings without resorting to clumsier methods or additional function calls.

When working with f-strings in Python, you can use {variable:x} for hex, {variable:o} for oct, and {variable:b} for bin.

F-String Basics

One powerful feature of f-strings is their ability to format numbers in different bases, such as hexadecimal (hex), octal (oct), and binary (bin). To represent numbers in these formats, you can use the appropriate format specifier:

  • Hexadecimal: {x:X}
  • Octal: {x:o}
  • Binary: {x:b}

For example, to convert an integer into its hexadecimal representation, you can use the following f-string:

x = 255
hex_string = f"x in hex is: {x:X}"
print(hex_string) # Output: "x in hex is: FF"

Similarly, for octal and binary representations, you can use the respective format specifiers within the f-string:

x = 255
oct_string = f"x in oct is: {x:o}"
bin_string = f"x in bin is: {x:b}"
print(oct_string) # Output: "x in oct is: 377"
print(bin_string) # Output: "x in bin is: 11111111"

Using f-strings, you can create more readable and efficient code when working with different number systems in Python ๐Ÿ”ฅ.

๐Ÿ’ก Recommended: 7 Tips to Clean Code

Formatting Numerical Values with F-Strings

To format a number in hexadecimal with f-strings, you can use the format specifier {variable:x}. If you want zero padding, use the format specifier {variable:0Nx}, where N is the desired number of digit characters.

x = 255
hex_string = f"0x{value:02x}"
# Output: "0xff"

Similarly, to format a number in octal representation, use the format specifier {variable:o}.

y = 63
octal_string = f"0o{y:03o}"
# Output: "0o077"

For binary representation, you can use the format specifier {variable:b}.

z = 10
binary_string = f"0b{z:04b}"
# Output: "0b1010"

๐Ÿ’ก In addition to numerical formats, you can also use other format specifiers like:

  • Decimal: {variable:d}
  • Floating-point: {variable:.Nf} (where N is the number of decimal places to round)
  • Percentage: {variable:.N%}

Hexadecimal Representation

You can easily represent numbers in hexadecimal notation using f-strings in Python. Hexadecimal is a base-16 numeric system that uses sixteen distinct symbols โ€“ 0-9 representing zero to nine and A-F for ten to fifteen. It is widely used in computer programming and digital electronics.

You can use the format specifier within curly braces to convert a number to its hexadecimal representation using f-strings. For example:

number = 255
hex_num = f"{number:x}"
print(hex_num) # Output: "ff"

The same can be achieved using the format() function:

number = 255
hex_num = format(number, 'x')
print(hex_num) # Output: "ff"

You can also include the 0x prefix by using the # flag in the format specifier:

number = 255
hex_num = f"{number:#x}"
print(hex_num) # Output: "0xff"

Hexadecimal representation can be helpful in various situations, such as when working with colors in CSS or addressing memory locations in computer systems. ๐Ÿ–ฅ ๐ŸŽจ

Octal Representation

In Python, working with octal representations is smooth and straightforward thanks to built-in functions and f-strings. An octal number system has a base of 8, which means it uses eight symbols: 0, 1, 2, 3, 4, 5, 6, and 7. Converting between decimal and octal values can be accomplished with ease.

๐Ÿ’ก Recommended: Python Conversions: Decimal + Binary + Octal + Hex

YouTube Video

To obtain the octal representation of an integer in Python, simply use the oct() function. This function takes an integer as input and returns its octal representation as a string:

octal_value = oct(42) # 42 in decimal equals '0o52' in octal

With f-strings, you can elegantly include octal values directly in your strings. To do this, use the format specifier {value:#o} within an f-string:

number = 42
formatted_string = f"The octal representation of {number} is {number:#o}"
# Output: "The octal representation of 42 is 0o52"

Here are some essential points to remember when working with octal representations in Python:

  • Octal literals can be defined by adding a 0o prefix to the number: octal_number = 0o52.
  • Using arithmetic operations on octal numbers works the same as on decimal numbers: result = 0o52 + 0o10.
  • Convert between integer and octal string representations with the int() and oct() functions, respectively.

Binary Representation

In Python, f-strings are a convenient option for formatting strings, which can be used for various purposes like binary, octal, and hexadecimal representations. In this section, we’ll focus on the binary representation using f-strings. ๐Ÿ˜„

To display a binary value of an integer using f-strings, you can use the formatting specifier b followed by the variable you want to convert inside the curly braces. The syntax looks like this: f"{variable:b}".

As an example, let’s say we want to display the binary representation of the number 5:

number = 5
binary_representation = f"{number:b}"
print(binary_representation) # Output: 101

Now, you can use a loop to display binary representations for a range of numbers. Let’s say we want to print binary values for numbers 0 to 5:

for i in range(6): print(f"{i} in binary is {i:08b}")

This will output the following:

0 in binary is 00000000
1 in binary is 00000001
2 in binary is 00000010
3 in binary is 00000011
4 in binary is 00000100
5 in binary is 00000101

Note the use of 08b within the f-string. The number 8 indicates the minimum width, and leading zeros are used to fill any remaining space. This ensures that binary values are displayed with a consistent width, making the output easier to read. ๐Ÿค“

Conversion Functions

This section will focus on Python’s f-string capabilities for converting between hexadecimal, octal, and binary number systems. The primary goal is to make these conversions as simple as possible using f-string syntax.

Int to Hex, Oct, and Bin

When working with integers, you can easily convert them to their corresponding hexadecimal, octal, and binary representations using f-string formatting. Here are some examples:

hex_number = 255
oct_number = 127
bin_number = 101 hex_string = f"{hex_number:x}"
oct_string = f"{oct_number:o}"
bin_string = f"{bin_number:b}"

This simple f-string syntax allows you to convert integers to their corresponding representation within an f-string using the 'x', 'o', and 'b' format specifiers.

String to Hex, Oct, and Bin

For converting strings to their hexadecimal, octal, and binary representations, you can use the following approach:

import binascii text = "Hello, World!" # Convert the string to bytes
text_bytes = text.encode('utf-8') # Use binascii to convert bytes to hex, oct, and bin
hex_string = binascii.hexlify(text_bytes).decode('utf-8')
oct_string = "".join([f"{char:o}" for char in text_bytes])
bin_string = "".join([f"{char:08b}" for char in text_bytes])

In this example, we first convert the string to bytes using the 'utf-8' encoding. Then we utilize the binascii module to convert bytes to their hexadecimal representation. We use list comprehension and f-string formatting for octal and binary conversions to achieve the same result.

Incorporating f-strings allows you to conveniently and efficiently perform conversions between various number systems in Python. This technique can be particularly beneficial when dealing with data representation and manipulation tasks. ๐Ÿ˜Š

Formatting Specifiers and F-Strings

The formatted string literals allow you to embed expressions inside the string, which are evaluated and formatted using the __format__ protocol.

Formatting numbers in hex, oct, and bin is quite easy with f-strings. Here are some examples:

  • Hexadecimal: f"{number:x}"
  • Octal: f"{number:o}"
  • Binary: f"{number:b}"

You have the option to add formatting specifiers and padding to your f-Strings. For instance, you can center the output and add zero-padding:

f" {data:^14s}" .format(f" {data:#04x}")

This snippet first converts the data to hexadecimal using {data:#04x} and then centers the output with {data:^14s} (from Stack Overflow).

Here’s a brief table that demonstrates how to format numbers using f-Strings:

Type Example Output
Hexadecimal f"{15:x}" f
Octal f"{15:o}" 17
Binary f"{15:b}" 1111

Utilizing f-Strings and various formatting specifiers can help you efficiently manage complex string formatting tasks in your Python projects ๐Ÿ˜ƒ.


To keep boosting your Python skills and stay on track with the emerging technologies of the exponential age (e.g., ChatGPT), check out our free cheat sheets and email academy here:

Posted on Leave a comment

How to Correctly Write a Raw Multiline String in Python: Essential Tips

5/5 – (1 vote)

Python provides an effective way of handling multiline strings, which you might have encountered when working with lengthy text or dealing with code that spans multiple lines. Understanding how to correctly write a raw multiline string in Python can be essential for maintaining well-structured and easily readable code.

Ordinarily, we express strings in Python using single or double quotes.

โœ… Recommended: Python Strings Made Easy

However, when it comes to multiline strings, Python offers a special syntax for defining these types of text. To create a multiline string, you can use triple quotes, either single or double, at the beginning and end of your string.

To correctly write a raw multiline string in Python, use the letter “r” before your opening triple quotes while enclosing your string with triple quotes. For example: r'''This is a raw\n Multiline String'''.

This denotes a raw string and preserves special characters such as backslashes (used for escape sequences) without interpreting them as part of the string. Doing so lets you easily and efficiently handle long strings spanning multiple lines in your Python code.

Understanding Raw Strings

In Python, raw strings are a convenient way to represent strings literally, without processing escape characters. This can be particularly useful when working with regular expressions or dealing with file system paths. To create a raw string, simply prefix the string literal with an r or R character.

For example, a regular string containing a backslash (such as in a file path) would need to be escaped:

normal_string = 'C:\\Users\\John\\Documents'

With raw strings, you don’t need to escape the backslashes:

raw_string = r'C:\Users\John\Documents'

Both of these variables will hold the same string value.

When it comes to creating raw multiline strings, you can use triple quotes """ or ''' combined with the raw string prefix to achieve the desired result. Here’s an example:

raw_multiline_string = r"""This is a
raw multiline string
with backslashes \t and \n
that are not escaped."""

This string will preserve the backslashes and newlines as they appear between the triple quotes.

It is important to note that raw strings cannot end with an odd number of backslashes, as the final backslash would escape the final quote character:

# This will raise a SyntaxError
invalid_raw_string = r"This is not valid\"

To deal with this limitation, you can concatenate a regular string with the final backslash:

valid_raw_string = r"This is valid" + "\\"

Multiline Strings

In Python, multiline strings are created using triple quotes, either three single quotes (''') or three double quotes ("""). This allows you to include quotes, tabs, and newlines within the string without using escape characters. Here is an example of a multiline string:

multiline_string = """This is a
multiline string in Python
with newlines, tabs, and "quotes"."""

If you want to create a raw multiline string, you’ll need to use a different approach, as the r prefix only works for single-line strings. One way to achieve this is by combining raw strings and parentheses, adding an r prefix to each part of the string. This will preserve the string’s escape characters:

raw_multiline_string = (r"on\e" r"\\tw\\o")

Keep in mind that when using parentheses, the line break will not be included in the string. You can manually add a line break using the \n escape character in the appropriate location like this:

raw_multiline_string_with_linebreak = (r"on\e" r"\n" r"\\tw\\o")

This method allows you to create raw multiline strings while preserving the escape characters and maintaining readability in your Python code.

๐Ÿ’ก Remember: it’s essential to use the r prefix for each part of the string to ensure it’s treated as a raw string. For more information, check out the discussion on Stack Overflow.

3 Ways to Combine Raw and Multiline Strings

In Python, you can combine raw and multiline strings to create a string that spans across multiple lines, while also preserving special characters and escape sequences. This section will explain different ways to achieve this combination.

One common approach is to use triple quotes for creating a multiline string. By using three single quotes (''') or three double quotes ("""), you can create a multiline string that retains any whitespace and can include special characters. To add a raw string, use the r prefix before the triple quotes:

raw_multiline_string = r"""This is a raw
multiline string with a backslash: \\
and a new line \n is just character literals."""

Another way to write a raw multiline string is by using parentheses and string concatenation. Each line of the string can be enclosed in single or double quotes, followed by a space to ensure a single whitespace character divides them. Add the r prefix before each quoted line to maintain the raw string format:

raw_multiline_string = (r"This is a raw" r" multiline string with a backslash: \\" r" and a new line \n is just character literals.")

Alternatively, you can use the + operator to concatenate multiple raw strings, creating a multiline string. This approach allows you to explicitly specify newline characters or other special characters as needed:

raw_multiline_string = (r"This is a raw" + "\n" r" multiline string with a backslash: \\" + "\n" r" and a new line \n is just character literals.")

With these techniques, you can create raw multiline strings that are easier to read and maintain in your Python code.

Multiline Raw String Use Cases and Examples

This section reviews some use cases and examples demonstrating how to correctly write a raw multiline string in Python.

Using raw multiline strings is beneficial when dealing with strings containing many backslashes or with regular expressions. In these scenarios, raw strings prevent the need to escape backslashes, making the code more readable.

Here’s a basic example of creating a raw multiline string:

multiline_raw_string = r"""This is a raw \
multiline string in Python. \\
You don't need to escape the backslashes \\."""

In this example, the backslashes are preserved in the text as they’re written, without the need to escape them, thanks to the r prefix before the triple quotes.

Now, let’s take a look at a specific use case with regular expressions:

Suppose you want to match a file path pattern in a text, using a regular expression. Without raw strings, you’d need to escape the backslashes:

import re pattern = 'C:\\\\Users\\\\[A-Za-z0-9]+\\\\Documents'
text = 'C:\\Users\\JohnDoe\\Documents\\example.txt' result = re.search(pattern, text)
print(result.group())

With raw strings, the regex pattern becomes more readable, as you don’t need to escape the backslashes:

import re pattern = r'C:\\Users\\[A-Za-z0-9]+\\Documents'
text = 'C:\\Users\\JohnDoe\\Documents\\example.txt' result = re.search(pattern, text)
print(result.group())

In both examples, the output is the same:

C:\Users\JohnDoe\Documents

These examples demonstrate the benefits of using raw multiline strings in Python, especially when working with text that contains special characters like backslashes or incorporating regular expressions in your code.


Feel free to check out our full guide on raw strings here:

๐Ÿ’ก Full Guide: Python Raw Strings: A Helpful Easy Guide

If you want to keep improving your programming skills, consider joining our free email academy (130,000 coders) by downloading your cheat sheets here:

Posted on Leave a comment

How I Created a Machine Learning Web Application Using Django

5/5 – (1 vote)

Deploying a Machine Learning model as a web application makes it easy for others with little or no programming experience to use it.

In previous tutorials, where I explained how I created a house price prediction app and a loan eligibility app, we made use of Streamlit. Streamlit is easy to use. This is why it is a popular choice for data scientists.

In a world where learning one framework isnโ€™t enough, wonโ€™t it be nice to learn how to accomplish this using Django?

Understandably, Django can be tough for beginners. The only remedy though is constant practice. If you have been going through some of my tutorials on Django, there is no doubt that you have become familiar with the process.

Therefore, in this tutorial, we will add to your knowledge by creating a machine learning application using Django. Guess what we will used for prediction? The famous Titanic dataset!

Developing Machine Learning Model

The Machine Learning classification problem aims to predict the survival of the passengers based on their attributes. There are multiple steps involved in creating a Machine Learning model. To keep things simple, we will skip those steps and focus on showing how to implement Machine Learning in Django.

Create a folder for this project. Then, inside the folder, create a file named model.py. This is where we will develop our model. You can download the dataset on my GitHub page.

import pandas as pd
import numpy as np
from sklearn.model_selection import train_test_split
from sklearn.preprocessing import MinMaxScaler
from sklearn.linear_model import LogisticRegression
import pickle df = pd.read_csv('titanic.csv', index_col=0) # selecting the features we need
df = df[['Pclass', 'Sex', 'Age', 'SibSp', 'Parch', 'Fare', 'Embarked', 'Survived']] # encoding the column to a numberic value
df['Sex'] = df['Sex'].map({'male': 0, 'female': 1}) # converting the Age column to numberic type
df['Age'] = pd.to_numeric(df.Age) # filling the null values
df['Age'] = df.Age.fillna(np.mean(df.Age)) # creating additional features from Embarked columns after converting to dummy variables
dummies = pd.get_dummies(df.Embarked)
df = pd.concat([df, dummies], axis=1)
df.drop(['Embarked'], axis=1, inplace=True) X = df.drop(['Survived'], axis=1)
y = df['Survived'] # scaling the features
scaler = MinMaxScaler(feature_range=(0,1))
X_scaled = scaler.fit_transform(X) model = LogisticRegression(C=1)
model.fit(X_scaled, y) # saving model as a pickle
pickle.dump(model, open('titanic.pkl', 'wb'))
pickle.dump(scaler, open('scaler.pkl', 'wb'))

After importing the CSV file, we saw that there are missing values in the features selected. We simply fill them up with the mean of the values. We convert the Embarked column to a dummy variable. Then, we add them to the features.

We are using LogisticRegression as the Machine Learning algorithm to make this prediction. Finally, we save the model as a pickle object to be used later.

Creating Django Project

As covered in previous tutorials, the steps to set up a new Django project are as follows:

  • create and activate a virtual environment
  • install required libraries
  • create a new Django project which we will call predictions
  • create a requirements.txt file
  • create a new app called titanic
  • perform a migration to set up the database
  • update settings.py
$ python3 -m venv venv
$ source venv/bin/activate
(venv) $ pip install django tzdata scikit-learn pandas numpy
(venv) $ pip freeze > requirements.txt
(venv) $ django-admin startproject venv_predictions .
(venv) $ python manage.py startapp titanic
(venv) $ python manage.py migrate
(venv) $ python manage.py runserver

The (venv) indicates that you are in the virtual environment. Donโ€™t forget to include the dot which signifies creating the project in the current directory. You will see the image below if everything was installed successfully.

Open the settings.py file to let Django know that a new app is created. We will do so in the INSTALLED_APP section.

INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', # custom app 'titanic',
]

Letโ€™s configure the URLs for our website. Open the urls.py in the project folder and make it appear like this:

from django.contrib import admin
from django.urls import path, include urlpatterns = [ path('admin/', admin.site.urls), path('', include('titanic.urls')),
]

Letโ€™s now configure the URLs for the app. Create a urls.py in the app folder.

from django.urls import path
from .views import home, result urlpatterns = [ path('', home, name='home'), path('result/', result, name='result'),
]

Letโ€™s create another file in the app folder named predict.py. This is where we will use the pickled files to make predictions.

import pickle def getPrediction(pclass, sex, age, sibsp, parch, fare, C, Q, S): model = pickle.load(open('titanic.pkl', 'rb')) scaled = pickle.load(open('scaler.pkl', 'rb')) transform = scaled.transform([[pclass, sex, age, sibsp, parch, fare, C, Q, S]]) prediction = model.predict(transform) return 'Not Survived' if prediction == 0 else 'Survived' if prediction == 1 else 'error'

The function contains the exact number of features used to train the model.

Notice we first transform the values the user will input on the web page. Since the trained model was transformed, we have to do the same to any values the user enters. Finally, we return the results based on the prediction.

Alright, letโ€™s head over to the views.py file in the app folder.

from django.shortcuts import render
from .prediction import getPrediction # Create your views here.
def home(request): return render(request, 'home.html') def result(request): pclass = int(request.GET['pclass']) sex = int(request.GET['sex']) age = int(request.GET['age']) sibsp = int(request.GET['sibsp']) parch = int(request.GET['parch']) fare = int(request.GET['fare']) embC = int(request.GET['embC']) embQ = int(request.GET['embQ']) embS = int(request.GET['embS']) result = getPrediction(pclass, sex, age, sibsp, parch, fare, embC, embQ, embS) return render(request, 'result.html', {'result': result})

The home() function simply renders the home.html which contains the form where our users will input some details. Then the result() function will get those details, make predictions, and renders the prediction result.

Notice that we made sure every detail corresponds to the features used in training the model.

The final step is templates. Create a folder bearing the name. Make sure you are doing so in the current directory. Then register it in the settings.py file.

TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [os.path.join(BASE_DIR, 'templates')], # add these 'APP_DIRS': True, 'OPTIONS': { 'context_processors': [ 'django.template.context_processors.debug', 'django.template.context_processors.request', 'django.contrib.auth.context_processors.auth', 'django.contrib.messages.context_processors.messages', ], }, },
]

Donโ€™t forget to import the required module. Inside the templates folder, create a home.html file.

<!DOCTYPE html>
<html lang="en" dir="ltr"> <head> <meta charset="utf-8"> <title>Home</title> </head> <body> <h1 style= โ€œcolor:blueโ€>Titanic Survival Prediction</h1> <form action="{% url 'result' %}"> {% csrf_token %} <p>Passenger Class:</p> <input type="text" name="pclass"> <br> <p>Sex:</p> <input type="text" name="sex"> <br> <p>Age:</p> <input type="text" name="age"> <br> <p>Sibsp:</p> <input type="text" name="sibsp"> <br> <p>Parch:</p> <input type="text" name="parch"> <br> <p>Fare:</p> <input type="text" name="fare"> <br> <p>Embark Category C:</p> <input type="text" name="embC"> <br> <p>Embark Category Q:</p> <input type="text" name="embQ"> <br> <p>Embark Category S:</p> <input type="text" name="embS"> <br> <input type="submit" value='Predict'> </form> </body>
</html>

This syntax "{% url 'result' %}" is Django templating language. Itโ€™s a link to the result.html. Remember the name argument in the path() function in urls.py? That is another way to refer to the result.html URL. The csrf_token is for security reasons. Itโ€™s mandatory when a form is created.

Can you now see itโ€™s from this form we get those names in the result() function? It is here that the data will be collected and sent to the result() function which processes the data, makes predictions, and displays the result in the result.html.

We now create the result.html file in the templates folder.

<!DOCTYPE html>
<html lang="en" dir="ltr"> <head> <meta charset="utf-8"> <title>Result</title> </head> <body> <h1 style=โ€œcolor:blueโ€>Prediction</h1> <p>Verdict: {{ result }} </p> </body>
</html>

Itโ€™s very simple. The {{ result }} is a variable that will be rendered to this web page. Go back to your result() function to recall if you have forgotten.

Thatโ€™s it. We are done. Thanks for staying with me so far in this tutorial. Letโ€™s check what we have done. Run the local server.

That is the home page. Everything in the form is displayed. Enter details and make predictions. Remember, only numbers will be in the form. If you are lost, check the dataset using Pandas.

If you encounter an error saying, โ€œNo such file or directory: 'titanic.pkl'โ€, you may have to manually run the model.py to generate the file.

๐Ÿ’ก Recommended: 5 Minutes to Pandas

Conclusion

Congratulations!! You are not only a data scientist but also a Django developer.

In this tutorial, we performed Machine Learning using Logistic Regression.

We demonstrated how to implement it using Django.

๐Ÿ’ป Exercise: As an assignment, can you use what you have learned to make predictions on the iris dataset, the hello world of data science? Give it a try using Django.

You are welcome. ๐Ÿ’ช

Posted on Leave a comment

GitHub Proactively Replaces Exposed RSA SSH Host Key to Safeguard Git Operations

5/5 – (1 vote)

GitHub swiftly replaced its RSA SSH host key today after discovering it was briefly exposed in a public repository. Fear not, as the key switch doesn’t affect GitHub’s infrastructure or customer data, and only impacts Git operations over SSH using RSA. HTTPS Git operations and web traffic remain unaffected.

The exposure wasn’t due to a compromise but rather an inadvertent publishing of private information. GitHub took action out of caution, and there’s no evidence of the exposed key being misused.

If you’re using ECDSA or Ed25519 keys, no action is needed. However, if you encounter a warning message while connecting to GitHub.com via SSH, follow the provided steps to remove the old key and add the new one. GitHub Actions users should take note of potential failed workflow runs and update their workflows accordingly:

For further details, consult GitHub’s official documentation on SSH public key fingerprints.

Posted on Leave a comment

Executive Summary of Bill Gatesโ€™ The Age of AI has begun

4/5 – (1 vote)

๐Ÿ’ก This article summarizes Bill Gates’ article on “The Age of AI has begun” but focuses on the most important ideas for ease and speed of reading. I left the overall structure intact but reduced the text by approximately 70%.

Time savings with average reading speed: 9 minutes. โŒ›


๐Ÿ’ก In the article, Bill Gates shared his thoughts on the revolutionary potential of artificial intelligence (AI) and its potential to address global inequities.

Gates compared the impact of AI to the invention of the graphical user interface in 1980, a critical turning point for modern computing.

He was astonished by OpenAI’s GPT model, which managed to score a 5 on an AP Biology exam, a remarkable feat that showcased its potential.

Gates believes that AI will transform how people work, learn, travel, receive healthcare, and communicate, with entire industries reorienting around it. He sees AI as a tool to reduce the world’s worst inequities, especially in health, education, and climate change.

๐ŸŽ Regarding global health, Gates envisions AI could help save the lives of millions of children who die each year from preventable causes. In the US, AI could be instrumental in improving education, particularly in boosting math skills for underprivileged students. Finally, AI could contribute to climate change solutions, given that the world’s poorest populations, who did the least to cause the problem, are the most affected.

Gates acknowledges that AI raises concerns around workforce displacement, privacy, bias, and other issues. However, he emphasizes the importance of governments and philanthropy in ensuring that AI reduces inequity

Artificial Intelligence

Artificial intelligence (AI) refers to models designed for specific tasks or services, like ChatGPT, while artificial general intelligence (AGI) is a software capable of learning any task or subject. AGI doesn’t exist yet, and its creation is still debated within the computing industry.

AI development has been a long-standing dream, and with machine learning and increased computing power, sophisticated AI is now a reality. The growth of AI will likely accelerate, similar to the rapid expansion of the software industry during the early days of personal computing. As more attention turns to AI, innovations will come faster, eventually making the pre-AI era seem like a distant memory.

Productivity

AI, like GPT, can help automate various tasks in jobs such as sales, service, or document handling, making work more efficient.

AI integrated into products like Microsoft Office will enhance tasks like writing emails and managing inboxes. Eventually, computers will be controlled using plain language rather than pointing and clicking.

This is what I found most exciting in the whole article:

๐Ÿง‘โ€๐Ÿ’ป AI advances will enable the creation of personal agents or digital personal assistants, streamlining scheduling, communications, and e-commerce across all devices. Company-wide agents will empower employees, making them more productive by providing relevant information and insights.

Increased productivity from AI can benefit society by freeing people up for tasks requiring human touch, such as teaching or patient care. Governments should help workers transition into new roles to address the changes brought by AI. By targeting global health and education, AI can help reduce inequity and address areas with significant needs.

Health

AI has the potential to significantly improve healthcare and the medical field. It can assist healthcare workers with tasks like paperwork, insurance claims, and drafting notes, increasing efficiency. In poor countries, AI can help health workers become more productive and enable patients to perform basic triage and seek appropriate treatment.

AI models in poor countries will need to be adapted for different diseases, languages, and challenges. Although AI adoption may take longer in healthcare due to necessary testing and regulation, AI can still significantly benefit the sector.

AI will also accelerate medical breakthroughs by analyzing large amounts of biological data, helping design drugs, and predicting side effects. The Gates Foundation aims to use AI tools to address health problems affecting the world’s poorest people, such as AIDS, TB, and malaria.

Additionally, AI-generated insights can improve agriculture in poor countries by developing better seeds, advising farmers, and creating drugs and vaccines for livestock. As climate change increasingly impacts subsistence farmers, AI-driven advances become even more crucial.

Education

While computers have not yet revolutionized education as hoped, AI-driven software in the next five to 10 years has the potential to transform teaching and learning.

๐Ÿ’ก AI can tailor content based on a student’s interests and learning style, provide immediate feedback, and assist teachers and administrators with tasks like assessing understanding and career planning.

Despite the potential of AI, learning will still rely on strong relationships between students and teachers. Ensuring that AI tools are available to low-income schools and training AI on diverse data sets to avoid bias is crucial.

Educators are already adapting to AI technologies, such as GPT, in their classrooms. While concerns about students using AI to write essays persist, some teachers have found ways to incorporate the technology into their teaching, such as using AI-generated drafts that students then personalize.

Risks and problems with AI

Current AI models have limitations, such as struggling with context and abstract reasoning, but these issues are expected to be largely fixed within a few years. There are non-technical concerns, like the potential misuse of AI and the possibility of AI running out of control.

However, recent AI advancements have not made these concerns more urgent.

Superintelligent AI, or artificial general intelligence (AGI), could be a profound change in the future, raising questions about its goals, potential conflicts with humanity’s interests, and whether its development should be prevented. Although AI has become more human-like in expression, it does not indicate meaningful independence.

๐Ÿ“– Gates Book Tips: Three influential books on AIโ€”Superintelligence by Nick Bostrom, Life 3.0 by Max Tegmark, and A Thousand Brains by Jeff Hawkinsโ€”provide thought-provoking perspectives on the subject, even if they don’t always agree with each other or the reader.

Next Frontiers

The future of AI will see an explosion of companies working on new uses and improvements in the technology, with advancements in both hardware and software. The development of specialized AIs and artificial general intelligence will be competitive areas.

The public discussion surrounding AI should be guided by three principles:

  1. Balance fears about AI’s downsides with its potential to improve lives while guarding against risks and spreading benefits widely.
  2. Governments and philanthropy should ensure AI reduces inequity, as market forces may not naturally produce AI products and services that help the poorest.
  3. Recognize that AI’s limitations will be overcome, and this new technology can help people improve their lives globally.

The Age of AI presents opportunities and responsibilities, requiring rules to ensure AI’s benefits outweigh its downsides and are accessible to everyone, regardless of location or wealth.

๐Ÿš€ Recommended: 7 Effective Prompting Tricks for ChatGPT

Posted on Leave a comment

Contact Us Page Design โ€“ HTML Form

by Vincy. Last modified on March 23rd, 2023.

This article has HTML templates for contact form pages. All these templates are responsive to fit any viewports.

On a responsive page, the site header menu can be toggled. Template 1 and 2 of this example has JavaScript function to perform the toggle events for a sliding menu in the mobile view.

Contact Form Template 1

This template has the contact form in the site footer. The footer contains three columns to show the contact form details.

If you are creating a contact form page, it should clearly show the location and the contact details.

In this template, the footer columns show these details with a contact form.

The site header contains menu links and a hamburger icon. The hamburger icon can be seen in the mobile view only.

The header dropdown menu will be shown on clicking that icon in the site banner.

contact form template1

template-1/index.html

<html>
<head>
<meta name="viewport" content="width=device-width, initial-scale=1">
<link href="style.css" rel="stylesheet" type="text/css">
</head>
<body> <div class="container"> <div class="site-banner"> <div class="header-menu"> <a href="">Logo</a> <span id="menu-icon" onClick="toggleMenu()"><img src="images/menu.svg" /></span> <span id="header-right-menu"> <a href="#">Our work</a> <a href="#">About</a> <a href="#">News</a> <a href="#" class="header-active">Contact</a> </span> </div> <h1 class="heading">Contact Us</h1> </div><div class="footer"> <div class="footer-column"><img class="map-image" src="images/location.jpg" /></div> <div class="footer-column"> <div class="tile-content"> <h1>Meet Us</h1> <div class="contact-row"> <img src="images/phone.svg"><span class="tile-field">+466723723666</span> </div> <div class="contact-row"> <img src="images/at-sign.svg"><span class="tile-field">contact@admin.com</span> </div> <div class="contact-row"> <img src="images/map-pin.svg"><span class="tile-field">1784 Griffin Street, Alabama</span> </div> </div> </div> <div class="footer-column contact-form-container"> <div class="tile-content"> <form method="POST"> <h1>Contact</h1> <div class="contact-row"> <input type="text" class="form-field" placeholder="Name"> </div> <div class="contact-row"> <textarea rows="5" class="form-field" placeholder="Message"></textarea> </div> <button class="button">Send</button> </form> </div> </div> </div> </div> <script> function toggleMenu() { var menuElement = document.getElementById("header-right-menu"); if (menuElement.style.display === "block") { menuElement.style.display = "none"; } else { menuElement.style.display = "block"; } } </script>
</body>
</html>

The below CSS is created for this contact form template. It contains media queries for the responsiveness of the contact form page.

template-1/style.css

body { font-family: Arial;
} .container { max-width: 1180px; margin: 0 auto; line-height: 1.5;
}
/* header style starts */
.site-banner { min-height: 400px; background-image: url('images/header-image.jpg'); background-size: cover; background-position: center; color: #ffffff;
} .site-banner a { color: #ffffff; text-decoration: none; font-weight: bold; padding: 12px;
} .header-menu { padding: 40px 20px;
} #header-right-menu { float: right;
} .header-active { background: rgba(0, 0, 0, 0.5); border-radius: 25px;
} .heading { color: #ffffff; text-align: center; font-family: cursive; padding: 40px 0px; font-size: 3em; margin: 0px;
}
/* header style ends */ .footer { display: flex;
} .footer-column { width: 33.3%; float: left;
} .map-image { width: 100%;
} .contact-form-container { background-color: #eaeaea;
} img { vertical-align: middle;
} .tile-content { padding: 20px 40px;
} .tile-content .contact-row { margin-bottom: 20px;
} .tile-field { margin-left: 20px;
} .form-field { width: 100%; padding: 10px 8px; border-radius: 4px; border: #d9d8d8 1px solid;
} .button { color: #ffffff; padding: 10px 30px 10px 30px; border-radius: 20px; background: linear-gradient(to right, #08a9df, #12054a); border: 0px;
} #menu-icon { display: none; float: right;
} @media screen and (max-width: 1000px) { .footer-column { width: 50%; } .contact-form-container { width: 100%; } .footer { display: block; }
} @media screen and (max-width: 540px) { #header-right-menu { float: none; display: none; } #header-right-menu a { display: block; } .heading { padding: 0px; } .tile-content { padding: 0px 20px; } .footer-column { width: 100%; } #menu-icon { display: block; float: right; }
}

Contact Form Template 2

This contact template shows the contact details, address, phone, and email. It offers a form with primary fields to let the user communicate with the site owner.

This template has two columns in the site content area. The contact details and the contact form are shown in these two columns, respectively.

contact form template2

template-2/index.html

<!DOCTYPE html>
<html>
<head>
<title>Contact - Form</title>
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet" type="text/css" href="style.css">
</head>
<body> <div class="container"> <div class="text-center"> <h1>Contact Us</h1> <div> Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore <div>et dolore magra aliqua. Ut enim ad minim veniam.</div> </div> </div> <div class="content"> <div class="col-1"> <div class="address-line"> <img alt="location" src="image/marker.png" class="icon"> <div class="contact-info"> <div class="contact-info-title">Address</div> <div>1002 West 5th Ave,</div> <div>Alaska, New York,</div> <div>55060.</div> </div> </div> <div class="address-line"> <img alt="location" src="image/phone.png" class="icon"> <div class="contact-info"> <div class="contact-info-title">Phone</div> <div>12523-4566-8954-8956.</div> </div> </div> <div class="address-line"> <img alt="location" src="image/mail.png" class="icon"> <div class="contact-info"> <div class="contact-info-title">Email</div> <div>contactemail@gmail.com</div> </div> </div> </div> <div class="col-2"> <form> <div class="form-container"> <h2>Send Message</h2> <div class="form-row"> <label>Full Name</label> <div> <input type="text" class="form-field"> </div> </div> <div class="form-row"> <label>Email</label> <div> <input type="text" class="form-field"> </div> </div> <div class="form-row"> <label>Type your message...</label> <div> <input type="text" class="form-field"> </div> </div> <input type="button" class="send-btn" value="Send"> </div> </form> </div> </div> </div>
</body>
</html>

See the below CSS and include it in the template 2 HTML.

template-2/style.css

body { font-family: Arial; background-image: url('image/bg.png'); background-size: cover; background-position: center; background-repeat: no-repeat; background-attachment: fixed;
} .container { width: 950px; margin: 80px auto; color: white; line-height: 1.5;
} .text-center { text-align: center;
} .content { display: flex; margin-top: 40px;
} .icon { background-color: white; border-radius: 30px; padding: 15px; vertical-align: top;
} .contact-info { display: inline-block; padding: 4px 20px 0px 20px;
} .address-line { margin-top: 40px;
} .col-1 { width: 530px;
} .col-2 { flex: 1 1 auto; background-color: white;
} .form-container { color: #000; padding: 30px;
} .contact-info-title { color: #01bdd4;
} .form-row { padding-bottom: 30px;
} .form-field { width: 100%; border: none; border-bottom: 1px solid #000;
} .send-btn { border: 0px; padding: 12px 26px; background-color: #01bdd4; color: white;
} @media all and (max-width: 1024px) { .container { width: auto; padding: 30px; } .col-1 { width: 360px; } } @media all and (max-width: 700px) { .content { display: block; } .col-2 { margin-top: 40px; } .col-1{ width:100%; }
} @media all and (max-width: 500px) { .container { padding: 10px; }
}

Contact Form Template 3

Template 3 is a simple and clean theme for a contact form page. It displays a contact form with a few primary fields. Also, it shows only the vital contact details on the page.

A simple contact template will encourage the end user to connect with you and increase the conversion rate.

contact form template3

template-3/index.html

<html> <head> <meta name="viewport" content="width=device-width, initial-scale=1"> <link href="style.css" rel="stylesheet" type="text/css">
</head> <body> <div class="container"> <div class="header-content"> <a href="">Logo</a> <span id="menu-icon" onClick="toggleMenu()"><img src="images/menu.svg" /></span> <span id="header-right-menu"> <a href="#">Services</a> <a href="#">Products</a> <a href="#">Pricing</a> <a href="#" class="header-active">Contact Us</a> </span> </div> <div class="inner-container"> <div class="tile1"> <div class="tile1-heading">Get in touch</div> <div class="form-row">We are here for you! How can we help?</div> <form> <div class="form-row"> <input type="text" class="form-field" placeholder="Enter your name"> </div> <div class="form-row"> <input type="text" class="form-field" placeholder="Enter your email address"> </div> <div class="form-row"> <textarea class="form-field" placeholder="Go ahead we are listening..."></textarea> </div> <div class="form-row"> <input type="button" class="form-field btn" value="Submit"> </div> </form> </div> <div class="tile2"> <div class="tile2-image"> <img src="images/contact.png"> </div> <div> <div class="form-row"> <img src="images/loaction.png" class="contact-image"><span>564 Alabama Avenue</span> </div> <div class="form-row"> <img src="images/phone.png" class="contact-image"><span>+466723723666</span> </div> <div class="form-row"> <img src="images/mail.png" class="contact-image"><span>contact@admin.com</span> </div> </div> </div> </div> </div> <script> function toggleMenu() { var menuElement = document.getElementById("header-right-menu"); if (menuElement.style.display === "block") { menuElement.style.display = "none"; } else { menuElement.style.display = "block"; } } </script> </body> </html>

And the styles of this template three are shown below.

template-3/style.css

body { font-family: Arial; background-image: url('images/bg.jpg'); background-position: center; background-size: cover; background-repeat: no-repeat; background-attachment: fixed;
} .container { border-radius: 16px; max-width: 1180px; margin: 0 30px;
} a { color: #ffffff; text-decoration: none;
} .header-content { font-weight: bold; width: 800px; margin: 20px auto;
} #header-right-menu { float: right;
} #header-right-menu a { padding: 12px;
} .header-active{ color:#000;
} .inner-container { width: 750px; margin: 80px auto; display: flex; background-color: white; border-radius: 12px; padding: 30px
} .tile1 { width: 350px;
} .tile2 { flex: 1 1 auto; padding: 0px 40px;
} .tile1-heading { background: -webkit-linear-gradient(#0aa6bd, #f126bd); -webkit-background-clip: text; -webkit-text-fill-color: transparent; font-weight: bold; font-size: 1.5em;
} .form-row { padding: 20px 0px 0px 0px;
} .form-field { border-radius: 4px; width: 100%; padding: 15px; background-color: #f5f4fa; border: 0px;
} .contact-image { padding: 10px; border-radius: 35px; border: 1px solid #a8a4a4; vertical-align: middle; margin-right: 20px; width: 16px; height: 16px;
} textarea { height: 100px; font-family: Arial;
} .btn { color: white; background: linear-gradient(to right, #0aa6bd, #f126bd);
} .tile2-image img { width: 321px; height: 211px;
} #menu-icon { display: none; float: right;
} @media all and (max-width: 900px) { .inner-container { width: auto; display: block; margin: 30px auto; } .header-content { width: auto; } .tile1 { width: 100%; } .tile2 { padding: 0px; } .tile2-image img { width: 100%; height: auto; }
} @media all and (max-width: 540px) { #header-right-menu { float: none; display: none; } #header-right-menu a { display: block; padding: 10px 0px; } #menu-icon { display: block; float: right; }
} @media all and (max-width: 400px) { .container { padding: 10px; }
}

Download

โ†‘ Back to Top

Posted on Leave a comment

The Battle Between Centralization and Decentralization in Tech

5/5 – (1 vote)

Once upon a time, I was a distributed systems researcher specializing in graph partitioning algorithms. Those were thrilling days, though I must admit I didn’t enjoy the daily commute and the time away from my family.

During that period, I delved deep into classic distributed systems conundrums like the Byzantine Generals Problem. When I discovered that Bitcoinโ€”a peer-to-peer monetary systemโ€”offered a practical solution, I was excited.

My colleagues and I would spend hours over lunch breaks dissecting and discussing this groundbreaking resolution.

If you’re curious about this captivating problem and its ingenious solution, don’t miss today’s Finxter blog tutorial:

๐Ÿช™ [Blog] How Bitcoin Solves the Byzantine Generals Problem

It’s a remarkable technical triumph that proves no challenge is insurmountable for dedicated and driven individuals. Just look at the success of Bitcoinโ€”an anonymous coder created the 21st most capitalized currency in the world!

In the world of tech, we witness an ongoing battle between two formidable forces:

🏋

Giant 1 – Leviathan. This force represents the powerful centralization trends and winner-take-most economies in the tech and machine learning industries. Think big tech, big government, and big brotherโ€”those with the best data sets win.


🧑‍💻🧑‍💻🧑‍💻

Giant 2 – Atomos. This symbolizes the ever-strengthening decentralized infrastructures and systems, such as Bitcoin and decentralized social networks like PeerBrain. Atomos represents everyday coders like you and me. Derived from the ancient Greek word for “uncuttable” or “indivisible,” Atomos signifies the countless small, independent entities in a decentralized system.


I’m thankful for recent advancements in AI, as they’ll propel humanity toward hyper-efficiency and uncharted heights. Yet, I also appreciate the existence of counterbalancing forces like the indomitable Atomos, redistributing power from the few back to the many.

Decentralized money, energy production, and social networks are just the beginning of this promising trend, and its potential is immense!

If you’re eager to contribute to the growth of Atomos, consider checking out the Uniswap Automated Finance for Blockchain Engineers course. While the Ethereum ecosystem isn’t entirely decentralized yet, it could beโ€”and that would serve as an effective countermeasure to centralized platforms.

We need more builders!

“A democracy is only as resilient as its people. An informed and engaged citizenry is the bedrock of a healthy democracy.”

The same holds true for decentralization!

To your success! ๐Ÿš€
Chris


This email was part of our free email academy for exponential technologies. To stay ahead of the curve and remain on the right side of change, join our free email academy by downloading your cheat sheets for learning here: