What Is a Smart Contract and Where to Use It?

Featured Imgs 23
What Is a Smart Contract and Where to Use It?

The concept of smart contracts is not a new one and was introduced by cryptography experts 20 years ago. But the realization of these ideas in practice became possible only with the development of blockchain technology, which is compatible with all the necessary conditions for their execution.

Recently, smart contracts became a well-known opportunity to exchange existing assets like money, shares, and other property types without any intermediaries. In this article, we want to show how can the smart contract be used for your business.

What Is a Smart Contract?

A smart contract is a self-executing agreement built on the blockchain. It allows conducting transactions directly without the participation of third parties. Plus, because the data on the blockchain cannot be changed or manipulated by anyone - smart contracts built trust and transparency between parties since neither side can play with the contract terms.

What Is a Smart Contract and Where to Use It?

In some way, smart contracts became a logical development of blockchain technology after the emergence of cryptocurrencies. Nick Szabo first described smart contract technology in the 1990s. He defined smart contracts as a tool that formalizes and secures computer networks by combining protocols with a user interface. However, the practical implementation became possible with the advent of the blockchain in 2008.

Blockchain made it possible to get rid of the involvement of third parties and build a reliable system for creating automated contracts. Thanks to a decentralized blockchain system, the code can’t be arbitrarily changed or prevented from being executed without interfering with the entire network. So, a smart contract is managed only by the rules laid down in it.

How Do Smart Contracts Work?

In simple terms, a smart contract works like a deterministic algorithm. It performs certain actions when specified conditions are met. Based on this, the smart contract system often uses "if… then…" expressions. For example, if Party A transfers money, then Party B transfers item/property rights.

A classic example of a smart contract is a vending machine. A person puts the coin into the machine to get a drink or a snack. This interaction is an agreement that involves the purchase of the product for a set amount of money. The difference between our example and the traditional contract is that the machine self-executes the terms of agreement and transaction: if the payment has passed, then the machine provides a drink/snack.

A smart contract is the same as a traditional one, except that there is no need for trust between parties. Each party of the contract must trust the other party, hoping that he will fulfill the obligations of the agreement. The terms of the smart contract are executed automatically by a computer program without any exceptions. As soon as certain contract conditions are met, the smart contract executes the transaction and guarantees. Thus, a bet between two people about what the weather will be like tomorrow is another good example of a smart contract.

What Is a Smart Contract and Where to Use It?

The primary platform for the implementation of smart contracts is Ethereum, as it provides the most opportunities for their realization. Using this system as an example, the way smart contracts work can be explained as follows:

  • The asset is introduced into the program and it independently monitors compliance with the contract terms;

  • Upon execution, the seller receives money, and the buyer – the goods.

In the Ethereum network, smart contracts are responsible for performing transactions between users (addresses). Any address that is not a smart contract is called a personal account (EOA). Thus, smart contracts are controlled by software code, and personal accounts are controlled by users.

Essentially, Ethereum smart contracts consist of a contract code (containing execution conditions) and two public keys. The first public key is provided by the creator of the contract. Another key is the contract itself, being a digital identifier unique to each smart contract.

The execution of any smart contract occurs during a blockchain transaction, and it can be activated when initiated by a personal account (or other smart contract). However, a sequence of smart contracts is always launched from a personal account (i.e., by a user).

The structure of any smart contract includes the following attributes:

  • The contract parties that have accepted the agreed conditions (for this, an electronic signature or multi-signatures, if there are several parties, is used);

  • The environment in which the contract will be located (for example, Ethereum);

  • The subject of the contract – namely, resources for exchange;

  • Terms of the contract – a description of the mathematically confirmed conditions under which the contract will be considered as fulfilled.

A smart contract will store all of the listed funds until the set goal is reached. If the goal is not achieved, then the money is returned to investors.

ERC-20

Tokens issued on the Ethereum blockchain comply with the standard also known as ERC-20. This standard describes the basic functions of all tokens based on the Ethereum network. These types of digital assets are often referred to as ERC-20 tokens and represent most of the cryptocurrencies in existence.

Many blockchain companies and startups are developing smart contracts to issue their digital tokens on the Ethereum network. After some sort of issuance, most of these companies distribute their ERC-20 tokens through an Initial Coin Offering (ICO). In most cases, the use of smart contracts made it possible to exchange funds and distribute tokens in a trusting and efficient manner.

What Is a Smart Contract and Where to Use It?

How Smart Contracts Can Be Used?

Since the smart contract is a transaction protocol, they are highly customizable and can be developed for different types of services and solutions.

As a decentralized and self-executing program, smart contracts can provide increased transparency and lower operational costs. Depending on the type of business, they can also improve efficiency and reduce costs. The benefits of smart contracts are particularly evident when it comes to money transfers or exchanges of funds between two or more parties.

In other words, smart contracts can be designed for a wide variety of use cases. Some of the examples include the creation of tokenized assets or shares, voting systems, cryptocurrency wallets, decentralized exchanges, games, and mobile applications. They can also be co-implemented, along with other blockchain solutions that address areas such as healthcare, supply chain, government, and decentralized finance (DeFi).

