Localized Currency and Dates in Java

Introduction

When working with an application with a global user base, there is usually a need to display text, numbers, currency, date, and time in multiple localized formats. For example, the en-US (English-USA) version of the date

September 22, 2021 

is written as

22  2021 .

when the locale used is ru-RU (Russian-Russia).

In this tutorial, we will learn how to format currency and date in localized formats using java.time.* and java.text.* classes.

Goals

At the end of this tutorial, you would have learned:

  1. How to format currency based on locale.
  2. How to format dates based on locale.
Prerequisite Knowledge
  1. Basic Java.
Tools Required
  1. A Java IDE.
Locale Overview

Before proceeding further, let us discuss an important concept: java.util.Locale.

A Locale object is an encapsulation of data used to specify the language, the country, and/or the variant of a geographic region.

There are 3 Locale constructors:

    public Locale(String language)
    public Locale(String language, String country)
    public Locale(String language, String country, String variant)

When creating a Locale object (the first constructor), you must at least pass in a language code, which must be in the form of an ISO 639 alpha-2 or alpha-3 language code, or a language subtag up to 8 characters in length. For this tutorial, we will only be using the ISO 639-1 alpha-2 language code, which is in the form of lowercase 2 letters abbreviation (i.e, en, es).

For the second constructor, we can pass in a country code as well, which must be in the form of An ISO 3166 alpha-2 country code or a UN M.49 numeric-3 area code. For this tutorial, we will be using the ISO 3166 alpha-2 country code, which is in the form of uppercase 2 letters abbreviation (i.e, US, UK).

We do not concern ourselves with the locale variant in this tutorial.

Besides using constructors, Locale objects can also be created using the convenient constants that the Locale class provides, such as

Locale.UK

or

Locale.CANADA

After retrieving the Locale object, we can then pass it to DateTimeFormatter or NumberFormat instances to localize the data.

Project Setup

Now that we have finished talking about concepts, perform the steps below to set up our project:

  1. Create a new Java project.
  2. Create a package com.example.
  3. Create a Java class called Entry.java. This is where our main() method lives.
Localizing Dates

First, create a method called localizeDate() that takes a LocalDate argument and a Locale argument. This method will return the formatted String representation of a localized date.

    private static String localizeDate(LocalDate date, Locale locale){ //7
       DateTimeFormatter formatter = DateTimeFormatter //8
               .ofLocalizedDate(FormatStyle.LONG) //9
               .withLocale(locale); //10

       return formatter.format(date); //11
    }

DateTimeFormatter does not have a public constructor, so we have to use the static factory methods to create an instance of DateTimeFormatter. The static factory method used has this signature:

public static DateTimeFormatter ofLocalizedDate(FormatStyle dateStyle)

It requires a FormatStyle enum as an argument. So we pass to it a FormatStyle.LONG constant at line 9. There are 4 constants in total in FormatStyle, SHORT, MEDIUM, LONG, and FULL. You can experiment with passing in different constants to see how the output changes.

On line 10, we use the withLocale() method to return a copy of the previous instance (including FormatStyle choice) with our choice of Locale.

To format the date, we only have to call the format() method at line 11.

Back in main(), create a new array of Locales and one LocalDate object to pass to our localizeDate() method.

    //Pre-made locales
    Locale[] locales = {
           Locale.US,
           Locale.JAPAN,
           Locale.FRANCE,
           Locale.KOREA,
           new Locale("es", "PE")
    }; //1

    LocalDate now = LocalDate.now(); //2

We need an array of Locales because it is interesting to observe how different Locales can produce different output. The first 4 Locale objects in the array were obtained using the convenient constants in Locale. The last Locale object was created using the constructor (which I have explained earlier) using the language and country codes. PE is the ISO 3166-2 country code for Peru and es is the ISO 639 alpha-2 language code for Spanish.

Now loop through the array and call the localizeDate() method against each Locale using the same LocalDate object now.

    //localized date loop
    for (Locale locale : locales){
       System.out.println("Locale: " + locale + ", date: " + localizeDate(now, locale)); //3
    } //4

The code prints:

    Locale: en_US, date: September 22, 2021
    Locale: ja_JP, date: 2021922
    Locale: fr_FR, date: 22 septembre 2021
    Locale: ko_KR, date: 2021 9 22
    Locale: es_PE, date: 22 de setiembre de 2021

As you can see, the ordering of the day of month, the month, and the year have all been automatically switched up depending on the Locale.

Localizing Currency

Next, we will create a method to localize currency (aka printing money in a specific format based on the Locale).

    private static String localizeCurrency(BigDecimal money, Locale locale){ //12
       return NumberFormat //13
               .getCurrencyInstance(locale) //14
               .format(money); //15
    }

In the localizeCurrency() method above, we use a similar approach to the localizeDate() method, but we have to use a different class to format monetary values, NumberFormat.

NumberFormat can format more than just currency, but we are not concerned with the other types for now; that is why we used the factory method getCurrencyInstance() at line 14 to get an instance specialized in formatting currencies. We also passed in the Locale object so the NumberFormat instance knows which Locale should the currency format be in.

Back in main(), create a random monetary value:

    BigDecimal money = BigDecimal.valueOf(1_484.2428127233); //5

Since we already declared our Locale array previously, we can just re-use it for our currency loop.

    //localized currency loop
    for (Locale locale : locales){
       System.out.println("Locale: " + locale + ", money: " + localizeCurrency(money, locale)); //6
    } //7

When executed, the code prints:

    Locale: en_US, money: $1,484.24
    Locale: ja_JP, money: 1,484
    Locale: fr_FR, money: 1484,24 
    Locale: ko_KR, money: 1,484
    Locale: es_PE, money: S/ 1,484.24

All of the currency symbols, number formatting, and currency symbols have been automatically added for our convenience. The last currency symbol of S/ is not an error. S/ is the official currency notation for the Peruvian Sol.

