GPU display issue with 2 5k2k LG monitors UWM

So I recently purchased 2 5k2k monitors to improve workflow for game development. I noticed once I run both displays the GPU gets hot and eventually the display goes black and the GPU fans go crazy. I also noticed that before that happens the GPU fans do not turn on to cool it down. Could this be an issue that can be fixed through an option the GPU might have? Or is the GPU not enough to keep both displays on?

The GPU starts getting hot and as soon as I display both screens, even though I dont run heavy GPU applications and sometimes it does before I do run them or minutes after I run something like Photoshop.

GPU is an RTX 1080 Ti.

If this the GPU isnt powerful enough, do you think an RTX 3080 might be enough?
Or if I use 1070ti to focus only on the displays and dedicate the 3080 GPU to the heavy applications.

Sorry for my ignorance in advance, I havent encounter this issue before so Ive never really looked into any of this.

A Forminator Quiz Is the Answer to Collecting Emails and Generating Leads

Collecting leads has never been as much fun! Thanks to our free 5-star plugin, Forminator, you can now create engaging quizzes and capture emails simultaneously.

Plus, you can easily manage your leads, integrate the emails with a 3rd party app (like Mailchimp, Aweber, etc.), automatically run submission reports, and more!

Quizzes are highly engaging, can offer personalized feedback, are interactive, and entertaining. Combine all of these elements with Forminator –the best form builder for WordPress– and you have a powerful and creative way to generate leads in just a few simple steps.

In this article, we’ll be going over how to:

  1. Set Up a Quiz in Forminator to Gather Leads
  2. Customize the Lead Generation Form to Your Specifications
  3. Adjust the Quiz Module Editor
  4. Set Up Email Notifications and Integrations
  5. Implement Quizzes on Your WordPress Site
  6. Easily View Submissions

You’ll have your lead generating quiz up quickly and added to your WordPress site in no time.

So…

I think that’s the best answer, too.

1. Set Up a Quiz in Forminator to Gather Leads

It takes only a switch of a button to get the lead generator feature on your next quiz.

From the Forminator dashboard, simply click Create, name the quiz, and pick whether you want to create a knowledge or personality quiz. When you hit Continue, activate the option for collecting email leads in one-click.

One-click and your quiz is primed for collecting leads.

It’s that simple! There’s nothing more to get your lead generating quiz started.

From here, you’re ready to…

2. Customize the Default Lead Generation Form to Your Specifications

When it comes to adjusting your quiz, you’ll see all of the available options in the Edit section of the dashboard.

Since we’ve covered the basics already on creating a quiz in other articles (check out the quiz section in Getting the Most Out of Forminator for more details), we’ll jump down to Leads.

When you’re in this section, the Lead Generation Form area is where you can customize the default lead generation form. To edit, just click on the pencil in the container that shows the quiz’s name, and it will open up in a new tab.

The lead generation form.
This example is named ‘Test Quiz.’

When you open the new tab, you’ll find the default fields are already in place. These include:

  • HTML
  • Email Address
  • First Name
  • GDPR
Where you edit the fields.
These fields are an excellent start for creating a quiz with lead generation.

Add as many fields as you feel are necessary by clicking Insert Fields. Also, adjust the default ones by clicking on each area’s gear icon.

With Forminator’s drag-and-drop functionality, you can arrange the fields any way you want. Also, delete any fields with one-click.

When it comes to editing the rest of the form, you’ll notice that Email Notifications and Integrations are locked. That’s because these are shared settings between the quiz and form modules. They’re configured back in the quiz editor (which we’ll get to in a moment).

The unaccessable areas to edit.
You can’t access Email Notifications or Integrations from here.

Everything else is accessible and editable.

In the Appearance section, you can pick the form container’s design style, change colors of separate areas, use custom fonts, create an optional border, adjust the spacing, and even add custom CSS.

Blue? Bold? Want a new font? You can do it all from here.

Choose what you want to happen after a form is successfully submitted in the Submission Behavior section.

In terms of validation, you decide if you want validation checks when the user submits the form using Ajax (which is recommended). The live method will inspect fields at the same time as the user fills them out.

Plus, you can enable inline validation with one-click.

Also, the Submission Indicator can be activated to show a loader on your form until it’s submitted.

The submission behavior area.
Choose your validation method and whether you’d like a submission indicator to be displayed.

You can enable autofill, boost security by enabling Honeypot protection & enabling logged in submissions only, and set the life span of the form for submissions.

We’ll add some added protection to this quiz with Honeypot.

In the Settings area, it’s possible to disable the store submissions in your database.

Also, determine how long you want to retain the form’s submission form by the number of days, customize how you’d like to handle erasure requests, and, if your form contains files, decide if the file gets deleted with deleted submissions.

The privacy area where you can edit submissions.
Customize exactly how long you want to retain your form’s submission and more.

The global privacy settings can also be accessed from here, where you can adjust however you’d like.

The global privacy settings.
When clicking the global privacy settings, it opens up in a new tab, and you can adjust.

You’ll also notice that the status is Published. That’s because when created, it’s automatically connected to the quiz module.

The status says it's published.
The status tells you it’s published.

Since it’s published, all you need to do is save any changes by clicking on Update.

Where you'll update to save changes.
Clicking update will save all of your changes.

You can adjust the settings at any time if you ever need to make changes.

3. Adjust the Quiz Module Editor

Now that we have the default lead generation form set up, you can hop back over to the tab that has the quiz editor, and you’ll be able to adjust additional settings.

In the Leads section, you’ll notice that you now have Form Placement and Skip Form options.

Where you'll edit the form placement.
You now have two more areas to adjust since editing the default lead generation form.