In the twenty-first century, there is the possibility of translating all kinds of paper contracts into digital smart contracts, and therefore a wide range of potential applications is emerging. Let’s consider some of them:

Automation of payments: the contract can be programmed to ensure that the requested amount arrives at the specified time to the specified persons or organizations.

Registration and change of ownership: The necessary documents can be registered on the blockchain to establish ownership from the start and change ownership through smart contracts.

Energy Transactions: This is believed to create a digital ecosystem for the exchange of energy. Thus, the sources of electricity or fuel will be associated with smart contracts concluded only between individuals or with organizations involved, which, in turn, can personalize the consumption of each client.

Intellectual property: You can embed a smart contract in any object that is digitally controlled. This is where the smart property is born that can be assimilated with networked IoT objects. They can range from home to cars. In this way, for example, the rental of these properties can be automated.

Also, cryptocurrencies such as Bitcoin can be viewed as a set of smart contracts that enforce property law. Cryptographic techniques are used to ensure that only the owner of the digital token can spend them. Several decentralized asset markets already exist, so that many different digital assets can be traded on the same blockchain. The same principle can be extended to physical products with electronic control or embedded microchips.

Financial Services: Cryptocurrencies obviously open up a wide range of different use cases for smart contracts that would not otherwise be possible. For example, systems like the one used by BurstCoin can run auctions that automatically check for the highest price at a given time and automatically transfer inactive funds.

Pros and Cons of Smart Contracts

Compared to traditional contracts, smart contracts have many advantages, and the most important of them is autonomy. Smart contracts are concluded by two parties, no intermediaries, and the blockchain ensures the implementation of the agreement. You don’t have to spend money on the services of a lawyer or notary. Also, you can be sure that no one will deceive you and the terms of the contract will be fulfilled.

Another advantage is speed. In smart contracts, all stages are as automated as possible and require the presence of a person only at the initial stages of creation. This significantly saves the parties time and speeds up the processing of documents.

Smart contracts are secure, as is the blockchain itself. The data recorded in the blockchain can’t be changed or destroyed, which imposes obligations on the parties. If one party didn’t fulfill its obligations, the other party would be protected by the terms of the contract anyway.

Cost reduction is what makes blockchain so attractive. Using smart contracts you save on involving additional specialists (lawyers, notaries, brokers), as well as on operating expenses. Such savings enable the parties to conclude an agreement on more favorable terms.

Nevertheless, this mechanism does have its drawbacks, like:

  • Legal status. Blockchain and cryptocurrencies are relatively new tools and in most countries, their legal status is not yet completely defined.

  • Creation complexity. They are based on the program code, which already creates difficulties for the average person. Also, when creating a smart contract, you need to provide several conditions and scenarios for the transaction, which is time-consuming.

  • Gas consumption. With every transaction client pays the fee, in gas, in order to execute so-called smart contract functions. On the Ethereum blockchain, gas is an execution fee used to compensate miners for the resources required to power smart contracts. And since network usage is progressively increasing, the gas costs are being millions of dollars per day. As the ecosystem continues to grow, so too will the value of gas optimization.

  • No flexibility. The data included in the blockchain can’t be changed during the interaction.

  • Innovative technology. Most people still do not clearly understand what smart contracts are and this prevents them from actively spreading.

Despite all the problems described, most experts agree that smart contracts are headed in a very promising direction and they have great potential to take a foothold in our lives in the future.

Smart Contract Market Forecast

Global Smart Contracts Market is expected to reach approximately 300 USD Million by the end of 2023 with 32% CAGR during the forecasted period from 2017 – 2023. The same research shows that Europe is the market leader for smart contracts. However, in the forecast period, North America is showing significant growth. This has greatly expanded the use of digital technology in countries such as the United States, China, Britain, and Japan.

What Is a Smart Contract and Where to Use It?

Market players in the regions are actively focusing on product innovation and implementing strategies that allow them to consolidate their market position. Many companies are also investing in mergers and acquisitions.

Final Thoughts

The creation of smart contracts is quite a new direction and certainly one of the most important technologies implemented in the blockchain. It clearly exceeds those centralized systems that are now used in many economic sectors. So, smart contracts introduce the new vision of running the business in various sectors.

Obviously, such benefits as cost savings, time-saving, security, and eliminating the need for intermediaries will contribute to the technology being distributed all over the world. If you are looking for a reliable partner to implement smart contracts in your business or you simply have a question about smart contracts, drop us a line in a contact form and we will help you!

10 Tips For Better Book Designs

Featured Imgs 23

Creating a book or textbook is a production that requires time and patience. In order to make a better book that engages the reader, you need to think about a number of things, such as the visual appeal of the book and making it more readable. Not only is the book design of great importance, but as the graphic designer, you have to be ready to discuss design points with the client and editor to make a book of the highest quality.

In order to publish a book or stunning book design that everyone loves, here are some tips for you:

 

1. Simple and Clear Numbering

Make sure you are using page numbers and chapter numbers in such a way that people understand where they are in the textbook. Readers should be able to figure out the page they are on easily and navigate without issues. You may also want to consider how you number prologue or introduction pages to separate them from the main text. Some people use Roman numerals (I-X), but Arabic numbers (0-9) may be more clear for certain age groups. 