Solution Code
    package com.example;

    import java.math.BigDecimal;
    import java.text.NumberFormat;
    import java.time.LocalDate;
    import java.time.format.DateTimeFormatter;
    import java.time.format.FormatStyle;
    import java.util.Locale;

    public class Entry {

       public static void main(String[] args){
           //Pre-made locales
           Locale[] locales = {
                   Locale.US,
                   Locale.JAPAN,
                   Locale.FRANCE,
                   Locale.KOREA,
                   new Locale("es", "PE")
           }; //1

           LocalDate now = LocalDate.now(); //2

           //localized date loop
           for (Locale locale : locales){
               System.out.println("Locale: " + locale + ", date: " + localizeDate(now, locale)); //3
           } //4

           BigDecimal money = BigDecimal.valueOf(1_484.2428127233); //5

           //localized currency loop
           for (Locale locale : locales){
               System.out.println("Locale: " + locale + ", money: " + localizeCurrency(money, locale)); //6
           } //7
       }

       private static String localizeDate(LocalDate date, Locale locale){ //7
           DateTimeFormatter formatter = DateTimeFormatter //8
                   .ofLocalizedDate(FormatStyle.LONG) //9
                   .withLocale(locale); //10

           return formatter.format(date); //11
       }

       private static String localizeCurrency(BigDecimal money, Locale locale){ //12
           return NumberFormat //13
                   .getCurrencyInstance(locale) //14
                   .format(money); //15
       }

    }
Summary

We have learned how to localize dates and currency in this tutorial.

Please keep in mind that we have only formatted the representation of the monetary value, and we did not convert the monetary value by exchange rates at all. The number 100 can be represented as $100 USD or 100 YEN, but that does not mean $100 is equal to 100.

The full project code can be found here https://github.com/dmitrilc/DaniwebLocaleCurrency/tree/master

How to read stdout from an external process in Java 17

Introduction

Although not included in the headlines, the release of JDK 17 also added 3 sets of new methods to the class java.lang.Process:

  1. inputReader() to read from stdout.
  2. inputWriter() to write to stdin.
  3. errorReader() to read from stderr.

In this tutorial, we are going to learn how to use Process.inputReader() to read stdout from external processes.

Goals

At the end of this tutorial, you would have learned:

  1. How to read stdout from an external process.
  2. What command injection is.
Prerequisite Knowledge
  1. Basic Java.
  2. Java IO/NIO.
Tools Required
  1. A Java IDE with at least JDK 17 support.
Project Setup

To follow along with this tutorial, perform the steps below:

  1. Create a new Java project.

  2. Create a package com.example.

  3. Create a Java class called Entry.java. This is where our main() method lives.

  4. Create a static reference to the current Runtime object like below.

     private static final Runtime runtime = Runtime.getRuntime();
Read stdout from scripts

If the security policy allows it, it is possible to execute a script that is not part of the current Java runtime environment.

Executing scripts written in other programming languages or system shells can also be used for illegitimate purposes, such as in a code injection/shell injection attack. After an external script is run, it can potentially evade your Java applications permissions. If you are running a service that is executing arbitrary code from end users(e.g Slack/Discord bots that execute code), then you need to make sure that proper safeguards are in place.

Without further ado, let us create some code that can both create and execute an external python script.

Inside the Entry class, we will create two new methods, createPyScript() and execPyScript(). Copy and paste the code below:

    private static Path createPyScript(Path path, String content){ //1
       //Creates the script if does not exists, else do nothing.
       try {
           Files.writeString(path, content, StandardOpenOption.CREATE); //2
       } catch (IOException e) {
           e.printStackTrace();
       }

       return path; //3
    }

    private static void execPyScript(Path script){ //4
       try {
           Process process = runtime.exec("python " + script); //5

           try (BufferedReader reader = process.inputReader()){ //6
               reader.lines() //7
                       .forEach(System.out::println); //8
           }

       } catch (IOException e) {
           e.printStackTrace();
       }
    }

The first method,createPyScript(), creates the actual script file in the file system. We only need to pass to it the content of the script file and the Path object representing the file location and name. To keep our example simple and not having to perform existence checks/removal, the StandardOpenOption.CREATE enum passed to the method makes sure that a new file is created only if it does not exist (but the file is still subject to the default writing behavior of Files.writeString()).

The second method, execPyScript(), receives the Path object representing the file location, and then executes that script:

  1. There are two ways to execute shell commands from Java, using a ProcessBuilder or a Runtime object. Line 5 uses the application Runtime object, whose exec() method executes the system command calling the python executable.
  2. Line 5 also gives us a reference to the Process object. Runtime.exec() spawns a new subprocess, which we can control via this Process object.
  3. On line 6, we declared a BufferedReader object in a try-with-resources block to retrieve sdout from the Python script.
  4. On lines 7 and 8, we retrieved a Stream<String> of all the lines printed to process stdout and printed them out in our IDE.

In main(), call the code like below:

    String pyContent = """
               for i in range(1, 6):
                   print(f'Found secret {i}')
               """; //15
    Path path = Path.of(".", "test.py"); //16

    Path script = createPyScript(path, pyContent); //17
    execPyScript(script); //18

On line 15, we create the script file content using the convenient new multiline String syntax. Python code is obviously white-space aware, so it is important to understand how to use the multiline syntax correctly in this case.

The Python code is just a very simple for loop that uses the f-string Literal String Interpolation (PEP 498) syntax to print some text 5 times.

Line 17 is where we call the method to create the script. Line 18 is where we call the method to execute the python script created on line 17.

The code prints:

    Found secret 1
    Found secret 2
    Found secret 3
    Found secret 4
    Found secret 5
Read stdout from system commands

Using a very similar approach, it is also possible to read stdout from system commands. Command injections are even easier (for attackers) to perform compared to the previous approach as this does even require write permissions(to create our own script).

Inside the Entry class, create an execSysCommands() method that can execute any number of shell commands.

    private static void execSysCommands(String... commands){ //9
       try {
           for (String command : commands){ //10
               Process process = runtime.exec(command); //11

               try (BufferedReader reader = process.inputReader()){ //12
                   reader.lines() //13
                           .forEach(System.out::println); //14
               }

           }
       } catch (IOException e) {
           e.printStackTrace();
       }
    }

In this scenario, we can pass the command directly to runtime.exec() without having to call an executable such as python.

Python is not pre-installed on Windows like most Linux distributions, so attackers are unlikely to call it if they found out that your server is Windows. Instead, they are going to use some commands that came pre-installed in Windows systems.

In main(), create some commands and call the execSysCommands() method like below:

    String ipconfig = "ipconfig /all";
    String systeminfo = "systeminfo";
    execSysCommands(ipconfig, systeminfo);