Form Placement is where you want to embed the lead generation form. You can choose between the beginning of the quiz or before showing the results.

If you want to give users the option to skip the form, you can enable the Skip Form feature.

Enter a customized message when you enable the Skip Form feature.

You can configure the Appearance and Behavior of the quiz, too. For help with this, please refer to our documentation on Appearance and Behavior.

4. Setting Up Email Notifications and Integrations

We can now get back into the Email Notifications and Integrations area since we set up the lead generation default. They were locked, but are now accessible. This is where we’ll set up email notifications every time a user opts into the quiz.

In the Email Notifications area, set up the Admin Notification and Participant’s Notification.

Where you can adjust the email notifications.
The admin’s email is also displayed here.

In terms of setting up, both of these fields function the same.

You can edit the message to the admin & participants that will go out after opting in, edit what emails the message goes out to, create advanced customizations with the email (e.g. CC & BCC), and add conditions.

Customize email notifications the way you want them.

Plus, in our new form data dropdown list, you can add quiz and form data in the body of your emails.

Add any specific piece of data in the emails that you’d like.

If you have any 3rd party apps integrated with Forminator, you can connect them in the Integrations area. Just click on the plus sign, and that particular app will walk you through on how to connect.

A view of the integrations area.
Easily sync your quiz up with MailChimp, Zapier, and more!

Once connected, you can start collecting the quiz’s data with any supported integrated app.

5. Implement Quizzes on Your WordPress Site

Once you have your quiz set up the way you’d like, hit Publish. Then, Forminator will give you a shortcode that you can use on any post, page, or acceptable widget.

Forminator hands over the shortcode as quick as that. 

Simply copy and paste the code, and that’s it. Your quiz is now ready to collect leads!

6. Easily Viewing Submissions

Viewing and monitoring submissions is quick and easy. The Quizzes dashboard gives you an immediate glimpse of activity.

You can see when the last submission was made, the number of submissions in the last 30 days, and easily access the submissions for a specific quiz.

Forminator's quizzes dashboard.
You can create a new quiz, view submissions, and edit quizzes in Forminator’s dashboard.

To see submissions from a specific quiz, locate the name of the quiz, tap on the gear icon, and then View Submissions.

Where you'll view submissions.
View submissions and much more from the gear icon.

Once you click View Submissions, Forminator brings up all the submissions to that particular quiz. It shows the submission date & time, email address, first name, and information from other fields you included.

Individual submissions display.
The submissions are also numbered by the submission date.

By clicking on the dropdown on individual submissions, you can view detailed information, quiz results, and any details on 3rd party integrations.

All of the field information is displayed here and quiz results.

Want to download the data? That’s a click away.

Click on Export and you can download a CSV file. Plus, you can apply submission filters and schedule exports by specific times, making them automatically emailed directly to you.

Manually or schedule exporting the data.

Q: What’s the Best Lead Generating Quiz Maker Out There?

A: With a 5-star rating and many tens of thousands of active downloads, we have to side with our four-eyed friend as the best lead generating quiz maker because he makes it quick, easy, and free to do.

Plus, Forminator can create contact & registration forms, collect payments, make polls, perform calculations, and much more. He’s continuously updated, thanks to Forminator’s awesome team of developers and designers.

To check out what else is coming out with Forminator, check out our Roadmap. And to learn more, you can always refer to Forminator’s documentation.

Finally, for a quick overview of what we just covered, be sure to watch this short video:

Need a recap? Check out this video.

Happy lead-generating quiz making!

Supercharge the Default WordPress Theme With Twentig, a Toolbox for Twenty Twenty

Page layout from the Twentig WordPress plugin.
Custom page pattern from the Twentig plugin.

I am often on the hunt for those hidden gems when it comes to block-related plugins. I like to see the interesting places that plugin authors venture. That is why it came as a surprise when someone recommended I check out the Twentig plugin a few days ago. Somehow, it has flown under my radar for months. And, it has managed to do this while being one of the more interesting plugins for WordPress I have seen in the past year.

Twentig is a plugin that essentially gives superpowers to the default Twenty Twenty theme.

While I have been generally a fan of Twenty Twenty since it was first bundled in core, it was almost a bit of a letdown in some ways. It was supposed to be the theme that truly showcased what the block editor could do — and it does a fine job of styling the default blocks — but there was a lot of potential left on the table. The Twentig plugin turns Twenty Twenty into something worthier of a showcase for the block editor. It is that missing piece, that extra mile in which WordPress should be marching its default themes.

While the new Twenty Twenty-One default theme is just around the corner, Twentig is breathing new life into the past year’s theme. The developers behind the plugin are still fixing bugs and bringing new features users.

Of its 34 reviews on WordPress.org, Twentig has earned a solid five-star rating. That is a nice score for a plugin with only 4,000 active installations. As I said, it has flown under the radar a bit, but the users who have found it have obviously discovered something that adds those extra touches to their sites they need.

What Does Twentig Do?

It is a toolbox for Twenty Twenty. The headline feature is its block editor features, such as custom patterns and page layouts. It also offers a slew of customizer options that allow end-users to put their own design spin on the default theme. However, my interest is primarily in how it extends the block editor.

Let’s get this out of the way up front. Twentig’s one downside is that it adds a significant amount of additional CSS on top of the already-heavy Twenty Twenty and block editor styles. I will blame the current lack of a full design system from WordPress on most of this. Styling for the block editor can easily bloat a stylesheet. Adding an extra 100+ kb per page load might be a blocker for some who would like to try the plugin. Users will need to weigh the trade-offs between the additional features and the added page size.

The thing that makes Twentig special is its extensive patterns and pages library, which offers one-click access to hundreds of layouts specifically catered to the Twenty Twenty theme.