Relevant: Top 10 Mistakes Ottawa Businesses Make on Graphic Design Projects

2. Running Heads

A running head is common practice. What this means is that, on the left page, you will see the title of the book; the right page contains the chapter number and/or chapter title. This is more than aesthetic. Readers can use the page number, book title, and chapter title to find information in the book. If the text gets photocopied or split up as a PDF, it’s easy to cite the information, too. 

3. Word Spacing

No one wants to read paragraph after paragraph when the text is either smashed together or spaced too far apart. Consider word spacing very carefully. Since nearly every font has its own unique spacing, you will have to adjust accordingly. A general rule of thumb is reducing the word spacing to around 90% for a tight line and less gaps in a single sentence. 

4. Make Gutters Right

Think about all those times when you were given a handout or opened a textbook that had been bound so closely together that you couldn’t read the words at the crease. This often happens because the right hand (recto) or left hand (verso) side of the page is too close to the gutter. How do you avoid such an issue?

You make sure that the gutter is wide enough. For a perfectly bound textbook, make the gutters no less than 25mm on either side. The other factor to consider is how the book is being bound. For example, if a book is bound with cold melt glue, the book will lay flat, making text easier to read. A hot melt glue, on the other hand, dries stiff, making it more difficult to open the gutter and read the words. 

5. Character Spacing

Similar to word spacing, you also want to think about the proximity of every character in relation to one another. Again, this depends largely on the font you’re working with. Avoid squishing letters too close together, making the words look too dark from a distance. If you’re working with Adobe InDesign, aim for -3%; use 0.6% for QuarkXPress.

6. Easier-to-Read Tables

The best method for creating an easily legible table is to space horizontal columns with about 5mm between them and no less. Doing so makes horizontal tables less confusing to read. People will be able to link the information from one page to another, as well. 

7. Paper Choice

Despite being in the age of electronic publications, many people still love the feel of paper pages between their fingers. Therefore, it’s more important than ever to consider how the pages feel. Bright white pages are less appealing than off-white paper. Plus, it is easier for people to focus on the text. 

8. Contrast

As we started mentioning in the point above, you want less of a contrast between the color of the font and the paper. However, if you plan on targeting the population with visual impairments, the opposite holds true. You will want more contrast to help people see the shapes of the letters. 

Yet, this isn’t necessarily true for the dyslexic population. A high contrast makes words look blurry and harder to discern. Because of this, dyslexic individuals often use a colored acetate overlay to read printed text. 

9. Make Suggestions to Clients

Any design is a collaboration between the client, the designer, and other team members. Some clients are far more open to suggestions than others, and you may have to develop a relationship with the client before they listen to you. That said, you should openly discuss your thoughts and feelings about the design. If you are unsure of something, ask. It would be disappointing for the book to be published, only for there to be a design problem that hinders its success. 

10. Ask for Feedback

Although designers often want to let their creativity go when it comes to books, so many of them are published in a cookie-cutter fashion. Because of that, more books get seen by the editor, designer, and producers but never get discussed or tested by those who matter most—the readers! 

If you want to create an amazing book design, you should consider the individuals most likely to pick the book up in the first place. Ask a small test group what they think of the design. What would they change? Have them send you feedback. 

You never know how people will respond. Sometimes, you get very detailed and helpful feedback that could make the book all the more successful. 

Conclusion

Textbooks—and all books—are just as difficult to construct and publish as works of fiction or poetry. There are many factors to consider when you start designing a book, including readability. You want to make sure that things like wording and kerning are dealt with long before production. Keeping such things in mind will help you create a better book.

what is the answer?

558fe5180e0e8fc922d31c23ef84d240

There are 3 different types of tags in a library: red, green, blue.

There are two different arrangement methods planned for the arrangement of the shelves, and 42 books can be arranged on these shelves. ( mathematical)

Lineup A: Red, green, blue books will be lined up in a row on a shelf.

Arrangement B: First, the red, then the green, and the last, the blue books will be lined up in an equal number on a shelf.

Use mathematical operations methods when writing the codes for this problem (eg addExact(a,b) instead of a+b)

Which transactions are deadlocked?

Category Image 101

Our database is running into problems, as many transactions are waiting for locks held by other transactions. Here is what each transaction is waiting for:

T1 is waiting on T4

T5 is waiting on T8

T2 is waiting on T7

T6 is waiting on T2

T3 is waiting on T2

T7 is waiting on T6

T4 is waiting on T1

T8 is not waiting

Which transactions are deadlocked?

#318: Anna Lytical on What CodePen Is

Featured Imgs 23

When Anna Lytical heard Stephen and I talking about “What is CodePen?” she mentioned we did fab without her. So of course, I had to do one with her! Anna creates fun coding content all over the web, in addition to being an engineer at Google. Catch her on YouTube, Instagram, TikTok, and Twitter. For Anna, the appeal of CodePen is in the simplicity: nothing to set up, easy/free to get started, and you can get to the heart of learning quickly. Not to mention the sharing—as a teacher you can provide code as simply as sharing a URL. And of course, all the existing code to be inspired by!

