Click-counter component
Strategy

Vue Tutorial 7 – Components


Granny is delighted! Your latest update of her web app really impressed her. She can now comfortably manage guests for her upcoming birthday party, knowing that she will not accidentally submit invalid data to the table, thanks to our frontend validation. However, she also mentioned something about reviewing your code and asked about the reusability of components within the app. This sent a chill down your spine. It’s time to learn about reusable Vue Components…

Vue Components

The more you program in Vue, the more thankful you will be for the Vue component system. Components are not very useful in small applications that we covered in this series of tutorials up to now. It is really important to understand how they work and what they are as they become very useful when building large applications, which you will inevitably face in your programming career.

You may also like: Vue.js 2 Authentication Tutorial, Part 1.

Components are small, self-contained, reusable objects that we can define and re-use in our app. Each component has a name and can be instantiated using that name. Here’s a simple example of a component that simply counts the number of times it has been clicked on.

// click-counter component
Vue.component('click-counter', {
    data: function () {
        return {
            count: 0
        }
    },
    template: '<button v-on:click="count++">Click count = {{ count }}</button>'
})


Watch out: Make sure you define the component before you instantiate your Vue app.

This component is called click-counter, which means we can instantiate it by that name in the app

<div id="components-app">
    <click-counter></click-counter>
</div>

The above app results in the following output

Click-counter component

Click-counter component

Since this component is reusable, we can instantiate it as many times as we please! Notice how each one of them maintains their own state.

<div id="components-app">
    <click-counter></click-counter>
    <click-counter></click-counter>
    <click-counter></click-counter>
</div>

The updated app results in the following output

Creating multiple click-counter components

Creating multiple click-counter components

You may have noticed that the component data is defined slightly differently to when we define it in a Vue app. If you recall, this is the typical way to define data:

data: {
  count: 0
}

However, in order to maintain an independent state for each instance of the component, it’s required that data is defined as a function.

Passing Data into a Component

Let’s assume we would like to implement a blog feature on a website where users can comment on a post. Let’s also assume that we have the list of comments stored in the data like this:

var app = new Vue({
    el: '#comments-app',
    data: {
        comments: [
            {id: 1, name: "Jerry", content: "I love Vue so much"},
            {id: 2, name: "Eric", content: "Vue.js solved all my relationship problems"},
            {id: 3, name: "Sandra", content: "I'm currently on the beach coding Vue as we speak!"},
        ]
    }
})

In this scenario, it would make sense to implement a user-comment component. This is how we could go about it.

Vue.component('user-comment', {
   template: '<div><p class="font-weight-bold">{{ comment.name }} said:</p><p>{{ comment.content }}</p></div>'
})

We’d quickly discover that we don’t know how to pass data to components! Not to worry, this can be achieved using props.

Props are custom arguments you can define in the component. If you worked with React before, you will recognize the term props. It has the very same meaning in Vue. To add props to the user-comment component we add props element as follows

Vue.component('user-comment', {
    props: ['comment'],
    template: '<div><p class="font-weight-bold">{{ comment.name }} said:</p><p>{{ comment.content }}</p></div>'
})

The one last thing we must do is to display the comments in some way. You can probably guess that it will somehow involve the v-for directive. Here’s how we can do it:

<user-comment
        v-for="comment in comments"
        v-bind:comment="comment"
        v-bind:key="comment.id"
>
</user-comment>

This is the result of our work

User-comment component

User-comment component

Conclusion

We have successfully created a component and passed data down to it using props. This means we are a step closer to being able to code large applications consisting of reusable components and separating out the concerns of each element.

The code for this tutorial is available here.

Note: You can find parts one, two, three, four, five, and six of this series at their respective links.

Further Reading



Source link

walrus-sleeping-on-beach
Strategy

Python 3.8 New Features — Code Name Walrus


walrus-sleeping-on-beach

He chonk

A brief and practical guide to the most important/interesting new features/changes coming with Python 3.8 (code name – walrus – joking 🙂 ). So, first let’s announce the news:

Python 3.8 was released on October 14th, 2019.

The official documentation is here:

If you want to play with the new features without installing the latest Python 3.8, you can do it here: Python 3.8 (pre-release)

A brief video showing the new features.

You may also like: Core Python.

Overview

In this article, we are going to have a brief, high-level review of some of the new features. Python 3.8 comes with a new Warlus Operator, positional-only parameters, and lots of other new and interesting changes, improvements, and features. It also offers plenty of language changesone new module, and improvements on others.

Many optimizations and C API changes can be found in the version. Several methods and commands are deprecated.

Personally, I’ll not move to python 3.8 soon. Nothing is so important or a game-changer for the moment. Some features could be tricky or cause confusion, which is another reason for me to stick to 3.7 for the moment.

New Features

For me, the most interesting new features are:

  • The Walrus Operator.
  • Positional-only parameters.
  • f-strings support =

The Walrus Operator :=

In short, this is a new operator that will be used as an assignment or named expression. The official description from the PEP describes it as follows:

This is a proposal for creating a way to assign to variables within an expression using the notation NAME := expr.

If you wonder why it’s called like this:

It is affectionately known as “the walrus operator” due to its resemblance to the eyes and tusks of a walrus.

The best way to understand the new operator is by viewing some examples like:

Avoid repeated expression calls:

num = 3
if (n := num % 2) != 0:
    print(f"Number is not even: number: {num}, remainder: {n}")

Result:

Number is not even: number: 3, remainder: 1      

Regex expressions

import re, datetime
text = 'The latest version of python 3.8 is released on 14-10-2019 .. '

# before walrus
whole_match = re.findall(r'[d]{1,2}-[d]{1,2}-[d]{4}', text)
if whole_match:
    print(whole_match)

# after walrus
if (found_date := re.findall(r'[d]{1,2}-[d]{1,2}-[d]{4}', text)):
    print(found_date)

List comprehension

If a value computed in a filtering condition is also needed in the expression body:

numbers = [3, '0', 0, '6', 2, 1, 0, '7']
print([final_number for number in numbers if (final_number := int(number)) != 0])

Result:

[3, 6, 2, 1, 7]

Errors and usage:

Sometimes, the walrus operator can be misleading and lead to confusion or errors. So, it might be a good idea to limit its usage to simple cases and expressions in order to avoid problems with code readability.

Below, you can find list comprehension and walrus operator, which leads to an error:

numbers = [3, 0, 0, '6', 2, 1, 0, '7']
[number for number in numbers if (number := int(number)) != 0]

SyntaxError: assignment expression cannot rebind comprehension iteration variable ‘number’

Another interesting case and possible abuse is:

if (I := he ) or ( you := me ) and ( we := alltogether):
    I = walrus

You can read more here: I walrus

The full description is available here: PEP 572

Positional-Only Parameters

A new syntax for function parameters is introduced —  /. This is an example function:

def f(a, /, b, *, c):
    print(a, b, c)

In this function parameter a  is a positional-only and cannot be a keyword argument. While on the other hand c must be a keyword argument.

Let’s check several examples:

Correct call for this function:

f(10, 20, c=30)

Result:

10 20 30

TypeError: f() takes 2 positional arguments but 3 were given

f(10, 20, 30) # c must be a keyword argument

Results in:

TypeError: f() takes 2 positional arguments but 3 were given

TypeError: f() got some positional-only arguments passed as keyword arguments: ‘a’

f(a=10, b=20, c=30)   # a cannot be a keyword argument

Results in:

TypeError: f() got some positional-only arguments passed as keyword arguments: ‘a’

Positional-only parameters can be used in two ways. Their names are not shown as possible keywords, which makes them available for kwargs:

def f(x, /, **kwargs):
    print(x, kwargs)

f(10, x=1, y=2)         # x is used in two ways
10 {'x': 1, 'y': 2}

For more info: Python Positional-Only Parameters.

F-Strings Support for Self-Documenting Expressions and Debugging

In 3.8 there is added support for = for f-strings. So f-string like:

 f'{version=} is released on {release_date=}' 

will be represented as:

 

version='3.8' is released on release_date=datetime.date(2019, 10, 14)

 

Few more examples on this

from datetime import date