Custom hero pattern from the Twentig WordPress plugin in the block editor.
Inserting one of the hero patterns.

It took me a few minutes to figure out how to access the patterns — mainly because I did not read the manual. I expected to find them mixed in with the core patterns inserter. However, the plugin adds a new sidebar panel to the editor, which users can access by clicking the “tw” icon. After seeing the list of options, I can understand why they probably would not fit into WordPress’s limited block and patterns inserter UI.

It would be easier to list what the plugin does not have than to go through each of the custom patterns and pages.

The one thing that truly sets this plugin apart from the dozens of other block-library types of plugins is that there are no hiccups with the design. Almost every similar plugin or tool I have tested has had CSS conflicts with themes because they are trying to be a tool for every user. Twentig specifically targets the Twenty Twenty theme, which means it does not have to worry about whether it looks good with the other thousands of themes out there. It has one job, which is to extend its preferred theme, and it does it with well-designed block output.

The other aspect of this is that it does not introduce new blocks. Every pattern and page layout option uses the core WordPress blocks, which includes everything from hero sections to testimonials to pricing tables to event listings. And more.

Twentig does not stop adding features to the block editor with custom patterns. The useful and sometimes fun bits are on the individual block level, and I have yet to explore everything. I continue to discover new settings each time I open my editor.

Whether it is custom pullquote styles, a photo image frame, or an inner border tweak to the Cover block (shown below), the plugin adds little extras that push what users can do with their content.

Custom inner border style from the Twentig WordPress plugin on the Cover block.
Inner border style for the Cover block.

Each block also gets some basic top and bottom margin options, which comes in handy when laying out a page. At this point, I am simply looking forward to discovering features I have yet to find.

Areas Themes Should Explore

One of the things I dislike about many of these features being within the Twentig plugin is that I would like to see them within the Twenty Twenty theme instead. Obviously not every feature belongs in the theme — some features firmly land in plugin territory. The default WordPress themes should also leave some room for plugin authors to explore. But, shipping some of the more prominent patterns and styles with Twenty Twenty would make a more robust experience for the average end-user looking to get the most out of blocks.

Block patterns were not a core WordPress feature when Twenty Twenty landed. However, for the upcoming Twenty Twenty-One theme, which is expected to bundle some unique patterns, the design team should explore what the Twentig plugin has brought to the current default. That is the direction that theme development should be heading, and theme developers can learn a lot by stealing borrowing from this plugin.

Coming in Jetpack 9.0: Shortcode Embeds Module Updated to Handle Facebook and Instagram oEmbeds

Facebook and Instagram are dropping unauthenticated oEmbed support on October 24. WordPress will be removing both Facebook and Instagram as oEmbed providers in an upcoming release. After evaluating third-party solutions, WordPress VIP is recommending its partners enable Jetpack’s Shortcode Embeds module. Jetpack will be shipping the update in its 9.0 release, which is anticipated to land prior to the October 24th deadline.

The module is being updated to provide a seamless transition for users who might otherwise be negatively impacted by Facebook’s upcoming API change. WordPress contributors have run some simulations but are not yet sure what will happen to the display for previously embedded content.

“It is possible that they change the contents of the JS file to manipulate cached embeds, perhaps to display a warning that the site is using an old method to embed content or that the request is not properly authenticated,” Jonathan Desrosiers commented on the trac ticket for removing the oEmbed providers.

WordPress.com VIP roughly outlined what users can expect if they do not enable a solution to begin authenticating oEmbeds:

By default, WordPress caches oEmbed contents in post metadata. These embeds will continue to display in previously-published content. If you edit older posts in the Block Editor, regardless of whether you update the post by saving changes, the embeds in the post will no longer be cached and will stop displaying. If you view these older posts using the Classic Editor, so long as the post is not re-saved, the embeds will continue to function and display properly. If you update the post content, the embed will cease functioning unless you have a mitigation installed.

Although WordPress VIP recommends using the Jetpack module as the best solution, self-hosted WordPress users may want to investigate other options if they are not already using Jetpack. oEmbed Plus is a free plugin created specifically for solving the problem of WordPress dropping Facebook and Instagram as oEmbed providers but it is more work to set up and configure. It requires users to register as a Facebook developer and create an app to get API credentials.

Audio and Video calling is not working in android webview

Hi to all! I am making an android app for a ready made social medial website.
Website url is: "www.MixMasala.in"
I am using webview for this site, all the functionality working accept two. As this is a social media website it has also audio and video calling option. When I use this website on regular browser such as Chrome, audio and video calling also works perfectly, but when I open this site in android web view then audio and Video calling don't work i-e interface of video and audio calling options open but voice and video can't be heard and seen. You can check that functionality by logging in that site on a regular browser.
Guide me what I am missing. I am pasting code of Oncreate() method of my webview activity.

   @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        mywebView = findViewById(R.id.wbvw);


        WebSettings webSettings = mywebView.getSettings();
        webSettings.setJavaScriptEnabled(true);
        webSettings.setBuiltInZoomControls(true);
        webSettings.setPluginState(WebSettings.PluginState.ON);
        webSettings.setAllowFileAccess(true);
        webSettings.setAllowContentAccess(true);
        webSettings.setMediaPlaybackRequiresUserGesture(false);
        mywebView.getSettings().setLoadWithOverviewMode(true);
        mywebView.getSettings().setUseWideViewPort(true);
        mywebView.getSettings().setDomStorageEnabled(true);
          if ( Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP ) {

                    CookieManager cookieManager = CookieManager.getInstance();

                    cookieManager.setAcceptThirdPartyCookies(  mywebView , true );

                }
        mywebView.setWebViewClient(new WebViewClient(){
            @Override
            public void onPageFinished(WebView view, String url) {
                super.onPageFinished(view, url);




                if (ContextCompat.checkSelfPermission(MainActivity.this,
                        Manifest.permission.RECORD_AUDIO) != PackageManager.PERMISSION_GRANTED
                ) {

                    ActivityCompat.requestPermissions(MainActivity.this,
                            new String[]{Manifest.permission.RECORD_AUDIO},
                            REQUEST_RECORD_AUDIO);


                }

            }
        });


        if (savedInstanceState == null) {
            mywebView.loadUrl("https://mixmasala.in/Script");
        }




        mywebView.setDownloadListener(new DownloadListener() {
            public void onDownloadStart(String url, String userAgent,
                                        String contentDisposition, String mimetype,
                                        long contentLength) {
                Intent i = new Intent(Intent.ACTION_VIEW);
                i.setData(Uri.parse(url));
                startActivity(i);
            }
        });

}