Timestamps

  • 00:31 Guest introduction
  • 03:05 Taking part in building the technology around us
  • 05:20 What is drag?
  • 07:08 How to pick a platform to share content on
  • 13:03 Sponsor: Netlify
  • 14:59 Changing the bar for learning
  • 17:06 Using CodePen to teach code
  • 19:59 GitHub vs CodePen
  • 23:33 What’s your incentive to keep going with this?

Sponsor: Netlify

Did you see that Netlify bought FeaturePeek and rolled into into all Deploy Previews? They did! It’s cool! Imagine you need to make a change to a website, and need approval from a client first. You can do a Pull Request against the site and your Netlify-hosted site will give you a URL with a Deploy Preview. They’ve done that forever, and it’s incredibly useful. Now, it’s even more useful, as that client can open up a little UI widget on the Deploy Preview and give feedback. They don’t need to know anything about GitHub, yet their feedback can manifest as a GitHub Issue. And that’s just one possible integration.

The post #318: Anna Lytical on What CodePen Is appeared first on CodePen Blog.

A Crash Course in WordPress Block Filters

Category Image 052

Blocks in WordPress are great. Drop some into the page, arrange them how you like, and you’ve got a pretty sweet landing page with little effort. But what if the default blocks in WordPress need a little tweaking? Like, what if we could remove the alignment options in the Cover block settings? Or how about control sizing for the Button block?

There are plenty of options when it comes to extending the functionality of core blocks in WordPress. We can add a custom CSS class to a block in the editor, add a custom style, or create a block variation. But even those might not be enough to get what you need, and you find yourself needing to filter the core block to add or remove features, or building an entirely new block from scratch.

I’ll show you how to extend core blocks with filters and also touch on when it’s best to build a custom block instead of extending a core one.

A quick note on these examples

Before we dive in, I’d like to note that code snippets in this article are taken out of context on purpose to focus on filters rather than build tools and file structure. If I included the full code for the filters, the article would be hard to follow. With that said, I understand that it’s not obvious for someone who is just starting out where to put the snippets or how to run build scripts and make the whole thing work.

To make things easier for you, I made a WordPress plugin with examples from this article available on my GitHub. Feel free to download it and explore the file structure, dependencies and build scripts. There is a README that will help you get started.

Block filters in an nutshell

The concept of filters is not new to WordPress. Most of us are familiar with the add_filter() function in PHP. It allows developers to modify various types of data using hooks.

A simple example of a PHP filter could look something like this:

function filter_post_title( $title ){
  return '<strong>' . $title . '</strong>';
};

add_filter( 'the_title',  'filter_post_title' );

In this snippet, we create a function that receives a string representing a post title, then wrap it in a <strong> tag and return a modified title. We then use add_filter() to tell WordPress to use that function on a post title.

JavaScript filters work in a similar way. There is a JavaScript function called addFilter() that lives in the wp.hooks package and works almost like its PHP sibling. In its simplest form, a JavaScript filter looks something like this:

function filterSomething(something) {
  // Code for modifying something goes here.
  return something;
}

wp.hooks.addFilter( 'hookName', 'namespace', filterSomething );

Looks pretty similar, right? One notable difference is addFilter() has a namespace as a second argument. As per the WordPress Handbook, “Namespace uniquely identifies a callback in the the form vendor/plugin/function.” However, examples in the handbook follow different patterns: plugin/what-filter-does or plugin/component-name/what-filter-does. I usually follow the latter because it keeps the handles unique throughout the project.

What makes JavaScript filters challenging to understand and use is the different nature of what they can filter. Some filter strings, some filter JavaScript objects, and others filter React components and require understanding the concept of Higher Order Components.

On top of that, you’ll most likely need to use JSX which means you can’t just drop the code into your theme or plugin and expect it to work. You need to transpile it to vanilla JavaScript that browsers understand. All that can be intimidating at the beginning, especially if you are coming from a PHP background and have limited knowledge of ES6, JSX, and React.

But fear not! We have two examples that cover the basics of block filters to help you grasp the idea and feel comfortable working with JavaScript filters in WordPress. As a reminder, if writing this code for the Block Editor is new to you, explore the plugin with examples from this article.

Without any further ado, let’s take a look at the first example.

Removing the Cover block’s alignment options

We’re going to filter the core Cover block and remove the Left, Center, Right, and Wide alignment options from its block settings. This may be useful on projects where the Cover block is only used as a page hero, or a banner of some sort and does not need to be left- or right-aligned.

We’ll use the blocks.registerBlockType filter. It receives the settings of the block and its name and must return a filtered settings object. Filtering settings allows us to update the supports object that contains the array of available alignments. Let’s do it step-by-step.

We’ll start by adding the filter that just logs the settings and the name of the block to the console, to see what we are working with:

const { addFilter } = wp.hooks;

function filterCoverBlockAlignments(settings, name) {
  console.log({ settings, name });
  return settings;
}

addFilter(
  'blocks.registerBlockType',
  'intro-to-filters/cover-block/alignment-settings',
  filterCoverBlockAlignments,
);