version = '3.8'
release_date = date(2019, 10, 14)
python_one_version = date(1994, 1, 1)

since_python_one = release_date - python_one_version

print(f'{version=} is released on {release_date=}')
print(f'{version=} day of Release {python_one_version.day=:02d}')
print(f'{version=} day of Release {since_python_one.days=:,d}')

Results:

version='3.8' is released on release_date=datetime.date(2019, 10, 14)
version='3.8' day of Release python_one_version.day=01
version='3.8' day of Release since_python_one.days=9,

Used in previous Python versions, like Python 3.7, this will result in:

  File "<fstring>", line 1
    (version=)
            ^
SyntaxError: invalid syntax

The main idea is:

#(really) bad old days this was pretty wordy:
print "foo=", foo, "bar=", bar

#f-strings make this slightly nicer to type:
print(f"{foo=} {bar=}")

Result:

foo=datetime.date(2019, 10, 14) bar=1

Other New Features

Some of the features cannot be easily explained with examples so I’ll just list them:

  • Parallel filesystem cache for compiled bytecode files.
  • Debug build uses the same ABI as release build.
  • PEP 578: Python Runtime Audit Hooks.
  • PEP 587: Python Initialization Configuration.
  • Vectorcall: a fast calling protocol for CPython.
  • Pickle protocol 5 with out-of-band data buffers.

Other Language Changes

In this section, there are some quite interesting changes which might need your attention when you migrated from older Python version to 3.8 like:

  • The continue statement is now allowed in the  finally clause.
  • The new method as_integer_ratio() for bool,  int, and Fraction types:
x = 7
print(x.as_integer_ratio())

Result:

(7, 1)
  • Added support of N{name} escapes in regular expressions:
import re

notice = 'Copyright © 2019'
copyright_year_pattern = re.compile(r'N{copyright sign}')
print(copyright_year_pattern.search(notice).group(0))

This will error in earlier versions:

sre_constants.error: bad escape N at position 0

  •  Dict and dictviews are now iterable in reversed insertion order using reversed(). 
  • Warnings when a comma is missing in code like: [(1, 2) (3, 4)]. 

Before:

  File ".code.tio", line 1, in <module>
    [(1, 2) (3, 4)]
TypeError: 'tuple' object is not callable

Now:

SyntaxWarning: 'tuple' object is not callable; perhaps you missed a comma?
  [(1, 2) (3, 4)]
Traceback (most recent call last):
  File ".code.tio", line 1, in <module>
    [(1, 2) (3, 4)]
TypeError: 'tuple' object is not callable
  • Arithmetic operations between subclasses of datetime.date or datetime.datetime and datetime.timedelta objects now return an instance of the subclass, rather than the base class.

For example:

from datetime import datetime, timezone

class DateTimeSubclass(datetime):
    pass

dt = DateTimeSubclass(2012, 1, 1)
dt2 = dt.astimezone(timezone.utc)

print(type(dt))
print(type(dt2))

In Python 3.8

<class '__main__.DateTimeSubclass'>
<class '__main__.DateTimeSubclass'>

Before:

<class '__main__.DateTimeSubclass'>
<class 'datetime.datetime'>
  • When the Python interpreter is interrupted by Ctrl-C (SIGINT), and the resulting KeyboardInterrupt exception is not caught, the Python process now exits via a SIGINT   signal
  •  Dict comprehensions have been synced-up with dict literals, so that the key is computed first and the value second:
from unicodedata import normalize
names = ['Löwis', 'Łukasz', 'Dörwald']
print({(n := normalize('NFC', name)).casefold() : n for name in names})

Result:

{'löwis': 'Löwis', 'łukasz': 'Łukasz', 'dörwald': 'Dörwald'}

Conclusion

Python 3.8 comes with a new assignment operator, syntax for function parameters, and many other improvements and features. At first sight, some of the changes look a bit controversial, but they can offer new solutions to old problems.

The examples covered in the article shows potential for expanding the usage beyond the scope described in PEPs.

Once this version is well adopted, I’ll move to it in order to explore the full potential of it.

Further Reading



Source link

Dependency Mocks: A Secret Weapon for Vue Unit Tests
Strategy