And with just two commands, the attacker was able to retrieve some of your networking information.

Solution Code
    package com.example;

    import java.io.BufferedReader;
    import java.io.IOException;
    import java.nio.file.Files;
    import java.nio.file.Path;
    import java.nio.file.StandardOpenOption;

    public class Entry {

       private static final Runtime runtime = Runtime.getRuntime();

       public static void main(String[] args) {
           String pyContent = """
                       for i in range(1, 6):
                           print(f'Found secret {i}')
                       """; //15
           Path path = Path.of(".", "test.py"); //16

           Path script = createPyScript(path, pyContent); //17
           execPyScript(script); //18

           String ipconfig = "ipconfig /all";
           String systeminfo = "systeminfo";
           execSysCommands(ipconfig, systeminfo);
       }

       private static Path createPyScript(Path path, String content){ //1
           //Creates the script if does not exists, else do nothing.
           try {
               Files.writeString(path, content, StandardOpenOption.CREATE); //2
           } catch (IOException e) {
               e.printStackTrace();
           }

           return path; //3
       }

       private static void execPyScript(Path script){ //4
           try {
               Process process = runtime.exec("python " + script); //5

               try (BufferedReader reader = process.inputReader()){ //6
                   reader.lines() //7
                           .forEach(System.out::println); //8
               }

           } catch (IOException e) {
               e.printStackTrace();
           }
       }

       private static void execSysCommands(String... commands){ //9
           try {
               for (String command : commands){ //10
                   Process process = runtime.exec(command); //11

                   try (BufferedReader reader = process.inputReader()){ //12
                       reader.lines() //13
                               .forEach(System.out::println); //14
                   }

               }
           } catch (IOException e) {
               e.printStackTrace();
           }
       }

    }
Summary

We have learned how to read stdout from an external process using the brand new inputReader() methods in JDK 17. If your app allows remote code execution(like a cloud IDE), then it is important to look into ways to secure your environment properly.

The full project code can be found here https://github.com/dmitrilc/DaniWebProcessStdout

How to Quickly Backup to S3, Google Drive, and Dropbox Using Snapshot Pro

With the Snapshot Pro WordPress plugin, you can safely and efficiently create and store backups to 3rd party platforms S3, Google Drive, and Dropbox.

Thanks to Snapshot Pro, storing backups to your favorite cloud storage set to your schedule is as easy as ever. He makes it simple to store backups to your host and elsewhere for added convenience and protection!

Image of Snapshot.
Snapshot is ready for your 3rd party backups!

Now, this is nothing new…

Snapshot has been storing incremental backups to 3rd party storage destinations for a while now. However, we include new areas to backup to regularly (e.g. Dropbox), and it’s worth mentioning, in case you weren’t aware of this feature.

And as you’ll see in this short article, adding a backup to third-party storage can be done in just a few clicks!

Getting Started

Of course, to get started, you’ll need Snapshot Pro. Snapshot Pro is free with a WPMU DEV membership. (Not a member? You can try us free for 7-days).

After installing and activating, you’re ready to go! Kick things off by heading to the Destinations area. Get to this area from Snapshot’s dashboard or by clicking Destinations on the sidebar.

Where to access the destinations area.
Destinations are easy to get to from the dashboard.

From either the dashboard or the Destinations area, clicking on the big blue Add Destination button will get you moving.

Button to add a destination.
Get ready to add a new destination in one click.

You’re now ready to…

Choose Your 3rd Party Service

Once clicking Add Destination, you’ll choose what new destination you want a full copy of each backup to go to. As mentioned earlier, you can choose from Amazon S3, Google Drive, and Dropbox.

For the sake of demonstrating how Snapshot’s backup works, let’s go with Dropbox.

Where you click to activate Dropbox.
Just select Dropbox as your option.

Once selected, you’ll hit Next, and you’ll go through an authentication process. Hit Authenticate, and then Snapshot will then ask you to sign in however you prefer to do with Dropbox (e.g. email, Google, or Apple).

Where to sign in for Dropbox.
Pick whatever way works best for you to sign in.

You’ll need to give Snapshot permission to edit, view content, and view & edit information. To do so, just click Allow.

The button to allow permissions for Snapshot.
If you want more information, you can always learn more about the permissions on the link provided.

Did it connect? Snapshot will let you know if it’s successful or not. If all is well, you’ll continue on by clicking Next.

Message about Snapshot being successfully connected.
The green indicates it’s good to go.

Snapshot then shows you the connected account. From here, you can name a Directory and set the number of backups that you want to store before removing older ones. You can enter any number you wish.

Where you connect to Dropbox.
We’ll name this directory ‘Snapshot.’

Next, we’ll give it a Destination Name. This name is so you can easily remember where backups are stored.

Where you save the destination.
We’ll label this destination ‘Snapshot’ as well.

Got it named? Great! Click Save Destination.

Your New Destination

Once doing so, you’ll now see the new Dropbox destination in Snapshot’s Destinations area. It includes the Dropbox logo, Directory name, schedule, and amount of exported backups.

Where the destination is located.
Snapshot keeps a running total of destinations on top of the page, too.

Click the gear icon to edit the destination, view the directory, or delete.

The gear icon.
Need to edit? You can quickly do so from here!

You can also turn this off or on with a click of a switch. Otherwise, that’s it! Add as many destinations as you desire, and use whenever you want.

Since this was an example with Dropbox, see how to store to S3 and Google Drive in our documentation.

View Logs

Now that your backups are off to the races, you can view the Dropbox export destination logs in the Snapshot Backups section. You’ll see the name of your Dropbox destination folder (in this case, I named it Snapshot) and view it by All, Warning, or Error.

A list of the backups.
You can see this is showing all the logs.

It shows all the information you need to know about what occurred during the backup.

Storing to 3rd Party Backups Is a Snap(shot)

The flexibility of choosing where your backups land, whether it be with S3, Google Drive, or Dropbox — is up to you. As you can see, it’s a snap!

For more on Snapshot, be sure to check out how to use Snapshot Pro with The Hub and how to get the most out of Snapshot.

And as I mentioned, we’re constantly updating Snapshot (and all of our plugins) with new options. Follow along to see what’s next in our Roadmap.

Hands on Presto Tutorial: Presto 103

Introduction