Let’s break it down. The first line is a basic destructuring of the wp.hooks object. It allows us to write addFilter() in the rest of the file, instead of wp.hooks.addFilter(). This may seem redundant in this case, but it is useful when using multiple filters in the same file (as we’ll get to in the next example).

Next, we defined the filterCoverBlockAlignments() function that does the filtering. For now, it only logs the settings object and the name of the block to the console and returns the settings as is.

All filter functions receive data, and must return filtered data. Otherwise, the editor will break.

And, lastly, we initiated the filter with addFilter() function. We provided it with the name of the hook we are going to use, the filter namespace, and a function that does the filtering.

If we’ve done everything right, we should see a lot of messages in the console. But note that not all of them refer to the Cover block.

This is correct because the filter is applied to all blocks rather than the specific one we want. To fix that, we need to make sure that we apply the filter only to the core/cover block:

function filterCoverBlockAlignments(settings, name) {
  if (name === 'core/cover') {
    console.log({ settings, name });
  }
  return settings;
}

With that in place, we should see something like this now in the console:

Don’t worry if you see more log statements than Cover blocks on the page. I have yet to figure out why that’s the case. If you happen to know why, please share in the comments!

And here comes the fun part: the actual filtering. If you have built blocks from scratch before, then you know that alignment options are defined with Supports API. Let me quickly remind you how it works — we can either set it to true to allow all alignments, like this:

supports: {
  align: true
}

…or provide an array of alignments to support. The snippet below does the same thing, as the one above:

supports: {
  align: [ 'left', 'right', 'center', 'wide', 'full' ]
}

Now let’s take a closer look at the settings object from one of the console messages we have and see what we are dealing with:

All we need to do is replace align: true with align: ['full'] inside the supports property. Here’s how we can do it:

function filterCoverBlockAlignments(settings, name) {
  if (name === 'core/cover') {
    return assign({}, settings, {
      supports: merge(settings.supports, {
        align: ['full'],
      }),
    });
  }
  return settings;
}

I’d like to pause here to draw your attention to the assign and merge lodash methods. We use those to create and return a brand new object and make sure that the original settings object remains intact. The filter will still work if we do something like this:

/* 👎 WRONG APPROACH! DO NOT COPY & PASTE! */
settings.supports.align = ['full'];
return settings;

…but that is an object mutation, which is considered a bad practice and should be avoided unless you know what you are doing. Zell Liew discusses why mutation can be scary over at A List Apart.

Going back to our example, there should now only be one alignment option in the block toolbar:

I removed the “center” alignment option because the alignment toolbar allows you to toggle the alignment “on” and “off.” This means that Cover blocks now have default and “Full width” states.

And here’s the full snippet:

const { addFilter } = wp.hooks;
const { assign, merge } = lodash;

function filterCoverBlockAlignments(settings, name) {
  if (name === 'core/cover') {
    return assign({}, settings, {
      supports: merge(settings.supports, {
        align: ['full'],
      }),
    });
}
  return settings;
}

addFilter(
  'blocks.registerBlockType',
  'intro-to-filters/cover-block/alignment-settings',
  filterCoverBlockAlignments,
);

This wasn’t hard at all, right? You are now equipped with a basic understanding of how filters work with blocks. Let’s level it up and take a look at a slightly more advanced example.

Adding a size control to the Button block

Now let’s add a size control to the core Button block. It will be a bit more advanced as we will need to make a few filters work together. The plan is to add a control that will allow the user to choose from three sizes for a button: Small, Regular, and Large.

The goal is to get that new “Size settings” section up and running.

It may seem complicated, but once we break it down, you’ll see that it’s actually pretty straightforward.

1. Add a size attribute to the Button block

First thing we need to do is add an additional attribute that stores the size of the button. We’ll use the already familiar blocks.registerBlockType filter from the previous example:

/**
 * Add Size attribute to Button block
 *
 * @param  {Object} settings Original block settings
 * @param  {string} name     Block name
 * @return {Object}          Filtered block settings
 */
function addAttributes(settings, name) {
  if (name === 'core/button') {
    return assign({}, settings, {
      attributes: merge(settings.attributes, {
        size: {
          type: 'string',
          default: '',
        },
      }),
    });
  }
  return settings;
}

addFilter(
  'blocks.registerBlockType',
  'intro-to-filters/button-block/add-attributes',
  addAttributes,
);

The difference between what we’re doing here versus what we did earlier is that we’re filtering attributes rather than the supports object. This snippet alone doesn’t do much and you won’t notice any difference in the editor, but having an attribute for the size is essential for the whole thing to work.

2. Add the size control to the Button block

We’re working with a new filter, editor.BlockEdit. It allows us to modify the Inspector Controls panel (i.e. the settings panel on the right of the Block editor).

/**
 * Add Size control to Button block
 */