Dependency Mocks: A Secret Weapon for Vue Unit Tests


If your Vue single-file components have dependencies, you’ll need to handle the dependencies somehow when you unit test the component.

One approach is to install the dependencies in the test environment, but this may overcomplicate your tests.

In this article, I’ll show you how to mock a module file in Jest by replacing it in your component’s graph of dependencies.

Example Scenario

Say we have a single-file component that we want to test called Home.vue. This component is part of a blog app, and its main job is to display post titles.

To do this, it retrieves posts by importing a Vuex ORM model Post and calling itsall method. It doesn’t matter if you’re unfamiliar with Vuex ORM, the important point is that the Post model is a dependency of this component.

You may also like: Vue Development in 2019: What You Need to Know.

Home.vue

The Unit Test

Now, we want to write a unit test for this component to confirm that it renders correctly.

The details of this test aren’t important, but here’s how we might write it. First, we’d mount the component using Vue Test Utils. Second, we’d check the mounted component against a snapshot of its rendered markup.

Home.spec.js

The Test Error

If we try to run this test, we’ll get an error:

The reason for this error is that the Post Vuex ORM model in the component depends on both Vuex ORM and Vuex, and neither plugin is present in the test Vue instance.

Mocks to the Rescue

You might be tempted to install the VuexORM and Vuex on the test Vue instance. The problem with this approach is that the errors won’t stop there; next, it will complain that the Vuex store hasn’t been created and then that the model hasn’t been installed into the Vuex ORM database, etc. Suddenly, you have 20 lines of code in your test and a whole lot of complexity.

But,  here’s the thing: it’s not important for this unit test that the posts come from the Vuex store. All we need to do here is satisfy the dependency, so that’s why we’ll turn to mocking.

Creating a Mock

The easiest way to create a mock is to first create a directory, mocks, adjacent to the file you want to mock. Then, create the mock module in that new directory. If you follow this recipe, Jest will automatically pick the file up.

Inside the new file, export a Common JS module. For the mock to work, you’ll need to stub any method of the Post model that the component calls.

The only method used in Home is all. This method will retrieve all the items in the store. The output of this method is then used to feed the v-for. So, all we need to do is make all a function that returns an array, and the Home component will be happy.

src/store/models/__mocks__/Post.js

How Jest Resolves Dependencies

We now want to make it so the Home component uses the mock Post model instead of the “real” Post model.

Before I show you how to do that, I need to briefly explain how Jest, like Webpack, builds a graph of dependencies when it runs your test code. In other words, it starts with your test file, then follows each import and require statement, noting every module needed.

Currently, one path of that dependency graph relevant to what we’re discussing would be this:

It’s this path of dependencies that’s the source of the error we’re experiencing.

Fortunately, Jest allows us to replace modules in the dependency graph with ones we specify. If we use our Post mock, the above path would be modified to look like this:

The crux of the solution is that, unlike the real  Post model, the mock has no further dependencies, and so the  TypeError should no longer occur if we use it.

Using the Mock

To use the mock, we use the jest.mock method. This goes at the top of the file, as it’s handled at the same time as import and require statements.

The first argument is the module you want to mock, in this case, "@/store/models/Post". If you put the mock in a __mocks__ directory, as described above, that is all that is required for this to work.

Home.spec.js

When you run this test again, Jest will ensure the dependency graph is modified to replace "@/store/models/Post" with the mock you created, and instead of the  TypeError, you’ll get a green tick.

Further Reading



Source link

Importing a Maven Project in Eclipse
Strategy

Importing a Maven Project in Eclipse


This tutorial explains how to import an existing Maven project into Eclipse and how to create a run configuration for a Maven goal. This is useful, for example, when using the Jetty Maven plugin that allows you to quickly deploy and run a Java web application using this popular server.

Maven is a project management tool that goes beyond dependency management. See Learning Maven Concepts for more.

Download an Existing Maven Project

This tutorial uses a Maven archetype that generates a Java web application with a preconfigured Jetty Maven Plugin in it:

If you prefer, you can generate a ZIP file with the project at https://vaadin.com/start/latest or https://start.vaadin.com. Make sure you select the Plain Java Servlet option before downloading the project.