This tutorial is Part III of our getting started with Presto series. As a reminder, PrestoDB is an open source distributed SQL query engine. In tutorial 101, we showed you how to install and configure presto locally, and in tutorial 102, we covered how to run a three-node PrestoDB cluster on a laptop. In this tutorial, we’ll show you how to run a PrestoDB cluster in a GCP environment using VM instances and GKE containers.

Environment

This guide was developed on GCP VM instances and GKE containers.

Should Users Be Able To Select More Than One Block Style?

When I first tried the block styles feature in WordPress, I was impressed. As a theme creator, it was a simple way of allowing users to select a design-related class without them actually needing to know what was happening under the hood. In that first week or so, I hit the problem that many others had. I wanted to combine two or more classes/styles to offer a wide range of user options.

This was back in late 2018 or early 2019 — around the time of the WordPress 5.0 release. Others have requested the ability to combine styles since, and Keith Devon, the co-founder of Highrise Digital, brought the issue up again via Twitter last week. However, these multiple requests have never resulted in a change to the core code.

This snail’s pace has been beneficial. Jumping too early on some features when others have yet to mature can create unnecessary legacy baggage.

Over the past couple of years, I have reassessed my position on combining block styles. As the editor has evolved, there is a clearer vision emerging around what options users will have. While I initially wanted to combine block styles, I am not so sure anymore. The primary reason for this is that core has already made many obsolete through block options, and it will continue to do so with other controls in the future. When WordPress itself handles this, it creates a standard that all themes can rely on.

With one of those passion projects I’m building in my free time, I currently have six styles for the Image block:

  • Rounded
  • Flip: Horizontal
  • Flip: Vertical
  • Polaroid
  • Polaroid: Tilt Left
  • Polaroid: Tilt Right
Block style for the WordPress Image block.  Selected is a Polaroid-style frame design that is tilted to the left.
Polaroid-style image tilted left.

There are times when mixing and matching some of those might make sense. For example, the Flip: Horizontal style fits well with all the others and would not cause issues when combined. I could also go overboard by adding choices to meet every possible variation.

Some combos would break down entirely or not be aesthetically pleasing. For example, the Rounded style does not work well with the Polaroid styles. However, these are simple styles that barely scratch the surface of what is possible.

Most of these are not block styles that I would want to ship with a theme. For example, the Rounded style could easily be handled via the WordPress-supported border-radius option. The Polaroid style is just a fancy name for some padding and a box-shadow on the image. These are all standard design features that should eventually be a part of the base editor experience.

Currently, themes that ship such styles are filling in the gaps where WordPress has yet to do so. In the short term, theme authors must cater to their user base. However, down the road, WordPress should offer a more robust set of tools that cover the basics. There really is no reason for every theme to have a different, non-standard slug (i.e., class name) for essentially the same block styles (e.g., Polaroid vs. Framed vs. Borders). It creates cross-theme compatibility issues that we should avoid when possible.

Block styles are handy for introducing quick methods for achieving these fundamental design options, but I am looking at what they should be for the long term. If core WordPress evolves to the point where it makes most of these styles obsolete, what should theme authors do with the feature?

That is where more specialized block styles make sense. The goal is the same: fill in the gaps that WordPress leaves open.

One example that would be tough to replicate with simple design options would be a tag/label style for the Tag Cloud block, as shown in the following screenshot.

Tag/Label style as you'd see shopping designed around individual post tags in the Tag Cloud block.
Tag/Label style for tags.

I also have a Pill Outline style for the same block:

Core WordPress Tag Cloud block with a rounded/pill shape and outline/border.
Pill Outline block style for tags.

Obviously, those two styles would not work together. Creating a system where users could choose both would result in some problematic outcomes. The more complex any two block styles become, the more likely they will conflict with each other.

Right now, it is too early to commit to a multi-select feature for block styles. We need to let this thing play out a bit and give the core design tools a chance to catch up. We can reevaluate when most of the blocks packaged with WordPress have a broader set of styling options.

At that point, it may even make more sense to begin using block variations, an API that allows developers to preconfigure block attributes. If a solid set of design options exist, it would be simple to offer multiple combinations out of the box for users.

In the meantime, I would like to see a reevaluation of the UI for block styles. Shaun Andrews has an in-depth piece, Thinking Through: Switching Block Styles, that explores various options on how we could iterate on it.

Talk Python To Me Podcast Founder Michael Kennedy Interview

Introduction

Michael Kennedy is a successful entrepreneur and software development professional. He created and hosts the weekly podcast, Talk Python To Me, which focuses on Python and related software development topics. He also founded and is the chief author for Talk Python Training, an online Python training program. We had the opportunity to interview Michael about his programming experiences, and we have included the entire transcript below. Hope you enjoy it!

The Interview

Evrone: We at Evrone have done custom development for many years, and we try to organize professional communities in Russia, like a community for Ruby developers, for Python developers. Your podcasts are famous in Russia. So, first of all, from the Russian Python community, thank you for your hard work.

Container Units Should Be Pretty Handy

Container queries are going to solve this long-standing issue in web design where we want to make design choices based on the size of an element (the container) rather than the size of the entire page. So, if a container is 600px wide, perhaps it has a row-like design, but any narrower than that it has a column-like design, and we’ll have that kind of control. That’s much different than transitioning between layouts based on screen size.

We can already size some things based on the size of an element, thanks to the % unit. For example, all these containers are 50% as wide as their parent container.

The % here is 1-to-1 with the property in use, so width is a % of width. Likewise, I could use % for font-size, but it will be a % of the parent container’s font-size. There is nothing that lets me cross properties and set the font-size as a % of a container’s width.

That is, unless we get container units! Here’s the table of units per the draft spec:

unitrelative to
qw1% of a query container’s width
qh1% of a query container’s height
qi1% of a query container’s inline size
qb1% of a query container’s block size
qminThe smaller value of qi or qb
qmaxThe larger value of qi or qb

With these, I could easily set the font-size to a percentage of the parent container’s width. Or line-height! Or gap! Or margin! Or whatever!

Miriam notes that we can actually play with these units right now in Chrome Canary, as long as the container queries flag is on.

I had a quick play too. I’ll just put a video here as that’ll be easier to see in these super early days.

And some great exploratory work from Scott here as well:

Ahmad Shadeed is also all over this!