const addInspectorControl = createHigherOrderComponent((BlockEdit) => {
  return (props) => {
    const {
      attributes: { size },
      setAttributes,
      name,
    } = props;
    if (name !== 'core/button') {
      return <BlockEdit {...props} />;
    }
    return (
      <Fragment>
        <BlockEdit {...props} />
        <InspectorControls>
          <PanelBody
            title={__('Size settings', 'intro-to-filters')}
            initialOpen={false}
          >
            <SelectControl
              label={__('Size', 'intro-to-filters')}
              value={size}
              options={[
                {
                  label: __('Regular', 'intro-to-filters'),
                  value: 'regular',
                },
                {
                  label: __('Small', 'intro-to-filters'),
                  value: 'small'
                },
                {
                  label: __('Large', 'intro-to-filters'),
                  value: 'large'
                },
              ]}
              onChange={(value) => {
                setAttributes({ size: value });
              }}
            />
          </PanelBody>
      </InspectorControls>
      </Fragment>
    );
  };
}, 'withInspectorControl');

addFilter(
  'editor.BlockEdit',
  'intro-to-filters/button-block/add-inspector-controls',
  addInspectorControl,
);

This may look like a lot, but we’ll break it down and see how straightforward it actually is.

The first thing you may have noticed is the createHigherOrderComponent construct. Unlike other filters in this example, editor.BlockEdit receives a component and must return a component. That’s why we need to use a Higher Order Component pattern derived from React.

In its purest form, the filter for adding controls looks something like this:

const addInspectorControl = createHigherOrderComponent((BlockEdit) => {
  return (props) => {
    // Logic happens here.
    return <BlockEdit {...props} />;
  };
}, 'withInspectorControl');

This will do nothing but allow you to inspect the <BlockEdit /> component and its props in the console. Hopefully the construct itself makes sense now, and we can keep breaking down the filter.

The next part is destructuring the props:

const {
  attributes: { size },
  setAttributes,
  name,
} = props;

This is done so we can use name, setAttributes, and size in the scope of the filter, where:

  • size is the attribute of the block that we’ve added in step 1.
  • setAttributes is a function that lets us update the block’s attribute values.
  • name is a name of the block. which is core/button in our case.

Next, we avoid inadvertantly adding controls to other blocks:

if (name !== 'core/button') {
  return <BlockEdit {...props} />;
}

And if we are dealing with a Button block, we wrap the settings panel in a <Fragment /> (a component that renders its children without a wrapping element) and add an additional control for picking the button size:

return (
  <Fragment>
    <BlockEdit {...props} />
    {/* Additional controls go here */}
  </Fragment>
);

Finally, additional controls are created like this:

<InspectorControls>
  <PanelBody title={__('Size settings', 'intro-to-filters')} initialOpen={false}>
    <SelectControl
      label={__('Size', 'intro-to-filters')}
      value={size}
      options={[
        { label: __('Regular', 'intro-to-filters'), value: 'regular' },
        { label: __('Small', 'intro-to-filters'), value: 'small' },
        { label: __('Large', 'intro-to-filters'), value: 'large' },
      ]}
      onChange={(value) => {
        setAttributes({ size: value });
      }}
    />
  </PanelBody>
</InspectorControls>

Again, if you have built blocks before, you may already be familiar with this part. If not, I encourage you to study the library of components that WordPress comes with.

At this point we should see an additional section in the inspector controls for each Button block:

We are also able to save the size, but that won’t reflect in the editor or on the front end. Let’s fix that.

3. Add a size class to the block in the editor

As the title suggests, the plan for this step is to add a CSS class to the Button block so that the selected size is reflected in the editor itself.

We’ll use the editor.BlockListBlock filter. It is similar to editor.BlockEdit in the sense that it receives the component and must return the component; but instead of filtering the block inspector panel, if filters the block component that is displayed in the editor.

import classnames from 'classnames';
const { addFilter } = wp.hooks;
const { createHigherOrderComponent } = wp.compose;

/**
 * Add size class to the block in the editor
 */
const addSizeClass = createHigherOrderComponent((BlockListBlock) => {
  return (props) => {
    const {
      attributes: { size },
      className,
      name,
    } = props;

    if (name !== 'core/button') {
      return <BlockListBlock {...props} />;
    }

    return (
      <BlockListBlock
        {...props}
        className={classnames(className, size ? `has-size-${size}` : '')}
      />
    );
  };
}, 'withClientIdClassName');

addFilter(
   'editor.BlockListBlock',
   'intro-to-filters/button-block/add-editor-class',
   addSizeClass
);

You may have noticed a similar structure already:

  1. We extract the size, className, and name variables from props.
  2. Next, we check if we are working with core/button block, and return an unmodified <BlockListBlock> if we aren’t.
  3. Then we add a class to a block based on selected button size.

I’d like to pause on this line as it may look confusing from the first glance:

className={classnames(className, size ? `has-size-${size}` : '')}

I’m using the classnames utility here, and it’s not a requirement — I just find using it a bit cleaner than doing manual concatenations. It prevents me from worrying about forgetting to add a space in front of a class, or dealing with double spaces.

4. Add the size class to the block on the front end

All we have done up to this point is related to the Block Editor view, which is sort of like a preview of what we might expect on the front end. If we change the button size, save the post and check the button markup on the front end, notice that button class is not being applied to the block.