You may also like: Building Java Applications With Maven.

The project should include a directory with a Maven project in it:

Maven project directory

You need Node.js installed on your computer to compile the example application.

Import the Project

  1. In Eclipse, select File > Import…
  2. In the import window, expand Maven, select Existing Maven Projects, and click Next: Import window
  3. Click Browse, and select the directory that contains the pom.xml file of the project you want to import: Select the root directory
    If you are importing a multi-module Maven project, make sure you select the correct project to import. You will typically want to select all the projects.
  4. Click Finish. Eclipse will import the project and start downloading the required resources.

Running Maven goals

Eclipse has built-in integration with Maven. You can run common commands, such as  mvn install or  mvn jetty:run without having to leave the IDE.

The most common commands are available in the Run As and Debug As folders when you right-click the project in Project Explorer view. For example, to run  mvn install, right-click the project and select Run As > Maven install:

Maven install

You can find additional useful options in the Maven submenu.

You’ll see how Eclipse executes the  install build phase (and all the previous phases in the Maven’s default lifecycle) that download dependencies from the repositories and copies the generated artifacts into your local Maven repository among other things.

Creating a Run Configuration

run configuration is a shortcut to run a specific task from within the IDE. Let’s create a run configuration for the  jetty:run  Maven goal to make it simpler to run the web application from the IDE.

If you are using Spring Boot, use the spring-boot:run goal.

  • Right-click the project in the Project Explorer view and select Run As > Maven build.
  • In the Edit Configuration window, for Goals type jetty:run and optionally give the run configuration a new name: jetty:run configuration
  • Click Run to save the new configuration and execute it. You should see the Console view with the log generated by the application and the Jetty server.
  • To stop the server, click the Terminate icon in the Console view: Terminate You can deploy and run the web application by clicking the run (or the debug) icon in the toolbar and selecting the corresponding run or debug configuration:

Toolbar

If you use the Vaadin project used in the tutorial, you can invoke the web application at http://localhost:8080.

That’s it. Now you can use Eclipse to develop your Maven application. To learn more about:

Further Reading



Source link

The Making of a "Special Series" on a WordPress Site
Strategy

The Making of a “Special Series” on a WordPress Site


We just ran a fancy article series here on CSS-Tricks with a bunch of different articles all answering the same question. By fancy, I mean two things:

  • The articles had a specially-designed template just for them. (Example)
  • The series has a specially-designed landing page.

One of the reasons I enjoy working with WordPress is because of how easy this is to pull off. I’m sure any CMS has their own ways of doing this, and I don’t mean it to be a battle-of-CMSs thing here. I just want to illustrate how easy I found this to pull off in WordPress.

Any post can have a template

I made a PHP file in the theme directory called eoy-2019.php (eoy meaning “End of Year,” the spirit of this series). At the top of this file is some special code comments to make it read as a template:

<?php
/*
Template Name: EOY 2019
Template Post Type: post
*/

Now any post we publish can select this template from a dropdown:

And they’ll use our cool template now!

Special scripts and styles for that template

I actually didn’t need any scripting for this, but it’s the same concept as styles.

I put a conditional check in my header.php file that would load up a CSS file I created just for these posts.

if (is_page_template('art-direction/eoy-2019.php') || is_category('2019-end-of-year-thoughts')) {
  wp_enqueue_style('eoy-2019', get_template_directory_uri() . "/css/eoy-2019.css?version=7");
}

A special template for the whole group

I could have grouped the posts together in any number of ways:

  • I could have made a special Page template for these posts and designed that to link to these special posts manually or with a custom query/loop.
  • I could have had them share a tag, and then created a special tag archive page for them.
  • I could have used the same system we used for our Guides, which is a combination of CMB2 and the attached-posts plugin.

Instead, I gave all the posts the same category. That felt the most right for whatever reason. We don’t use categories a ton, but we use them for some major groups of posts, like Chronicle posts.