Query units can save us effort and time when dealing with things like font-sizepadding, and margin within a component. Instead of manually increasing the font size, we can use query units instead.

Ahmad Shadeed, “CSS Container Query Units”

Maybe container queries and container units will drop for real at the same time. 🤷


The post Container Units Should Be Pretty Handy appeared first on CSS-Tricks. You can support CSS-Tricks by being an MVP Supporter.

How to Start a Window Cleaning Business

You can start a window cleaning business rather affordably. In many cases, the largest expenses you’ll face consist of your website development, logo design, and business document creation. 

But if you have the right tools and can complete some or all of these tasks yourself, you can keep your startup costs minimal. 

Once you have your business up and running, you can start building up your client base and enjoy the empowerment that comes with being a business owner. 

Starting a window cleaning business doesn’t have to be difficult or expensive. 

If you put extra effort into developing your own website, logo, or other essential materials, then you’ll be setting your business up for success and saving even more money. 

The Easy Parts of Starting a Window Cleaning Business

When starting a window cleaning business, you’ll have a few advantages. The first is that window cleaning is an in-demand service. If you do your market research carefully, you can position your business to solve a need for many homeowners and business owners, making it easy to acquire new customers. 

Technology has made setting up a website easy and affordable. 

Website builders can help you create a professional website, even if you don’t have design experience. Website hosting has also become highly affordable, so you can make and launch your website for a minimal investment. If you are uncomfortable developing your own website, you can always hire a professional to take care of it for you, making it specific to your needs.

Canva can help with your website design, logo creation, and even the development of marketing materials. If you paid a professional for each of these elements, you might spend thousands of dollars. Canva makes it easy to create these yourself, saving you money and giving you complete control of each aspect. Canva even has a free account option with over 250,000 templates to get you started.

If you want to upgrade your Canva account to a paid plan, the Pro package is $12.99 per month or $119.99 billed annually. You get everything in the free plan plus tons of additional features and functionalities. If you aren’t sure about the paid plan, you can try it free for 30 days.

The Difficult Parts of Starting a Window Cleaning Business

Starting a window cleaning business is filled with challenges, too. Finding your first customers can take time, and you may not have enough customers to support you full-time for a while. 

If possible, plan on starting your window cleaning business on a part-time basis, so you have other income you can depend on while you get that business up and running. Different strategies, such as creating a customer loyalty reward program or customer referral program, can also help you build up your customer base faster.

Other challenges you may face include setting competitive pricing, doing a lot of in-depth market research, hiring employees, and doing administrative work like bookkeeping and invoicing. 

Many of these things can be outsourced, automated, or just take time to learn. The challenges here are not insurmountable at all. They just take your time and effort.

Step 1: Develop a Business Plan

It’s so important to take the time to create a business plan. Think of your business plan as being the roadmap for your business. It includes details about everything from your target audience to how you’ll market your business and plans for how your business will become successful. 

Creating a business plan requires lots of hard thinking, but addressing the challenges you’ll face early on can help ensure that you have a solid plan that will work. You can find many business plan templates available online to guide you through the process.

The main thing to remember is to be brutally honest about your skills, timelines, and financial plans for the business when developing your plan.

Do Market Research and Define Your Audience

Start your business plan by doing market research into the need for window cleaning in your area. If possible, poll business owners or homeowners about their window cleaning process, whether they use a professional, and how much they would be willing to pay for the service. 

It’s also essential to research your local competitors. Review their pricing and the services they offer. See if you can determine a niche or a service that’s currently unmet in the area or another way to differentiate your business. Reading a competitor’s customer reviews can help you identify any shortcomings, and those might be opportunities you could use to stand out or fill a need and attract new customers.

Determine Your Services and Pricing

Your market research will help to inform what services are most in demand in the area. You’ll need to think carefully about the types of services you’re comfortable and qualified to offer. For example, high-rise window washing requires significant experience, knowledge, skill, and specialized equipment. Your equipment and expertise may also define the services that you provide. 

Once you’ve outlined your services, you’ll need to determine your pricing structure. You’ll want to choose reasonable prices for the location, and you should already have some information about this from your market research.

To determine your prices, calculate the cost of your supplies and the overall cost of operating your business. While it’s important to develop an appropriate initial pricing structure, it’s also wise to reevaluate your prices in six months and adjust them if needed. As you gain more clients and experience, it is reasonable to raise your prices.

Define Your Unique Sales Proposition

Your unique sales proposition (USP) is what differentiates your business from others. Maybe you want to be known for your superior customer service, or perhaps you use only eco-friendly cleaning products and want to be the local environmentally conscious window cleaner. 

This unique sales proposition will be key to your marketing, so take the time to make sure that this message is clear, unique, and memorable. 

Brainstorm and Decide on a Business Name

Any great business needs an equally great name. Your name will need to be original and easy to remember. More importantly, your name should be significantly different from the names of other local window cleaners. 

To come up with a name, start brainstorming all sorts of potential names. Write all of those ideas down. Even if you don’t think you’ll use a particular name, it might lead to an idea for another, better one. Get your friends and family in on the process to help generate more ideas. You can also try a free business name generator to get more inspiration and ideas. BusinessNameGenerator.com has a good one, and it will also show you if a matching domain name is available.

Once you have a list of possibilities, start narrowing down the list to your favorites. With four or five top names selected, research to ensure that they aren’t trademarked, aren’t the name of other local businesses, and their domains are available. From there, you can choose your favorite and officially name your business. 

Step 2: Take Care of Business Paperwork

To operate your business legally, you’ll need to complete some paperwork, including business licenses and tax documents. Some of this paperwork can take time to process, so start your paperwork early on so that you don’t have to delay opening your business. 

Apply for an EIN

You’ll need to apply for a Federal Employer Identification Number, or EIN, for your business. This EIN works similarly to a Social Security Number, and it helps track income and appropriate taxes. 

When you have an EIN, you can avoid having to use your personal SSN for business purposes. This makes for a safer, more secure option that prevents your personal information from circulating with all of your business contracts. Some business checking accounts also require an EIN. You’ll also need an EIN to open a business bank account.

Get a Business License 

You’ll need a license to operate your window cleaning business. The specific licensing requirements will vary depending on the town and state where you live. Fees can vary, too. 