To fix this, we need to make sure we are actually saving the changes and adding the class to the block on the front end. We do it with blocks.getSaveContent.extraProps filter, which hooks into the block’s save() function and allows us to modify the saved properties. This filter receives block props, the type of the block, and block attributes, and must return modified block props.

import classnames from 'classnames';
const { assign } = lodash;
const { addFilter } = wp.hooks;

/**
 * Add size class to the block on the front end
 *
 * @param  {Object} props      Additional props applied to save element.
 * @param  {Object} block      Block type.
 * @param  {Object} attributes Current block attributes.
 * @return {Object}            Filtered props applied to save element.
 */
function addSizeClassFrontEnd(props, block, attributes) {
  if (block.name !== 'core/button') {
    return props;
  }

  const { className } = props;
  const { size } = attributes;

  return assign({}, props, {
    className: classnames(className, size ? `has-size-${size}` : ''),
  });
}

addFilter(
  'blocks.getSaveContent.extraProps',
  'intro-to-filters/button-block/add-front-end-class',
  addSizeClassFrontEnd,
);

In the snippet above we do three things:

  1. Check if we are working with a core/button block and do a quick return if we are not.
  2. Extract the className and size variables from props and attributes objects respectively.
  3. Create a new props object with an updated className property that includes a size class if necessary.

Here’s what we should expect to see in the markup, complete with our size class:

<div class="wp-block-button has-size-large">
  <a class="wp-block-button__link" href="#">Click Me</a>
</div>

5. Add CSS for the custom button sizes

One more little thing before we’re done! The idea is to make sure that large and small buttons have corresponding CSS styles.

Here are the styles I came up with:

.wp-block-button.has-size-large .wp-block-button__link {
  padding: 1.5rem 3rem;
}
.wp-block-button.has-size-small .wp-block-button__link {
  padding: 0.25rem 1rem;
}

If you are building a custom theme, you can include these front-end styles in the theme’s stylesheet. I created a plugin for the default Twenty Twenty One theme, so, in my case, I had to create a separate stylesheet and include it using wp_enqueue_style(). You could just as easily work directly in functions.php if that’s where you manage functions.

function frontend_assets() {
  wp_enqueue_style(
    'intro-to-block-filters-frontend-style',
    plugin_dir_url( __FILE__ ) . 'assets/frontend.css',
    [],
    '0.1.0'
  );
}
add_action( 'wp_enqueue_scripts', 'frontend_assets' );

Similar to the front end, we need to make sure that buttons are properly styled in the editor. We can include the same styles using the enqueue_block_editor_assets action:

function editor_assets() {
  wp_enqueue_style(
    'intro-to-block-filters-editor-style',
    plugin_dir_url( __FILE__ ) . 'assets/editor.css',
    [],
    '0.1.0'
  );
}
add_action( 'enqueue_block_editor_assets', 'editor_assets' );

We should now should have styles for large and small buttons on the front end and in the editor!

As I mentioned earlier, these examples are available in as a WordPress plugin I created just for this article. So, if you want to see how all these pieces work together, download it over at GitHub and hack away. And if something isn’t clear, feel free to ask in the comments.

Use filters or create a new block?

This is a tricky question to answer without knowing the context. But there’s one tip I can offer.

Have you ever seen an error like this?

It usually occurs when the markup of the block on the page is different from the markup that is generated by the block’s save() function. What I’m getting at is it’s very easy to trigger this error when messing around with the markup of a block with filters.

So, if you need to significantly change the markup of a block beyond adding a class, I would consider writing a custom block instead of filtering an existing one. That is, unless you are fine with keeping the markup consistent for the editor and only changing the front-end markup. In that case, you can use PHP filter.

Speaking of which…

Bonus tip: render_block()

This article would not be complete without mentioning the render_block hook. It filters block markup before it’s rendered. It comes in handy when you need to update the markup of the block beyond adding a new class.

The big upside of this approach is that it won’t cause any validation errors in the editor. That said, the downside is that it only works on the front end. If I were to rewrite the button size example using this approach, I would first need to remove the code we wrote in the fourth step, and add this:

/**
 * Add button size class.
 *
 * @param  string $block_content Block content to be rendered.
 * @param  array  $block         Block attributes.
 * @return string
 */
function add_button_size_class( $block_content = '', $block = [] ) {
  if ( isset( $block['blockName'] ) && 'core/button' === $block['blockName'] ) {
    $defaults = ['size' => 'regular'];
    $args = wp_parse_args( $block['attrs'], $defaults );

    $html = str_replace(
      '<div class="wp-block-button',
      '<div class="wp-block-button has-size-' . esc_attr( $args['size']) . ' ',
      $block_content
    );

    return $html;
}
  return $block_content;
}

add_filter( 'render_block', 'add_button_size_class', 10, 2 );

This isn’t the cleanest approach because we are injecting a CSS class using str_replace() — but that’s sometimes the only option. A classic example might be working with a third-party block where we need to add a <div> with a class around it for styling.

Wrapping up

WordPress block filters are powerful. I like how it allows you to disable a lot of unused block options, like we did with the Cover block in the first example. This can reduce the amount of CSS you need to write which, in turn, means a leaner stylesheet and less maintenance — and less cognitive overhead for anyone using the block settings.