By using a category, I can use a special templating trick. Naming the file category-2019-end-of-year-thoughts.php, I can use the end of that file name to match the slug of the category name I used and it “just works,” thanks to the WordPress template hierarchy. I don’t need to write any code for that file to be used to display this category and I get the URL for free. Now I have a file I can use to build a special design just for these posts.

Future fallbacks

Let’s say it’s five years from now and I’ve kinda stopped caring about the super special styling and treatment behind these posts. I don’t know if that will happen, but it might. All these special files can just be deleted without hurting the content or URLs.

Again, thanks to the template hierarchy, the special post templates will simply fall back to the regular single.php template. The category homepage will just render from the regular archive.php template. The special styles won’t be applied, but the content will be just fine and the URLs will be unchanged. Nice.



Source link

Deep Linking in React Native with React Navigation
Strategy

Deep Linking in React Native with React Navigation


In this article, we are going to build a simple deep linking mechanism in React Native, which takes a user to a specific screen of a sample app, after clicking on a deep link outside the app (e.g. Safari). The output will look like this:

Image title

Example output

Create a React Native App

To get started, please create a new React Native project by executing the following command:

To be able to support deep linking navigation, let us add the required npm packages. Once the project directory has been generated, navigate inside the project folder from your terminal and install the following dependencies.

The next step is to link all the libraries you just installed. I am using a React Native version greater than 0.60.x. If you are using a lower version of React Native, please follow the instructions to link the libraries here.

For iOS, you just have to run the following set of commands.

You may also like: React Native Developers: Create Your First App.

For Android, add the following lines to the 
android/app/build.gradle file under 
dependencies section.

Next, go to android/app/src/main/java/com/rndeeplinkdemo/MainActivity.java file and add the following.

Create Two Mock Screens

After the dependencies have installed and react-navigation configured for each platform, create two mock screen files inside the src/screens directory. First, create a file HomeScreen.js with the following code snippet. This screen is going to be the initial screen when the app loads.

Next, create another file DeepLinkScreen.js. This screen is going to open when the user is transiting from a URL.

Configure Deep Linking in React Navigation

Let’s create a stack navigator from both the screen files. Import the following statements inside the file src/navigation.js.

Next, create a stack navigator with HomeScreen as the initial screen.

To enable deep linking the app requires some identifier to recognize the path to the screen to open from the given external URL. react-navigation has path attribute that tells the router relative path to match against the URL. Re-configure both the routes as following:

The last piece of the puzzle here is to configure the navigation to extract the path from the incoming URL from an external resource. This is done by uriPrefix. Add the following code snippet at the end of the file.

Do not forget to import the navigator inside App.js file, which is the main entry point of the current React Native app.

Configure URI Scheme for Native iOS Apps

To make this work, you have to configure the native iOS app to open URLs based on the prefix myapp://. Open ios/rnDeepLinkDemo/AppDelegate.m file and add the following.

Then, open the ios/rnDeepLinkDemo.xcodeproj in the Xcode app. Select the app from the left navigation bar.

react native deep linking iOS

Selecting app

Open the Info tab.

Opening info tab in XCode

Next, go to the URL Types.

URL types

Click the + button and in identifier as well as URL schemes add myapp.

Adding URL type properties

Rebuild the React Native binaries by running react-native run-ios.

Testing the Deep Link

The external URL is going to look like this:

To test it out, there are two ways. You can either test by executing the command below in a new terminal tab.

Or, open the Safari web browser in your iOS device or simulator. Type in the URL and press enter.

Final output

Further Reading



Source link

Print-Inspired Layout on the Web
Strategy

Print-Inspired Layout on the Web


I always love seeing people get inspired by print design and trying to port it over to the web. There is a much deeper history of interesting print work to draw from, and still a ton of modern work happening that eclipses most digital design work today. The web is fully capable of bold, interesting designs, yet we see it all-too-rarely.

Just lately, we’ve seen a little surge of interest…

Dan Davies took inspiration from nine different print articles and built layouts that are similar in spirit to each of them.


Ahmad Shadeed rebuilt a rather complex grid layout with bold typography inspired by an image from a book.


Facundo Corradini built out a design from The New York Times Style Magazine.


Frederick O’Brien compared newspaper design to web design.