Some New Icon Sets

I’ve bookmarked some icon sets lately, partly because I can never find a nice set when I need to. I figured I’d even go the extra mile here and blog them so I can definitely find them later. Aside from being nice, cohesive, and practical sets of icons, I find it interesting that literally all of them:

  • are SVG, and thus easily resizeable
  • are built with rather efficient <path> elements
  • are stroked instead of filled (at least optionally)
  • have a click-to-copy SVG feature on their site
  • are free and open source

Good job, all! Seems like people are coming around to the idea of an SVG icon system where you just… put the SVG in the HTML.

Tabler Icons

Teenyicons

Heroicons

hola svg

This one is from Mariana Beldi who recently shared how hand-drawing SVG can be so much more efficient than using an illustration tool.


The post Some New Icon Sets appeared first on CSS-Tricks.

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

Make Your Own Dev Tool

Amber Wilson on making bookmarklets to help yo-self. She shows off one that injects an accessibility script — I like this approach, as it means you don’t have to maintain the bookmarklet, just the script it links to). Another example runs some code contained right in the link. The result is literally a bookmark in your browser you can click to do something that is useful to you on any site.

Well, I say “any” site, but what I mean is “sites that don’t have a Content Security Policy (CSP)” which is capable of totally blocking inline scripts (and that’s probably the best thing a CSP can do). That’s wonderful for security, but completely stops bookmarklets. The answer is browser extensions. The story with those is getting better as browsers converge on a standard format.

Browser extensions are much harder to write. Someone should make a browser extension that allows you to create arbitrary bookmarklet-ish snippets to run. I found a few attempts at this in a quick search, but nothing that looks particularly nice. Another thought: DevTools has snippets.

Direct Link to ArticlePermalink


The post Make Your Own Dev Tool appeared first on CSS-Tricks.

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

DataGridView Already Exists

Hi been working on this final piece of the puzzle and it seems like the last step is the hardest.

So far been able to stop it from adding multiple items per button click (number of rows + 1)
Update QTY count for first item only.

Trying to have it so all rows are checked and QTY updated, rather than adding new row per click for same item.

void UpdateProductList(object sender, EventArgs e)
        {
            Button button = (Button)sender;
            if (DGV_cart.RowCount == 1)
            {
                string[] newRow = new string[] { button.Text.ToString(), button.Tag.ToString(), "1" };
                DGV_cart.Rows.Add(newRow);
                UpdateTotal();
                return;
            }
            else
            {
                Boolean found = false;
                foreach (DataGridViewRow row in DGV_cart.Rows)
                {
                    if (row.Cells[0].Value.ToString() == button.Text.ToString())
                    {
                        // row exists
                        found = true;
                        Console.WriteLine(button.Text + " already existed in DataGridView.");
                        // set QTY + 1
                        int newQTY = int.Parse(row.Cells[2].Value.ToString());
                        int plusOne = newQTY + 1;
                        row.Cells[2].Value = plusOne;
                        UpdateTotal();
                        break;
                    }
                    if (!found)
                    {
                        string[] newRow = new string[] { button.Text.ToString(), button.Tag.ToString(), "1" };
                        DGV_cart.Rows.Add(newRow);
                        UpdateTotal();
                        break;
                    }
                }
            }
        }

Unit Testing In React Native Applications

React Native is one of the most widely used frameworks for building mobile applications. This tutorial is targeted at developers who want to get started testing React Native applications that they build. We’ll make use of the Jest testing framework and Enzyme.

In this article, we’ll learn the core principles of testing, explore various libraries for testing an application, and see how to test units (or components) of a React Native application. By working with a React Native application, we’ll solidify our knowledge of testing.

Note: Basic knowledge of JavaScript and React Native would be of great benefit as you work through this tutorial.

What Is Unit Testing?

Unit testing is the level of testing at which individual components of the software are tested. We do it to ensure that each component works as expected. A component is the smallest testable part of the software.

To illustrate, let’s create a Button component and simulate a unit test:

import React from 'react';
import { StyleSheet, Text, TouchableOpacity } from 'react-native';
function AppButton({ onPress }) {
    return (
      <TouchableOpacity
          style={[styles.button,
              { backgroundColor: colors[color] }]}
                 onPress={onPress} >
          <Text style={styles.text}>Register</Text>
      </TouchableOpacity>
    );
}
const styles = StyleSheet.create({
    button: {
        backgroundColor: red;
        borderRadius: 25,
        justifyContent: 'center',
        alignItems: 'center',
    },
    text: {
        color: #fff
    }
})
export default AppButton;

This Button component has text and an onPress function. Let’s test this component to see what unit testing is about.

First, let’s create a test file, named Button.test.js:

it('renders correctly across screens', () => {
  const tree = renderer.create(<Button />).toJSON();
  expect(tree).toMatchSnapshot();
});