But as I mentioned before, using block filters for heavy modifications can become tricky because you need to keep block validation in mind.

That said, I usually reach for block filters if I need to:

  • disable certain block features,
  • add an option to a block and can’t/don’t want to do it with custom style (and that option must not modify the markup of the block beyond adding/removing a custom class), or
  • modify the markup only on the front end (using a PHP filter).

I also usually end up writing custom blocks when core blocks require heavy markup adjustments both on the front end and in the editor.

If you have worked with block filters and have other thoughts, questions, or comments, let me know!

Resources


The post A Crash Course in WordPress Block Filters appeared first on CSS-Tricks.

You can support CSS-Tricks by being an MVP Supporter.

Unable to pop out value from Stack-CPU Sim

558fe5180e0e8fc922d31c23ef84d240

am using CPU Sim to change wombat1 to wombat2 by adding stack.

I have done adding a Stack RAM and a Stack pointer SPR.

I have implemented a push instruction as such:
acc->mdr
mdr->stack(spr)
End

The implementation of push instruction is able to push the acc value to Stack but not able to pop the value from stack to acc for output.
And the pop instruction implemented below is popping out the address of the value instead of the value. The implementation of pop is:

spr-decr
stack(spr) ->mdr
mdr->acc
End

what have i done wrong? Or any suggestions?

Hypothetical Indexes in PostgreSQL

Category Image 011

In this blog, we will first cover what are hypothetical indexes and what is needed for these types of indexes. Secondly, we shall see the practical usage of these indexes. 

Need of Hypothetical Indexes:

As the name suggests, these are not real indexes, these are hypothetical indexes i.e. they are virtual indexes that PostgreSQL query planner does not consider when running queries. 

Ujwal Thapa, Co-Founder of the WordPress Nepal Community, Passes Away

Featured Imgs 23

“Here is my resume of professional Failures,” began his LinkedIn profile. On a site where most are apt to share success, Ujwal Thapa started with nearly a two-decade history of dreams that did not quite work out. Or, maybe they did in some ways.

Much of Nepal is reeling from his death today. In the past week, he had been battling multiple health complications from Covid-19. The 44-year-old activist was the founder of the Bibeksheel Nepali political party, originally a peaceful movement that fought against political corruption and social injustice.

However, many Nepali WordPress users will remember him as a co-founder of their community. The WordPress Nepal Facebook group has now grown to nearly 8,000 members.

In a 2015 interview with Nepal Buzz, he noted his proudest WordPress-related achievement as building this community. “That is not just creating tens and hundreds, but thousands of jobs in Nepal, and has the potential to create tens of thousands more, which basically means we are contributing to the nation by creating opportunities where there are none.”

Later in the interview, he said he was a provoker, and he continued to live the remainder of his life in that belief.

“I believe that the easiest way to bring change is to align all the positive people in the same direction,” he said. “So my job is to provoke and bring together people with similar interests, and align them in a similar direction, creating the change that they would never believe could come.”

Thapa founded Digital Max Solutions in 2002, amidst the Nepalese Civil War. At one point, the company had as many as 35 employees. Over 30 eventually moved on to start their own IT businesses. He also created the Entrepreneurs for Nepal Facebook group, which now has over 100,000 members. From May 2013 to October 2019, he served as the Chairperson of the BibekSheel Nepali party.

Many in Nepal’s WordPress community owe him a debt of gratitude for having the vision of building off the core platform. WordPress.org Themes Team representative Ganga Kafle credits at least part of his career and deep involvement with WordPress to Thapa, helping him land an initial internship with Web Experts Nepal.

“Ujwal Thapa is the person who introduced WordPress to me in 2012 in a meetup,” he said. “After that, I was in close relation with him. In 2014, after my graduation, I went to Ujwal and asked him about the internship, and he took me to that office and talked with the boss and finalized for the internship. That’s how I jumped in WordPress, and now I am one of the leads of Themes Team.”

“Once he said to me, ‘WordPress is giving so much things for free, why you hesitate to put Proudly Powered by WordPress?'” Kafle shared of the mentor, referencing the typical credit line in many WordPress site footers. “He was in love with WordPress.”

You can view Thapa’s WordCamp presentations as a speaker and panel moderator via WordPress.tv.

Spurwing’s Appointment Scheduling API Powers Distributed Workforce Communication

Featured Imgs 23

As the COVID-19 pandemic has driven an office exodus and cemented work-from-home and distributed workforces as common business structures, companies have been forced to find ways to work efficiently in these new formats. Spurwing, an API-first appointment scheduling business, provides developers with tools for building scheduling integrations that promise to relieve some of the pain points that come from remote work.

How To Set Up WordPress Email Logs

Featured Imgs 26

How To Set Up WordPress Email LogsHow do you check email logs in WordPress? If you’re running a website, you’re probably using WordPress. And you’re probably allowing for site emails – whether they’re just basic password resets, contact forms or perhaps a newsletter. WordPress is not just your ordinary platform. Apart from the fact that it’s affordable, you can improve the […]

The post How To Set Up WordPress Email Logs appeared first on WPExplorer.