We’ve seen this kind of exploration before. I explored it in this article, which is largely about the CSS tools we have to do this work better, but also includes demos like this one I made as well as this one from Stuart Robson.

Also:

  • Jen Simmons has been banging this drum for ages. “Getting out of our ruts” is a phrase she used in a presentation that hits home for me.
  • Jules Forrest has done lots of grid explorations like this one that appears to be highly print-inspired.
  • Raisa Yang has explored magazine layout, this one using columns, which I don’t see used all that much out in the wild but is highly inspired by print.

I think it would be fun to put together an article with all the main CSS tools we have for replicating print-like designs. I just might do that, but what might talk me out of it is the fact that it’s sorta everything in CSS. CSS is about styling, and all styling is on the table for building unique designs.



Source link

A Few Notes From a Year of Freelancing
Strategy

A Few Notes From a Year of Freelancing


Recently I wrote an article about how I prepared to join the world of freelancing. Now that I’m over a year into freelancing and loving life, I thought it would be beneficial to share with you what I’ve learned so far. 

1. Set Your Rate

Time is money, and as a freelancer, you have to be very specific as to what exactly an hour of your time is worth. This varies depending on the type of software you write and the amount of experience you have. I suggest that you research your direct competitors in the area and find out how much they charge. Initially, you probably want to charge a bit less until you have a considerable amount of projects under your belt and numerous references from happy customers. 

2. Write it Down and Sign 

In the initial stages of every project, it’s very important that you outline what you’re willing to develop and for what price. Make sure that you’re as specific as you can be so when you’ve developed the software there’s no confusion as to what was expected. This also prevents the customer from taking advantage of you by asking for “one last thing.”

Guide for Freelancers – Skills to Land a Project In 2019.

3. Keep Personal and Professional Life Separate

I worked from home for the first 8 months of freelancing and found it to be amazing. I didn’t have to commute. I didn’t have to participate in useless meetings and didn’t partake in water cooler chit-chat about the weather or my plans for the weekend. My productivity skyrocketed, that is, until a time when my personal and professional life merged into one and I didn’t have a life anymore. 

Rent out a desk in your local co-working space if possible and don’t bring work home. It’s much healthier this way. 

4. Network

I found that networking and meeting new people were the best sources of new projects. Attend conferences where your potential customers are likely to be, and you’ll be surprised at the number of qualified leads this will generate. 

5. Time off

Elon Musk, Jeff Bezos, Jack Ma, and the rest of the successful businessmen of the modern world work 26 hours a day. I tried it and I found it to be unsustainable. You must realize that life is a marathon and not a sprint and a burnout will certainly not get you closer to achieving your goals. Set your working hours. Ensure you have at least one day a week off and get at least seven hours of sleep per night. 

6. Schedule Vacation

I schedule my time off ahead of time because if I don’t, the project I’m working on takes precedence and I keep postponing my holiday indefinitely. I find that if I know I’m off work between certain dates, I will work harder beforehand to close off a project and then actually enjoy my deserved time off. 

7. Track Time

I found it to be very beneficial to track my time. At the end of every week I receive a report, which clearly shows me what took up the most of my time in that particular week. This also helps me with invoicing my clients as I know exactly how much time I spent on each project. There are plenty of tools which will help you with this task. Google “Free time tracking software.”

Conclusion

I believe that if you keep the above points in mind you’ll do okay. The most important thing is to get started and begin making your own mistakes.

Further Reading



Source link

Strategy

SERP API | Fast Search Result Scraping with our Google Searc…


										
							



Source link

How to Use Geolocation and Geocoding in React Native Apps
Strategy

How to Use Geolocation and Geocoding in React Native Apps


In this post, we will learn, how to implement Geolocation in a React Native application

Geolocation will find your current location and Geocoding gives your address (like City Name, Street Name, etc) by Coordinates (Latitude and Longitude).

What Is Geolocation?

The most famous and familiar location feature — Geolocation is the ability to track a device using GPS, cell phone towers, WiFi access points, etc. Geolocation uses positioning systems to trace an individual’s whereabouts right down to latitude and longitude, or more practically, a physical address. Both mobile and desktop devices can use Geolocation.