To get the most accurate information, call or visit your town clerk. Research to find out if your county or state requires a business license, and make sure you follow all the steps to get one if it does.

Get Insured

You’ll need several types of insurance for your business. In addition to general business liability insurance, you’ll also need business insurance for your vehicle. 

Insurance plans and premiums can vary, so contact multiple insurance companies for quotes. When you compare those quotes, consider how the premiums differ and how the coverage, exclusions, and deductibles compare.

Develop Contracts and Documents

This is also the time to create the contracts and documents you’ll need to run your business. These specific documents will vary depending on your business needs, but plan to have at least a service agreement and an invoice document prepared. 

Canva can help you to develop professional-looking documents. Canva offers a wide selection of invoice templates, and many of them are free to use. You can choose a template and then customize it with your business branding. This can save you time and money over the cost of hiring a designer to prepare these documents. 

Step 3: Develop Your Marketing Materials

To find new customers and promote your business, you’ll need quality marketing materials. From designing a log to creating your website, it’s essential to develop professional marketing and branding that represents your business well. 

Start with a Logo

Your logo will be on all of your branded materials, so start by developing a quality logo. You’ll need to think about your branding colors, text, and overall design. 

While some business owners hire a logo designer, this can get expensive and be time-consuming. Canva offers a great selection of logo templates that you can fully customize to design your own logo. Alternatively, you can use Canva to design your logo from scratch.

Once you are happy with your logo, you can download it and add it to your website, vehicle signage, uniforms, business cards, and more.

Create Your Website

You’ll also need to create a website. Canva can help with this, too. Canva has website creation templates that look very professional. You just need to edit the text, font, colors, and photos to completely customize the design and create a site of your own. If you already have a host or domain through a website builder like Wix or WordPress, you may want to use the built-in templates on those platforms instead.

Pairing Canva with the many lower-cost website hosting and building programs available can help you create a website for a minimal investment. While many business sites can cost thousands of dollars to create, Canva lets you handle the design work easily and quickly. Even if you don’t have design skills, using a template to guide you can help ensure that your site still looks great.

Create Additional Marketing Materials

With your logo established, you can easily put it on additional marketing materials. You might choose to create business cards, brochures, flyers, posters, and more. Canva has templates for all of these. 

When you have these marketing materials prepared, you’ll be able to represent your business professionally. Quality marketing materials can be vital to getting your first customers and starting to build your business.

Step 4: Purchase Your Supplies

While you can save money by designing your logo and marketing materials yourself, you will need to put some money into your initial supply and equipment purchases. If you shop around and compare prices, though, you can help to keep your startup costs down. 

Find the Right Vehicle

If you don’t already have a truck or a van, you’ll really need to buy one for your business. Look for used or leased vehicles available at a lower cost. Your insurance payments will be less for these vehicles, and you can always upgrade to a newer vehicle once your business is established and profitable. 

Be sure that any vehicle you choose has the storage capacity to hold your larger equipment, like ladders. Look for a vehicle with a structure that lets you quickly load and unload these ladders, like a truck with a rack system that’s easily accessible.

Invest in Your Equipment

You’ll also need to buy equipment, like hoses, sprayers, ladders, buckets, and chemicals. You may find some of these products available for sale used, which can help keep your initial costs down. 

It’s important to research your cleaning chemical purchase carefully. Look for a solution that performs well while also being relatively safe. It’s crucial to review any local restrictions and requirements ahead of time to verify that you’ll be able to use the chemical you purchase. This is particularly important if you’ll be cleaning buildings located near a body of water. 

Also, don’t forget to set aside plenty of money to invest in safety equipment, like goggles, gloves, coveralls, and harnesses. Buy your safety equipment new and be prepared to regularly replace it as it ages. 

Buy Uniforms

Uniforms can help you make a professional first impression, and they show that you take your business seriously. Consider buying polo shirts or coveralls with your logo embroidered on them. If you decide to hire staff, this uniform is easy and affordable to replicate, and it makes for a cohesive, polished look, which is what any customer would look for in a window cleaning company.

What To Do Next

Now that you have everything you need, it is time to start marketing your business and getting your first customers! Remember to have all new clients sign your service agreement before starting work. 

As your business grows, you may find that you need to hire employees to start taking jobs. Don’t forget to do background checks and check references to hire trustworthy, reliable employees.

Top 10 Application Security Articles to Read Now

Introduction

Application security is a part of developing any application especially the ones that deal with user data. Staying up to date with the latest updates in security is a top priority to ensure the safety of an application. How awesome would it be to find top trending articles in one place so that you can always stay up to date with the latest trends in technology? We dug into Google Analytics to find the top 10 most popular Application Security articles at DZone. Let's get started!

10. The Bots Are Coming!

Internet of Things has to do with a vast amount of data hence security is very important or rather one of the topmost priorities. Here is an interesting article on ensuring the trustworthiness of information systems on the Internet of Things and how to protect against attacks of a global bot army.

Awesome Motive Acquires Sandhills Development

Awesome Motive, the company behind OptinMonster, WPForms, MonsterInsights, and other popular WordPress plugins, has acquired Sandhills Development. The deal includes all of the company’s WordPress products and services: Easy Digital DownloadsAffiliateWPWP Simple PaySugar CalendarWP Simple Pay, and the Payouts Service. The majority of the development team will be joining Awesome Motive to continue supporting the products.

In a personal farewell to the WordPress community, Sandhills Development founder Pippin Williamson confesses he lost his passion for WordPress and the web:

In the last few years I discovered a truth about myself: I had lost my passion for the web and building software products. I used to absolutely adore WordPress and building plugins to extend it and power businesses. That passion helped create amazing platforms that have helped tens of thousands of businesses grow, succeed, and thrive on the web, and I am so immensely proud of that. But when the passion is gone, the drive and motivation to build great things leaks away as well. It has been several years since I last felt truly inspired and motivated to build something with WordPress.

Sandhills Development has created an iconic and beloved suite of products with more than 100,000 users. Its Payouts Service paid out over a million dollars to affiliates in May and is on track to pass $2M this year. The service has more than 6,500 individuals and businesses registered and able to receive deposits and more than 1,350 businesses setup to pay their affiliates.

The financial details of the deal were not disclosed but Williamson has always been transparent about Sandhills’ financials. In last year’s summary he disclosed that the company brought in $4,331,814.12 in revenue from plugin sales, affiliate agreements, services, real estate, and payout processing, with a net profit of $232,201 after heavily investing in new projects and payroll increases.