Here, we are testing to see whether our Button component renders as it should on all screens of the application. This is what unit testing is all about: testing components of an application to make sure they work as they should.

Unit Testing In React Native Applications

A React Native application can be tested with a variety of tools, some of which are the following:

  • WebDriver
    This open-source testing tool for Node.js apps is also used to test React Native applications.
  • Nightmare
    This automates test operations in the browser. According to the documentation, “the goal is to expose a few simple methods that mimic user actions (like goto, type and click), with an API that feels synchronous for each block of scripting, rather than deeply nested callbacks.”
  • Jest
    This is one of the most popular testing libraries out there and the one we’ll be focusing on today. Like React, it is maintained by Facebook and was made to provide a “zero config” setup for maximum performance.
  • Mocha
    Mocha is a popular library for testing React and React Native applications. It has become a testing tool of choice for developers because of how easy it is to set up and use and how fast it is.
  • Jasmine
    According to its documentation, Jasmine is a behavior-driven development framework for testing JavaScript code.

Introduction To Jest And Enzyme

According to its documentation, “Jest is a delightful JavaScript testing framework with a focus on simplicity”. It works with zero configuration. Upon installation (using a package manager such as npm or Yarn), Jest is ready to use, with no other installations needed.

Enzyme is a JavaScript testing framework for React Native applications. (If you’re working with React rather than React Native, a guide is available.) We’ll use Enzyme to test units of our application’s output. With it, we can simulate the application's runtime.

Let’s get started by setting up our project. We’ll be using the Done With It app on GitHub. It’s a React Native application marketplace. Start by cloning it, navigate into the folder, and install the packages by running the following for npm…

npm install

… or this for Yarn:

yarn install

This command will install all of the packages in our application. Once that’s done, we’ll test our application’s UI consistency using snapshots, covered below.

Snapshots And Jest Configuration

In this section, we’ll test for user touches and the UI of the app’s components by testing snapshots using Jest.

Before doing that, we need to install Jest and its dependencies. To install Jest for Expo React Native, run the following command:

yarn add jest-expo --dev

This installs jest-expo in our application’s directory. Next, we need to update our package.json file to have a test script:

"scripts": {
    "test" "jest"
},
"jest": {
    "preset": "jest-expo"
}

By adding this command, we are telling Jest which package to register in our application and where.

Next is adding other packages to our application that will aid Jest to do a comprehensive test. For npm, run this…

npm i react-test-renderer --save-dev

… and for Yarn, this:

yarn add react-test-renderer --dev

We still have a little configuration to do in our package.json file. According to Expo React Native’s documentation, we need to add a transformIgnorePattern configuration that prevents tests from running in Jest whenever a source file matches a test (i.e. if a test is made and a similar file is found in the node modules of the project).

"jest": {
  "preset": "jest-expo",
  "transformIgnorePatterns": [
    "node_modules/(?!(jest-)?react-native|react-clone-referenced-element|@react-native-community|expo(nent)?|@expo(nent)?/.|react-navigation|@react-navigation/.|@unimodules/.|unimodules|sentry-expo|native-base|@sentry/.)"
  ]
}

Now, let’s create a new file, named App.test.js, to write our first test. We will test whether our App has one child element in its tree:

import React from "react";
import renderer from "react-test-renderer";
import App from "./App.js"
describe("<App />", () => {
    it('has 1 child', () => {
        const tree = renderer.create(<App />).toJSON();
        expect(tree.children.length).toBe(1);
    });
});

Now, run yarn test or its npm equivalent. If App.js has a single child element, our test should pass, which will be confirmed in the command-line interface.

In the code above, we’ve imported React and react-test-renderer, which renders our tests for Expo. We’ve converted the <App /> component tree to JSON, and then asked Jest to see whether the returned number of child components in JSON equals what we expect.

More Snapshot Tests

As David Adeneye states:

“A snapshot test makes sure that the user interface (UI) of a web application does not change unexpectedly. It captures the code of a component at a moment in time, so that we can compare the component in one state with any other possible state it might take.”

This is done especially when a project involves global styles that are used across a lot of components. Let’s write a snapshot test for App.js to test its UI consistency:

it('renders correctly across screens', () => {
  const tree = renderer.create().toJSON();
  expect(tree).toMatchSnapshot();
});

Add this to the tests we’ve already written, and then run yarn test (or its npm equivalent). If our test passes, we should see this:

  PASS  src/App.test.js
  √ has 1 child (16ms)
  √ renders correctly (16ms)

Test Suites: 1 passed, 1 total
Tests:       2 passed, 2 total
Snapshots:   1 total
Time:        24s

This tells us that our tests passed and the time they took. Your result will look similar if the tests passed.

Let’s move on to mocking some functions in Jest.

Mocking API Calls

According to Jest’s documentation:

Mock functions allow you to test the links between code by erasing the actual implementation of a function, capturing calls to the function (and the parameters passed in those calls), capturing instances of constructor functions when instantiated with new, and allowing test-time configuration of return values.

Simply put, a mock is a copy of an object or function without the real workings of that function. It imitates that function.

Mocks help us test apps in so many ways, but the main benefit is that they reduce our need for dependencies.

Mocks can usually be performed in one of two ways. One is to create a mock function that is injected into the code to be tested. The other is to write a mock function that overrides the package or dependency that is attached to the component.

Most organizations and developers prefer to write manual mocks that imitate functionality and use fake data to test some components.

React Native includes fetch in the global object. To avoid making real API calls in our unit test, we mock them. Below is a way to mock all, if not most, of our API calls in React Native, and without the need for dependencies:

global.fetch = jest.fn();