What Is Geocoding and Reverse Geocoding?

Geocoding is the method of remodeling an address or alternative description of a location into a (latitude, longitude) coordinate.

Reverse geocoding is the method of remodeling a (latitude, longitude) coordinate into a (partial) address. The amount of detail in a very reverse geocoded location description might vary. For example, one would possibly contain the complete address of the closest building, whereas another could contain only a city name and postal code.

You may also like: Geolocation With Titanium – Part 1.

Post Structure

We will go step-by-step to explore Geolocation.

Steps

  • Create a simple React Native app.
  • Install Plugins for Geocoding and Geolocation and get user location.
  • Get a user’s current location (Geocoding).
  • Convert user Geolocation into an address (Reverse Geocoding).

Three Major Objectives

  • Get user location in latitude and longitude (Geolocation).
  • Convert that latitude and longitude to street address (Reverse Geocoding).
  • Install plugins for Geocoding and Geolocation and get user location.

Step 1: Create a Simple React Native App

If you’re aware of native development, you’ll be familiar with React Native user interface.
It needs Xcode or Android Studio to get started.  If you already have one of these tools installed, you should be able to get up and running in minutes.

If they’re not installed, you should expect to spend about an hour installing and configuring them.

React Native CLI Quickstart
Assuming that you just have Node 10+ installed, you’ll be able to use npm to install the React Native cli command-line utility:

 npm install -g react-native-cli  

Then, run the following commands to create a new React Native project known as AwesomeProject:

 react-native init AwesomeProject

For details, you can check this link.

Step 2: React Native Geolocation Service

This library is created in an attempt to fix the location timeout issue on Android with the React Native implementation of Geolocation API. This library tries to solve the issue by using Google Play Service’s new FusedLocationProviderClient API, which Google strongly recommends over Android’s default framework location API. Which provider to use is based on your request configuration; it automatically decides and prompts you to change the location mode if it doesn’t satisfy your current request configuration.

Note: Location requests can still timeout, since many Android devices have GPS issues on the hardware level or in the system software level.

Installation:

Setup

No additional setup is requried for Android. For iOS, follow these steps: 

To enable Geolocation in the background, you will include the NSLocationAlwaysUsageDescription key in Info.plist and add location as a background mode in the Capabilities tab in Xcode.

Update Your Podfile

Then, run  pod install from the iOS directory.

Error Codes

NAME CODE DESCRIPTION
PERMISSION_DENIED 1 Location permission is not granted
POSITION_UNAVAILABLE 2 Location provider not available
TIMEOUT 3 Location request timed out
PLAY_SERVICE_NOT_AVAILABLE 4 Google play service is not installed or has an older version (android only)
SETTINGS_NOT_SATISFIED 5 Location service is not enabled or location mode is not
appropriate for the current request (android only)
INTERNAL_ERROR -1 Library crashed for some reason or the getCurrentActivity() returned null (android only)


Step 3: Get User Location (Geocoding)

Since this library was meant to be a drop-in replacement for the RN’s Geolocation API, the usage is pretty simple, with some further error cases to handle.

One issue to notice, this library assumes that location permission is already granted by the user, thus you have to use PermissionsAndroid to request permission to track user location before creating the placement request.

For obtaining user location, you have to import Geolocation API from a react-native-geolocation-service package like this.

import Geolocation from ‘react-native-geolocation-service’; 

Then, add this block to your code: 

So after adding all this code your file something look like this:

Step 4: User Geolocation Into an Address (Reverse Geocoding)

We used a react-native-geocoding package for Geocoding and Reverse Geocoding. 

This module uses the Google Maps Geocoding API and requires an API key for quota management. Please check this link to obtain your API key.

Installation

npm install –save react-native-geocoding 

You can just import Geocoder API from a react-native-geocoding package in your App.

import Geocoder from ‘react-native-geocoding’;  

And then you have to initialize the module in your app

A working example of Geolocation and GeoCoding to React-Native Apps.

Conclusion

In this blog, we learned how to implement the Geolocation React Native app. We also learned how to Convert Geocode in the Location address in a simple React Native app.

Further Reading



Source link