Many of Awesome Motive’s products use EDD, so the company has a vested interest in the product’s future, alongside others in the WordPress ecosystem who depend on it. Williamson explained in his announcement why he selected Awesome Motive as the new home for his products:

Awesome Motive has been an innovator in WordPress for more than a decade and during that time they have built infrastructures, processes, and a level of polish rarely seen in the WordPress industry. The learnings and strategies that have made Awesome Motive so successful will be applied to the whole suite of Sandhills products, making the products better than ever before and at a pace previously unseen by our customers.

Despite Williamson’s professed confidence in Awesome Motive, multiple sources inside Sandhills Development expressed reservations about the deal. The company was called to an all-hands meeting where employees were given the option to jump ship or continue on with Awesome Motive.

“Well the thing that made this the most frustrating was that there was little room for discussion, or choice,” one source said. “We were given a very short heads-up (2 weeks), and no opportunity to discuss employment terms. Basically it was ‘in two weeks, you’re working for Awesome Motive, or you are out of a job.'”

Awesome Motive currently employees more than 200 people across 36 countries. For years, the company has been known for its aggressive sales tactics and upsells in the WordPress admin. These concerns, along with the change in culture from Sandhills, gave some employees reason to pause when considering the change.

“Given AM’s questionable business practices, such as using screen recorders on many employees’ laptops, trigger happy firing tendencies, and incredibly aggressive non-competes, it felt like we were being coerced to work for a company that was so, so far from the fundamental values that brought us to Sandhills in the first place,” one source within the company said. Despite this criticism, the same source said they believe “every product acquired will become considerably better,” with Awesome Motive’s investment.

“Going into the meeting with Syed, I’d describe the prevailing sentiment as cautiously optimistic,” Sandhills’ former Director of Operations Kyle Maurer said. “Obviously none of us were involved in this decision; that was Pippin only. We didn’t ask for this and didn’t know what to expect. But our many questions have been answered and at this point everyone is wholly on board. Syed’s excitement and enthusiasm are infectious and, along with his team, he’s done a tremendous job welcoming and accommodating us. It feels like new energy has been injected into the organization and I’m personally very optimistic about the future.”

Awesome Motive Founder and CEO Syed Balkhi confirmed that in the past the company has used time tracking software on its employees but “shifted away from doing so as the vast majority of our employees are on full-time salary now.”

“Many people may think of AM as one large company, but I always see us as a collection of over a dozen small companies,” Balkhi said. “Each product team operates independently and will continue to do so.”

Balkhi confirmed that no pricing changes are planned for the products. He said Awesome Motive also plans to share several internal tools the company has built for EDD to help scale the business.

Acquisitions are ramping up in the WordPress space, with major players like Automattic and hosting companies scooping up smaller businesses and plugins to create a suite of products tailored to their users. Some question whether this is a healthy part of a maturing ecosystem or a trend that may stifle the unique range of diverse, smaller products that have always been available to WordPress users.

“I know that our goal is to help small businesses grow and compete with the big guys, and our growth is a result of us living true to our mission,” Balkhi said. “We never set out to become investors.

“As you can see the products that join AM — the founders have been around for a long time and they know of us already. Founders choose to join us because we are an independent bootstrapped business not some big PE /venture-backed corporation.”

Matt Medeiros, director at Castos and creator of the Matt Report business podcast, commented on how the deal reveals the current lifecycle of WordPress companies.

“It’s quite obvious that we’re in the buying season for WordPress product companies,” Medeiros said. “If you’re a company that has built a substantial business, with a solid product, strike while the ‘buying iron’ is hot! WP products reach a certain plateau point where they have to expand wider, creating a platform of their own. When you look up at Jetpack, Elementor, AwesomeMotive, Liquid Web you have to do some serious soul searching if that’s who you want to compete against. It doesn’t take 2x the effort, it takes 50x.”

In the end, it’s the users who unwittingly drive the success of these products through their responses to the engineering, support, and marketing. Awesome Motive is retaining much of the same team behind the Sandhills products but has its own packaging, vision, and leadership that will inevitably bring changes for users down the road.

“I think users can expect to remain supported and still have a great product, but should certainly expect to be part of a bigger platform or suite of services,” Medeiros said. “Ultimately, it probably means price changes, but in reality, WP solutions have been too cheap for a while. Folks like Syed at AwesomeMotive will be able to offer end-to-end solutions for WordPress site owners, particularly small businesses. While hosting companies like Liquid Web will give you a turnkey solutions _per site_ for non-profits, e-commerce, and now online educators. Ultimately, I think we will hear less about ‘WordPress the software’ and more about the complete solution + experience companies are delivering with WordPress at its core.”

334: Custom Properties

Chris & Shaw talk about a big ol’ conversion to getting CodePen’s color system to use --custom-properties all the way through, rather than Sass variables. Why? All sorts of reasons, kinda boiling down to the fact that they are just better. Here’s a tiny one: you can use the Web Inspector and see what some other element is colored easily. Here’s a huge one: ability to do theming way easier. But the refactoring isn’t without some bumps in the road, like the fact that CSS doesn’t have a way to alter colors (like lighten, darken, or add alpha) terribly easily yet, meaning we needed some work arounds.

Time Jumps

  • 01:01 Using Sass for colors
  • 08:28 Prefixing our global variables
  • 11:39 Theming all over CodePen
  • 15:41 Switching away from Sass with colors
  • 23:18 Sponsor: Retool
  • 24:54 Future CSS Color Models coming
  • 33:10 Buttons and custom properties

Sponsor: Retool for Startups

After working with thousands of startups, we’ve noticed that technical founders spend a ton of time building internal tools—which means less time on their core product. So, we built Retool For Startups—a program that gives early-stage founders free access to a lot of the software you need for great internal tooling.

The goal is to make it 10x faster to build the admin panels, CRUD apps, and dashboards that most early stage teams need. We’ve bundled together a year of free access to Retool with over $160,000 in discounts to save you money while building with software commonly connected to internal tools like AWS, MongoDB, Brex, and Segment.

We give you a head start with pre-built UI components, integrations, and other advanced features that make building from scratch much faster. To learn more, check out our site, apply, join webinars and much more at retool.com/startups.