// mocking an API success response once
fetch.mockResponseIsSuccess = (body) => {
  fetch.mockImplementationForOnce (
    () => Promise.resolve({json: () => Promise.resolve(JSON.parse(body))})
  );
};

// mocking an API failure response for once
fetch.mockResponseIsFailure = (error) => {
  fetch.mockImplementationForOnce(
    () => Promise.reject(error)
  );
};

Here, we’ve written a function that tries to fetch an API once. Having done this, it returns a promise, and when it is resolved, it returns the body in JSON. It’s similar to the mock response for a failed fetch transaction — it returns an error.

Below is the product component of our application, containing a product object and returning the information as props.

import React from 'react';
const Product = () => {
    const product = {
        name: 'Pizza',
        quantity: 5,
        price: '$50'
    }
    return (
        <>
            <h1>Name: {product.name}</h1>   
            <h1>Quantity: {product.quantity}</h1>   
            <h1>Price: {product.price}</h1>   
        </>
    );
}
export default Product;

Let’s imagine we are trying to test all of our product’s components. Directly accessing our database is not a feasible solution. This is where mocks come into play. In the code below, we are trying to mock a component of the product by using Jest to describe the objects in the component.

describe("", () => {
  it("accepts products props", () => {
    const wrapper = mount(<Customer product={product} />);
    expect(wrapper.props().product).toEqual(product);
  });
  it("contains products quantity", () => {
    expect(value).toBe(3);
  });
});

We are using describe from Jest to dictate the tests we want to be done. In the first test, we are checking to see whether the object we are passing is equal to the props we’ve mocked.

In the second test, we are passing the customer props to make sure it is a product and that it matches our mocks. In doing so, we don’t have to test all of our product’s components, and we also get to prevent bugs in our code.

Mocking External API Requests

Until now, we’ve been running tests for API calls with other elements in our application. Now let’s mock an external API call. We are going to be using Axios. To test an external call to an API, we have to mock our requests and also manage the responses we get. We are going to use axios-mock-adapter to mock Axios. First, we need to install axios-mock-adapter by running the command below:

yarn add axios-mock-adapter

The next thing to do is create our mocks:

import MockAdapter from 'axios-mock-adapter';
import Faker from 'faker'
import ApiClient from '../constants/api-client';
import userDetails from 'jest/mockResponseObjects/user-objects';

let mockApi = new MockAdapter(ApiClient.getAxiosInstance());
let validAuthentication = {
    name: Faker.internet.email(),
    password: Faker.internet.password()

mockApi.onPost('requests').reply(config) => {
  if (config.data ===  validAuthentication) {
      return [200, userDetails];
    }
  return [400, 'Incorrect username and password'];
 });

Here, we are calling the ApiClient and passing an Axios instance to it to mock the user’s credentials. We are using a package named faker.js to generate fake user data, such as an email address and password.

The mock behaves as we expect the API to. If the request is successful, we’ll get a response with a status code of 200 for OK. And we’ll get a status code of 400 for a bad request to the server, which would be sent with JSON with the message “Incorrect username and password”.

Now that our mock is ready, let’s write a test for an external API request. As before, we’ll be using snapshots.

it('successful sign in with correct credentials', async () => {
  await store.dispatch(authenticateUser('ikechifortune@gmail.com', 'password'));
  expect(getActions()).toMatchSnapshot();
});