The post 334: Custom Properties appeared first on CodePen Blog.

<how to solve this question>

I have a problem to do price data and i don’t know to insert it into the coding

this is question
Screenshot_2021-09-23_015318.png

this is the coding that i have made

<?php

$page_title = 'Yoho Express!';

include ('includes/header.html');

?>
<form action="q2.php" method="post">
<p><h1><fieldset><legend>Enter your information in the form below:</legend></p></h1>
<p><b>Departure day:</b> 
<?php

//This programme is display in an array.
$day = array (1 =>'Select',
                  'Saturday', 
                  'Sunday', 
                  'Monday', 
                  'Tuesday',
                  'Wednesday', 
                  'Thursday', 
                  'Friday');
//the programme is display using the pull-down menu.
echo '<select name="day">';
foreach ($day as $key => $value) {
echo "<option value=\"$value\">$value</option>\n";
}
echo '</select>';

?></p>
<p><b>Departure time:</b>
<?php

//This programme is display in an array.
$time = array (1=>'Select',
                   '7:00', 
                   '10:00', 
                   '13:00', 
                   '16:00', 
                   '21:00');
//the programme is display using the pull-down menu.
echo '<select name="time">';
foreach ($time as $key => $value) {
echo "<option value=\"$value\">$value</option>\n";
}
echo '</select>';
?>
</fieldset>
 <b><p><div align="left"><input type="submit" name="submit" value="Book" /></div></b></p>
</form>

<?php
if($_SERVER['REQUEST_METHOD']=='POST'){
//handler
// Validate day
if (!empty($_POST['day'])) {
 $day = $_POST['day'];
} else {
 $day = NULL;
 echo '<p><b><font color="purple">You forgot to enter your departure day!</b></p>';
}

// Validate time
if (!empty($_POST['time'])) {
 $time = $_POST['time'];
} else {
 $time = NULL;
 echo'<p><b><font color="purple">You forgot to enter your departure time!</b></p>';
}

// Validate price
if (!empty($_POST['price'])) {
    $price = $_POST['price'];
   } else {
    price= NULL;
   }

// If everything is okay, print the message.
if ($day && $time  && $price) {
 // Print the submitted information.
  echo "<b><font color='purple'>Below are your bus ticket details </font></b></p>
 <br /><b>Day:</b>$day
 <br /><b>Time:</b>$time
 <br /><b>Price No:</b>$price";
} else {
 // One form element was not filled out properly.
 echo '<p><font color="red">Please go back and fill out the form again.</font></p>';
}
}

include('includes/footer.html');
?>

The Pros and Cons of Using a Chat API in Your App

The popularity of chat APIs has risen in recent years. An API is a system of tools that allows you to create software applications. With chat APIs, developers can integrate chat features and server infrastructure into their apps. Companies make use of this technology to help engage with customers during a sales process.

Prometheus Blackbox: What? Why? How?

Introduction

Today, Prometheus is used widely in production by organizations. In 2016, it was the second project to join CNCF and, in 2018, the second project to be graduated after Kubernetes. As the project has seen a growing commercial ecosystem of implementers and adopters, a need has emerged to address specific aspects already implemented in older monitoring tools like Nagios. Blackbox service testing is one of them.

What Is Prometheus Blackbox?

As everyone knows, Prometheus is an open-source, metrics-based monitoring system. Prometheus does one thing, and it does it well. It has a powerful data model and a query language to analyze how applications and infrastructure perform.

Use Open-Source Kubecost to Understand (and Control) Kubernetes Spending

Many organizations deploying and quickly scaling Kubernetes struggle to understand how their cloud spend is actually, well, being spent. Precise visibility into which teams, projects, or applications are spending what amount on which infrastructure services is difficult to achieve. This black box of understanding has bigger implications, of course, as Kubernetes environments grow. 

(For more data on this problem, check out the Cloud Native Computing Foundation’s recent – and first-ever – report into FinOps for Kubernetes.)

Getting Your `head` Straight: A New CSS Performance Diagnostics Snippet

There are plenty of ways to detect performance bottlenecks and audit CSS. We can look into common performance bottlenecks and the complexity of stylesheets, the way we load assets, and the order in which it happens.

One helpful way to spot common problems easily is to use some sort of a performance diagnostics CSS — a dedicated stylesheet that highlights potential problems and errors.

Today, during his talk at Webexpo Prague 2021, Harry Roberts, a web performance consultant and front-end engineer, introduced a little helper that helps him spot common performance bottlenecks easily. And that is mostly related to the order of how assets are loaded in the <head>.

As Harry says,

“I spend a lot of my time looking through clients’ <head> tags to ensure everything in there is in the best possible shape it can be. There are a lot of complex and often conflicting rules that constitute ‘good’ <head> tags, and cross-referencing everything can soon grow unwieldy, so to make my life easier, I developed ct.css — a quick and dirty way of seeing inside of your <head>.”

ct.css is a little diagnostic snippet, named after Computed Tomography (CT) scans, that exposes potential performance issues in your page’s <head> tags, and will disappear as soon as you’ve fixed them.

Harry has put all the insights he’s learned from his performance work to a perfect <head> order, and the tool exposes some of the issues that often result from a suboptimal arrangement of <head> tags.

With the bookmarklet in the browser’s toolbar, browse to a website of your choice, click or activate the bookmarklet, and the tool highlights useful pointers for you to double-check when working around performance bottlenecks. Just a little helper to make your work a bit easier, and find all those hidden issues faster.

If you just want to play with the snippet, you can get it at csswizardry.com/ct. Happy debugging, everyone!

Selenium WebDriver with Python for Web Automation Testing

Introduction

In the agile environment, developers need to run relevant cross-browser tests to push any front-end changes quickly. While small projects use manual testing, larger projects need automation because of the increasing number of web browsers. How is this done using Selenium WebDriver and Python? Selenium is one of the most popular open-source web automation testing tools available today. 

Python on the other hand is picking up steam since the last decade and is highly favored among testers for automation testing, security testing, extracting data from the web, etc. Let us look at a step-by-step guide highlighting how to perform Web automation testing using Selenium WebDriver and Python and try to answer why Selenium and Python make a formidable pact? Can we use Python in Selenium WebDriver? etc., as we move ahead in this article.