it('unsuccessful sign in with wrong credentials', async () => {
  await store.dispatch(authenticateUser('ikechifortune@gmail.com', 'wrong credential'))
  .catch((error) => {
    expect(errorObject).toMatchSnapshot();
  });

Here, we’re testing for a successful sign-in with the correct credentials, using the native JavaScript async await to hold our inputs. Meanwhile, the authenticateUser function from Jest authenticates the request and makes sure it matches our earlier snapshots. Next, we test for an unsuccessful sign-in in case of wrong credentials, such as email address or password, and we send an error as a response.

Now, run yarn test or npm test. I’m sure all of your tests will pass.

Let’s see how to test components in a state-management library, Redux.

Testing Redux Actions And Reducers Using Snapshots

There’s no denying that Redux is one of the most widely used state managers for React applications. Most of the functionality in Redux involves a dispatch, which is a function of the Redux store that is used to trigger a change in the state of an application. Testing Redux can be tricky because Redux's actions grow quickly in size and complexity. With Jest snapshots, this becomes easier. Most testing with Redux comes down to two things:

  • To test actions, we create redux-mock-store and dispatch the actions.
  • To test reducers, we import the reducer and pass a state and action object to it.

Below is a Redux test with snapshots. We will be testing the actions dispatched by authenticating the user at SIGN-IN and seeing how the LOGOUT action is handled by the user reducer.

import mockStore from 'redux-mock-store';
import { LOGOUT } from '../actions/logout';
import User from '../reducers/user';
import { testUser } from 'jest/mock-objects';

  describe('Testing the sign in authentication', () => {
    const store = mockStore();

  it('user attempts with correct password and succeeds', async () => {
  await store.dispatch(authenticateUser('example@gmail.com', 'password'));
  expect(store.getActions()).toMatchSnapshot();
  });
});
  describe('Testing reducers after user LOGS OUT', () => {
    it('user is returned back to initial app state', () => {
      expect(user(testUser, { type: LOGOUT })).toMatchSnapshot();
    });
  });

In the first test, we are describing the sign-in authentication and creating a mock store. We do this by first importing a mockStore from Redux, and then importing a method named testUser from Jest to help us mock a user. Next, we test for when the user successfully signs into the application using an email address and password that matches the ones in our snapshot store. So, the snapshot ensures that the objects that the user is inputting match every time a test is run.

In the second test, we are testing for when the user logs out. Once our reducer snapshot confirms that a user has logged out, it returns to the initial state of the application.

Next, we test by running yarn test. If the tests have passed, we should see the following result:

  PASS  src/redux/actions.test.js
  √ user attempts with correct password and succeeds (23ms)
  √ user is returned back to initial app state (19ms)

Test Suites: 1 passed, 1 total
Tests:       2 passed, 2 total
Snapshots:   2 total
Time:        31s

Conclusion

With Jest, testing React Native applications has never been easier, especially with snapshots, which ensure that the UI remains consistent regardless of the global styles. Also, Jest allows us to mock certain API calls and modules in our application. We can take this further by testing components of a React Native application.

Further Resources

6 Best Email Capture Tools Compared for 2020 (+ Best Practices)

Do you want to capture the email addresses of your website visitors?

Over 70% of first time visitors will never return to your website again. Getting their email address is the smartest way to keep in touch and get them to visit again.

In this article, we’ll compare some of the best email capture tools for WordPress and share the best practices to help you get results fast.

The best WordPress tools for email capture

What is Email Capture and Why Does It Matter?

Email capture is the process of collecting email addresses from people who come to your website.

Studies show that an email list can offer as high as 4300% return on investment (ROI). But simply creating an email list isn’t enough.

You need to actively capture email addresses from the visitors of your WordPress website. This allows you to turn visitors into email subscribers and soon after into paid customers.

Of course, you can encourage people to like your page on Facebook, follow your Instagram, and other social media platforms, but all smart marketers agree that capturing an email address should be your #1 priority.

That’s because your email newsletter will reach a far higher percentage of your audience than Facebook or Instagram posts because it’s not controlled by an algorithm.

With that said, here are some of the best tools for email capture in WordPress and beyond.

1. OptinMonster

The OptinMonster website

OptinMonster is the best lead capture software on the market. It helps you convert abandoning visitors into email subscribers, so you can get more leads from your existing website traffic.

With OptinMonster, you can create a whole range of high converting dynamic lead forms including popups, floating bars, full screen welcome mats, slide-in scroll boxes, inline personalized lead forms, gamified spin to win optin forms, and more.

The best part about OptinMonster is that it lets you show the right message at the right time, so you can get the highest conversions.

For instance, you could make a lead form popup that uses OptinMonster’s Exit Intent® technology to detect when a visitor is about to leave your site.

Your popup can offer the visitor an incentive to put in their email address. This could be a coupon, free shipping, a free download, or a sample of a digital product.

There are lots of other ways to use OptinMonster on your site. You can create a gamified ‘Spin to Win’ lead form or add Yes/No multi-step optins. These campaigns can significantly increase the number of people signing up for your email list.

You can also use OptinMonster to create full-screen welcome mats, lock premium content so that visitors need to subscribe to view it, add countdown timers to leverage urgency, use smart tags to add website personalization, and more.

OptinMonster comes with dozens of pre-made templates that you can easily customize with their drag & drop builder. You can also create custom forms without writing any code.

OptinMonster makes it easy to integrate your email optin campaigns with your favorite email marketing service and analytics platforms like Google Analytics. This lets you run detailed reports and see exactly how your different email optins are performing.

Each month, OptinMonster helps optimize over 2 billion sessions for smart website owners. There’s not a tool in the market that offers more targeting and personalization options, and this is why all the top marketers prefer OptinMonster.

Price:

OptinMonster costs from just $9/month (billed annually). For powerful features like Exit Intent®, countdown timers, and Yes/No optins, you need the Pro plan. That costs from $29/month (again, billed annually).

OptinMonster is a SaaS platform, so it works on WordPress as well as other platforms like Shopify, BigCommerce, and other website builders.

2. WPForms

The WPForms website

WPForms is the best contact form plugin for WordPress. Over 3 million website owners use their drag & drop form builder to create lead capture forms.

You can use WPForms to create all sorts of different forms, including email subscription forms, payment forms, polls, surveys, and more. Each form can be setup, so it capture users’ email addresses and add it to your CRM.

WPForms lets you use conditional logic so that certain fields are shown based on options that the user has selected. For instance, if you have a survey form, you might have different questions that you show based on whether the user is interested in fashion or food.

The plugin seamlessly integrates with a range of popular email marketing services and CRM platforms including Drip, AWeber, GetResponse, Active Campaign, Salesforce, MailChimp, and more.

Their Form Templates addon comes with over 150+ pre-made form templates that you can use to create a form with literally 1-click. These templates include: online event registration, newsletter signup form, contest entries, requesting a quote, suggestions, food ordering, and more.

Even better, all the forms created by WPForms are mobile-friendly. That means they work perfectly on mobile devices as well as on computers.

Price:

WPForms costs from $39.50/year. To get features like newsletter forms and integration with popular email marketing tools, you need the Plus plan. That costs from $99.50/year.

3. LiveChat

The LiveChat website

LiveChat is one of the best live chat software in the market. It lets you add a live chat feature to your site so that visitors can easily ask questions. This can be a powerful way to boost sales.

When a visitor starts a chat, they’ll be prompted to enter their email address. This means you can easily answer their question by email if there’s no customer service agent available to answer it live.

LiveChat also integrates with a range of email marketing services. You can simply add a checkbox to the pre-chat questionnaire that lets users opt-in to receive your email newsletter.

Best of all, LiveChat integrates with other smart services such as ChatBot.com. This lets you create AI chatbots that can answer customers’ questions on the spot. Chatbots can also capture email addresses and automatically pass these onto your email marketing service or CRM.

Price:

LiveChat costs from $16/month, billed annually. There’s a 14 day free trial. WPBeginner users can get an extra 30% off and a 30 day free trial using our LiveChat coupon.

4. Bloom

The Bloom plugin on Elegant Themes' website

Bloom is a plugin from Elegant Themes that lets you create attractive popups. It has a drag and drop builder that’s easy to use.

With Bloom, you get a range of different types of popups as well as in-line forms that you can place within or below your content.

It integrates with 19 different email marketing services, including Constant Contact, Active Campaign, AWeber, Get Response, and more.

One key drawback to Bloom compared with OptinMonster is that it’s a standalone WordPress plugin that loads all the code from your website. If you have a large, busy website, this could affect your site’s speed and performance.

Price:

Bloom comes packaged with Elegant Themes’ other tools, including the Divi theme and page builder. Membership of Elegant Themes costs from $89/year.

5. ThriveLeads

The ThriveLeads plugin on the ThriveThemes' website

ThriveLeads is another lead building WordPress plugin, similar to OptinMonster and Bloom. It lets you create a range of different email optin forms, including popups, sticky ribbons that stay at the top of the screen, forms you can place within your content, and more.

It’s easy to integrate ThriveLeads with a range of popular email services. It comes with built-in basic A/B testing and analytics, too. This lets you see which of your email optins are performing well.

Like Bloom, ThriveLeads loads all the code from your website itself. This could slow your site down. It’s also not quite so beginner-friendly as OptinMonster and Bloom.

Price:

ThriveLeads costs from $67 for a single site license. Alternatively, you can get it as part of ThriveThemes membership for $19/month (paid annually). This gives you access to all ThriveThemes’ themes and plugins.

6. Formidable Forms

The Formidable Forms website

Formidable Forms is a powerful forms plugin for WordPress. It lets you create all sorts of different types of forms, including calculator forms and lead quizzes.

You can use Formidable Forms to capture email addresses and integrate with your email marketing service or CRM platform.

The easiest way to do this is to use the built-in newsletter signup template. If you want something more specialized, you could try the event registration form template or the B2B leads form template.

Formidable Forms integrates with a range of popular email services, including Constant Contact, AWeber, Get Response, Active Campaign, and more.

It also lets you style your forms to look just how you want. Formidable is extremely powerful which can be a little overwhelming if you’re a beginner, but once you familiarize yourself with the software, then it’s extremely powerful.

Price:

Formidable Forms costs from $99.38/year. For integration with some tools including Constant Contact and Get Response, you need the Business plan from $199.43/year.

Best Practices for Email Capture

Once you’ve chosen a tool for email capture, you need to make sure you’re using it effectively.

Here are 3 key best practices for email capture that you need to follow:

1. Give Your Visitors a Reward for Signing Up

If you want people to hand over their email address, you need to give them something in return.

That could be a coupon for your online store, a useful PDF, a free sample of your video course, or almost anything else that fits with your online business.

For instance, Blog Tyrant offers new readers a downloadable guide:

Blog Tyrant's ultimate blogging toolkit offer

You can take this even further by offering different rewards on different pages for your site. You might offer a coupon to people who are visiting your online store and a free download to people who are browsing blog posts.

2. Don’t Annoy Your Visitors

Sometimes, email optin popups get a bad reputation. You might have come across popups that were annoying and got in your way when you visited a website.

There are plenty of ways to use popups while also letting visitors enjoy your site. For instance, you could use OptinMonster’s Exit Intent® technology to only show a popup at the moment when a visitor is about to leave. That way, your popup isn’t interrupting them as they read your content.

Here’s the popup that appears on WPBeginner when a new visitor moves to leave the site:

WPBeginner's exit intent popup, offering videos, plugins, and more

This email capture form helped us increase our conversions by over 600%.

3. Use Multiple Optins

It’s easy to create a single popup or email sign up form and think that you’re done. But to capture more emails, you need more optin forms.

Some of the best places to put your optins are:

  • At the top or bottom of your page as a sticky bar, or in the bottom right corner of your page as an unobtrusive slide-in.
  • During your content. You could place an optin part way through a blog post, for instance.
  • At the end of your content. You could add an optin at the bottom of your posts and pages.
  • In your sidebar. This is such a common place for an email list optin that visitors will often look there for it, without any prompting from you.

For example, Smash Balloon has an email optin displayed prominently in their blog’s sidebar:

Email optin in Smash Balloon's sidebar

Remember, you can also create different popups to appear on different pages. This lets you tailor each popup to your content.

We hope this article helped you learn about the best tools for email capture in WordPress. You may also want to see our comparison of the best business phone services and our beginner’s guide on how to create a custom business email address.

If you liked this article, then please subscribe to our YouTube Channel for WordPress video tutorials. You can also find us on Twitter and Facebook.

The post 6 Best Email Capture Tools Compared for 2020 (+ Best Practices) appeared first on WPBeginner.

3 Scripts to Help You Collect on Unpaid Invoices

Learning how to collect on unpaid invoices is an invaluable skill for freelancers and small business owners alike. At some point, you’ll likely run into difficult clients who try to test your professional boundaries. If you don’t take effective countermeasures, late payments can impact your bottom line.

Where to get a good antivirus software

I have recently encountered a problem that my computer always get attacked, it seems antivirus software that has been installed on my pc cant work anymore, So I am planning to get new one from Bzfuture, Anyone has bought there? Does it work?

To Output An “X” Pattern On Screen

Hi dear forum members,

I am brand new in C programming and have to program an "X" as homework (see attached picture).
The edge length of the "X's" should be entered by the user, ie the "X" should be arbitrarily large or small.

Can someone help me with the task?

So far I have the following code:

include <stdio.h>
int main () {
int edge length, i;
printf ("Please enter the edge length of the pattern: \ n");
scanf ("% d", & edge length);

char sign;
character = '';

for (i = 0; i <edge length; i ++) {
printf ("-% c- \ n", character);

}
return 0;
}