Saturday, July 30, 2022

Read a File Line by Line With PHP

Read a File Line by Line With PHP

There are two reasons why you might want to read a file line by line with PHP. First one is that the project you are working on requires you to process the file one line at a time. Second is that you are reading a very large file and the only way to read it without going over the memory limit is to do it one line at a time.

Using file() to Read the File

You can use the file() function in PHP to read the entire file at once into an array. The array elements are individual lines of the file. So you will be able to iterate over the lines in the file by iterating over the array. The function accepts three parameters:

  • filename: This is the file that you want to read. You can also supply a URL as filename.
  • flags: This is an optional parameter and can be set to one or more of the following constant values: FILE_USE_INCLUDE_PATH, FILE_IGNORE_NEW_LINES and FILE_SKIP_EMPTY_LINES.
  • context: This is also an optional parameter used to modify the behavior of a stream.

We will be using the FILE_SKIP_EMPTY_LINES flag to skip all the empty lines in a file. You might also want to use FILE_IGNORE_NEW_LINES to remove line endings from individual lines.

This function returns an array with the file contents upon success and false upon failure. You will also get an E_WARNING level error if the file does not exist. Here is an example of using this function.

The output of the above code looks like this:

You can see that there are some empty lines in the output, we can get rid of them by using the FILE_SKIP_EMPTY_LINES flag. Also, it might not be evident but the lines above include the newline character. That is why we did not have to add a newline character of our own while echoing the lines. You can get rid of the blank lines by using the FILE_IGNORE_NEW_LINES flag.

The output with those flags will look like this:

Using the file() function is an easy way to read a file line by line in PHP if you are not worried about memory usage. However, you will have to get more creative if memory usage is an issue because file() reads the entire file into an array at once.

Using fgets() to Read the File

Another way to read a file line by line with PHP is to use the fgets() function. It has one required parameter which is a valid file handle. We will use the fopen() function to get access to the file handle. Here is the code that we are going to run:

On the first line, we open our file in read-only mode. Then, we define a function which accepts a $file_handle as parameter and gives back a single line. Please note that we are using a yield statement and our function get_all_lines() is a generator function. You might want to read about generator functions in PHP if you haven't used them before.

We are using the feof() function inside get_all_lines() to check whether our file pointer has reached end-of-file. We only yield as long as we are not at the end of file. You should get the following output by running the code above:

The outputs looks the same as our previous section. The only difference this time is that you are no longer in danger of running out of memory.

I mentioned earlier that fgets() will allow you to read one line of the file at a time and it only requires a single parameter that points to the file pointer for the file that you want to read. The memory consumption in this case would depend on the length of the line and there is a little chance of you running out of memory.

However, lets say you are reading a text file which contains unusually long lines. You can then pass an optional second parameter to the fgets() function which specifies the number of characters that you want to read. It will then read length - 1 bytes from the file before stopping. It will stop earlier if it comes across a newline or end of file. This gives you more control over the memory consumption of your code.

Final Thoughts

I have discussed two methods of reading a file line by line with PHP in this tutorial. There are a couple more ways of doing this but these two will meet almost all your needs. Use the file() function when memory consumption is not an issue and use fgets() with a generator function if you want to conserve memory.


Wednesday, July 27, 2022

8 Best Free JavaScript Graph Visualization Libraries

8 Best Free JavaScript Graph Visualization Libraries

When working with large amounts of data, you are likely to come across situations where the data has to be represented visually with the help of graphs.

A graph is a structure amounting to a set of objects in which some pairs of the objects are in some sense "related". They are basically mathematical structures used to model pairwise relations between objects. (Wikipedia)

If you implement everything on your own, visually representing data in form of graphs will require you to spend significant amount of time on writing the code for handling the graph structure. In this post, we have created a list of some of the best free JavaScript graph visualization libraries that will do all the heavy lifting for you.

People generally use the terms graphs and charts interchangeably. We have also got you covered with a list of best free JavaScript charting libraries if you were looking for those instead of graph visualization libraries.

1. D3.js

The first library that comes to mind whenever you are doing anything related to visualization of any kind of data either in the form of charts or graphs in D3.js. The D3 is short for Data-Driven Documents. It uses a combination of HTML, SVG and CSS to create visual representation of data.

D3.js Graph Visualization LibraryD3.js Graph Visualization LibraryD3.js Graph Visualization Library

The library basically allows you to bind arbitrary data to the DOM. After that it is possible to create all types of charts and graphs based on this data. The library gives you access to different methods and functions that you can use to make element selections. It also allows you to dynamically set the property values of different elements based on given data.

You can visit the website D3 Graph Library to see all the possibilities. It contains a bunch of different charts and graphs to show you the capabilities of D3.js.

One important thing to keep in mind is that the library does not come with built-in methods to help you directly create any bars or charts by calling a single method. You will have to implement that functionality on your own. However, it comes with a lot of helper functions to help you do all those things relatively easily.

2. Neo4j

As I mentioned earlier, D3.js is a powerful library for creating all kinds of graphs and charts. However, it requires you to do a lot of work in order to create any kind of graph visualization. One way to overcome this limitation is to use helper libraries based on D3.js which do all the basic heavy-lifting for you.

Neo4j Graph Visualization LibraryNeo4j Graph Visualization LibraryNeo4j Graph Visualization Library

One example of such a library is Neo4j. It has several useful features such as compatibility with multiple data formats, force simulations, double click callbacks, and custom node colors based on the node type. You can also show information about different nodes and their relationship with each other inside an info panel.

You can zoom and pan through the graph. The library also has auto-fit and relationship auto-orientation features. Dragging a node will make it sticky and clicking it again will take it back to its initial non-sticky state.

You can also provide callbacks for different events using options like onNodeClick, onNodeDoubleClick, onNodeDragStart, onNodeDragEnd etc. The example on the website adds a bunch of new nodes attached to the original node on each double click event.

3. React D3 Graph

React D3 Graph is yet another D3.js based graph generation library that allows you to create interactive and configurable graphs with React.

The library comes with a main graph component that will allow you to build the actual graph once you pass all the relevant data to it. You can also optionally provide configuration information as well as callback functions to handle user events like node click and link click.

Keep in mind that this library does not come pre-packaged with React and D3.js. You will have to install those libraries separately. This gives you the freedom to independently choose separate versions of the libraries as long as they are above the minimum requirement.

There are a bunch of configuration options that you can specify for each graph, for example to make it directional, zoom on focus, change the animation duration during focus, or use panning and zooming behavior. You can also disable any drag-and-drop related manipulations of the graph or make the graph completely static.

4. VivaGraphJS

VivaGraphJS is a dependency-free library that you can use to render graphs. The library is extensible and comes with support for multiple rendering engines and layout algorithms. There are a lot of related modules that you can install to get required functionality into your graphs. This includes support for basic events, force directed graph layouts and storing graph data in JSON format.

The library offers a lot of customization options. You can change the appearance of nodes and links with little effort. Similarly, you have full control over the layout algorithm and the medium used to display the graph. For instance, you can tell the library to use WeBGL for rendering your graphs instead of SVG which it uses by default.

Any graphs that you render on the webpage will have a different structure based on factors such as the numbers of nodes and the number of connecting edges etc. You can use a bunch of parameters like springLength, springCoeff and gravity etc. to tune the physics so that the graphs you render look great.

5. Graphology

The Graphology library is a robust and multipurpose package written in JavaScript and TypeScript. The aim of the library is to add support for multiple types of graphs using the same unified interface. This allows you to create a wide variety of graphs that can be directed, undirected or mixed. You can also decide on features like whether to allow self-looping or support parallel edges.

Graphs that you create using graphology can emit events for a large variety of actions such as adding or removing a node as well as adding or removing an edge. There are also events that get triggered with node or edge attribute updates.

You can also include a lot of standard helper libraries in your project to get additional functionality. This includes things like the canvas package for rendering on the canvas or the shortest-path package with functions for applying common search algorithms like Dijkstra algorithm.

A separate library that works really well with Graphology is Sigma.js. It gives you access to a WebGL renderer and helps you create interactive graphs.

6. Cytoscape.js

Cytoscape.js is yet another great library for graph theory visualization and analysis of data. You can use it to visualize all kinds of relational data like social network connections or biological data. The library comes with a graph theory model and an optional renderer to display your interactive graphs. It is an all-in-one package to handle all your graphing needs.

The library is highly optimized and comes with good browser support. The support for browsers goes as far back as IE10 with partial support for IE9. All modern browsers enjoy fantastic support. The library also supports use of selectors for filtering and graph querying. It also uses stylesheets to keep data separate from presentation.

There is built-in support for standard gestures on both desktops and mobile devices. It has support for set theory operations and includes graph theory algorithms such as BFS and PageRank. You can be rest assured about the quality of the library because it is used by big companies such as Amazon and Google as well as government organizations.

You can read the Cytoscape.js documentation to get started with the library.

7. Arbor

Arbor is a simple graph visualization library that has been built using web workers and the jQuery library as its foundation. Unlike some other libraries in this list, Arbor does not aim to be a complete all-in-one solution.

It simply provides you an efficient, force-directed layout algorithm along with other abstractions for graph organization. It also comes with built-in support for handling screen refresh events. This simply means that the rendering of the data on the webpage is left to the developer. You are free to use canvas, SVG or HTML elements in order to create the graph depending on the needs of your project.

8. Force Graph

You can use the Force Graph library to render force-directed graphs on the HTML5 canvas. While the library uses the HTML5 canvas for rendering, it relies on the D3 force library to take care of the underlying physics. There is support for zooming and panning across the canvas. You can also drag the nodes around or listen to click and hover events for the nodes and their links.

There are plenty of methods available to control the styling of nodes as well as links. You can also use a bunch of methods to control how different elements of the graph are rendered.

What if you want to render your graph in 3D? Luckily, the library also has a 3D version that relies on WebGL and ThreeJS to handle the rendering. The underlying physics of the graph is taken care of either by the D3 force 3D library or the ngraph library.

Final Thoughts

Visualization of complicated data in form of graphs can help us easily understand the relationship between different entities. Graphs will help you convey data that is too large and complicated to be explained easily with just textual information.

In this post, we have provided you a brief overview of some of the most popular JavaScript libraries that help you visualize information in form of graphs. One of these libraries will likely meet your project needs. However, you can also search for graph visualization libraries on GitHub for more options.


Tuesday, July 26, 2022

What Is Unretirement? (And How Can It Help Your Business?)

What Is Unretirement? (And How Can It Help Your Business?)

While the news media focused on the Great Resignation, a different phenomenon has been trending: unretirement.

back to workback to workback to work
Why are retired workers going back to work? Keep reading to find out. (Image source: Envato Elements)

What is unretirement? Unretirement, also known as “retirement reversal” or “post-retirement work,” is when a retiree comes out of retirement and goes back to work. The All-America Workforce Survey by CNBC found that 68% of workers who retired during the pandemic would consider going back to work.

In this article, we’ll discuss why unretirement is growing. We’ll also go over what to consider when weighing the pros and cons of unretirement, from the points of view of both the employer and the retiree.

Reasons Why People Unretire

jobs for retireesjobs for retireesjobs for retirees
Retirement may be fun at first, but some retirees soon look for more stimulation and meaning. (Image source: Envato Elements)

The word “retirement” conjures images of traveling the world, sleeping in, spending hours at the golf course, or finally decluttering your home. But in reality, retirees soon discover that retirement isn’t the blissful existence they expected it to be.

Retirees may choose to unretire for one or any combination of the following reasons:

1. Boredom 

“Retirement is just a never-ending vacation” is a common belief. But when you’re suddenly confronted with an empty calendar, boredom can quickly set in. Among Canadian retirees surveyed, for example, the top three things they most miss about work are:

  1. the people and social stimulation (39%)
  2. the pay (22%)
  3. having goals and projects (8%).

2. Purpose

It’s common for new retirees to have an identity crisis. After all, they’ve spent the majority of their adult lives working. And for many of us, our jobs or careers are a significant part of our identity. We may also derive a lot of confidence and self-esteem from our accomplishments at work. And so, when that's suddenly gone, it’s sure to leave a gaping void. 

Traveling and being able to do pretty much whatever you want and when you want to are all great—at first. Eventually, a person can grow tired of having too much leisure and look for more meaningful activities.

"You can't retire from being great." - Anonymous

3. Finances

Another reason retirees might return to work is because they need the money. A study in the United Kingdom found that retirees who have a mortgage are more likely to leave retirement than those who’ve already paid up and own their house. 

As post-pandemic inflation rises, more retirees are finding it harder to live within their limited and fixed incomes. Many of them may be forced to seek employment for financial reasons. Sadly, some people simply can't afford to retire.

4. Opportunities

jobs for retirees - hot job marketjobs for retirees - hot job marketjobs for retirees - hot job market
The Great Resignation has opened up many jobs for retirees. (Image source: Envato Elements)

A retired person could unretire because of the plentiful and attractive opportunities available. The Great Resignation means that many roles are open, including retirees' jobs. Employers are piling perk after perk to lure employees. A hot labor market is very attractive to retired workers who are bored, broke, and looking for meaning.

5. Health

"You don't stop laughing when you grow old. You grow old when you stop laughing." - George Bernard Shaw

Finally, a retired person may choose to come out of retirement because they believe it'll improve their physical and mental health. Retirement may cause a person to become sedentary (despite having the time to exercise). Whereas employment may force them to be more active, both physically and mentally. 

A study by the Oregon State University found that working beyond the age of 65 years is associated with a longer lifespan. Even respondents who considered themselves unhealthy were likely to live longer if they kept working. Moreover, researchers in France found that working longer reduces a person’s risk of getting dementia.

As you can see, there are many reasons why retired people can find unretirement very attractive! But unretirement can also be advantageous to employers.

Unretirement and Your Business

If you’re an employer desperate to fill vacancies, unretirement may sound like a good solution. The question remains, should you encourage retired employees to return back to work for you?

The Pros of Hiring Retired Employees

Hiring former employees who’ve retired has many advantages. They already have the skills and experience for the job. This means you don’t have to spend as much money and time training them when they return to their old jobs. 

retirees jobsretirees jobsretirees jobs
Older employees bring many strengths to the job. (Image source: Envato Elements)

Another benefit of rehiring retired workers is that it lowers your recruitment costs and time. You don’t have to spend money advertising the opening far and wide. You don’t have to conduct three interviews or do skills tests.

There’s also less risk. You already know this employee. They've got a track record with your company. And most importantly, you know exactly how they’ve performed the job and interacted with co-workers in the past. 

The Cons of Hiring Retirees

Rehiring previously retired employees isn’t all rainbows and unicorns, though. It can have disadvantages as well.

For one thing, if the employee retired several years ago, their knowledge and skills may be outdated. This is especially true for cutting-edge industries where innovations grow by leaps and bounds every year. You can of course still hire a retiree but know that you’ll have to invest in their training to get them up to speed.

Retired former employees may also be looking for different work arrangements than what they had when they were working for you. In the same workforce survey by CNBC, they found that retirees would consider returning to work if the job offered:

  • flexible hours (47%)
  • a good salary/pay (44%)
  • better work-life balance (30%)
  • some of them are also looking for care and retirement benefits (10%).

Another disadvantage of hiring retired workers is the risk that they may not stick around long. They may simply be looking for part-time work as a way of gently transitioning into full-time retirement. This means you could be in the same situation, looking to fill the job, a few months to a year down the road.

How to Entice Former Employees to Unretire

Ready to call retired former employees and offer them jobs? Increase your chances of success by making the offer as attractive as possible. Remember, in this post-pandemic job market, employers are throwing all kinds of benefits to attract workers. If you decide to offer jobs for retired people, your offer must be competitive. 

jobs for retirees-interviewjobs for retirees-interviewjobs for retirees-interview
Make jobs for retirees more attractive by offering perks. (Image source: Envato Elements)

Keeping in mind the reasons people unretire and the CNBC survey findings mentioned above, think of offering the following perks:

  • flexible working hours
  • competitive salaries
  • performance bonuses
  • more paid vacation days
  • paid sick days
  • remote work options
  • learning opportunities
  • mentoring programs
  • health insurance coverage
  • dental and vision coverage
  • retirement benefits
  • gym membership allowance
  • computer and/or mobile phone allowance
  • team bonding activities

These are only some of the benefits and perks that make jobs after retirement more attractive to former employees. 

Should or Can You Unretire? Things to Consider

Let’s turn the table around and look at unretirement from the point of view of the retired worker. If you’re already retired, should you unretire? Here are a few things to consider:

1. How Many Hours Do You Want to Work?

You may be bored now, but does that mean you want to work eight hours a day, five days a week? Or would working part-time give you enough of the social interaction, physical activity, and intellectual stimulation you crave? Also, think about the activities you've got right now. If you're the primary babysitter of your grandchildren, can you unretire?

2. Do You Want to Do the Same Thing?

Another area to consider is whether you want to return to your old job (or something similar) or try a role that’s completely new to you. With the job market being hot right now, you may find plenty of job opportunities. Now's the perfect time to pursue a passion you've always been interested in but never had the chance to do professionally.

jobs for retireesjobs for retireesjobs for retirees
Unretirement is the perfect opportunity to switch to a different line of work. (Image source: Envato Elements)

If you want to do what you’re good at but without a lot of stress, another option is to go into the same field but at a lower level of responsibility. For example, if you retired as a marketing director, you could go back to the workforce as a marketing coordinator.

3. Where Do You Want to Work?

Something happened during the pandemic. Employers and employees alike discovered that many jobs can be done just as well at home as in an office. And so, another consideration is whether you want to work in person, remotely, or a combination of both (hybrid).

4. Can You Afford to Work?

retirees jobsretirees jobsretirees jobs
Do the math to determine if you can afford to go back to work. (Image source: Envato Elements)

As you think about getting employed again, don’t forget to factor in the cost of working. This is especially important if you’re returning to employment for financial reasons. The cost of working includes the cost of getting to work, such as fuel for your car, parking, commuting fare, and the like. You may also need to buy a new wardrobe. If you’re working remotely, you might need a better computer and internet connection. Some employers cover these costs, but not all.

Also think about how the new income will affect your pension benefits and taxes. It may put you on a higher tax bracket, for instance. This means your after-tax income may not be as big as you thought it would be.

And consider how extra income will affect your pension and old age benefits. These may be reduced or taken away altogether, depending on how much salary you’re making. Can you unretire without compromising your pension income? Laws are different depending on where you live, so consult an accountant or financial planner to know what applies to you.

5. Is a Job the Answer?

Whether you’re looking to unretire for stimulation or for financial reasons, realize that employment isn't the only solution. If you’re bored, maybe volunteering a few days a week at a local charity could provide enough stimulation—without the pressure and stress of a job.

jobs for retireesjobs for retireesjobs for retirees
Starting your own business is another form of unretirement. (Image source: Envato Elements)

If you want to augment your income and none of the jobs for the retired appeals to you, starting a home-based or online business may be the way to do it. Entrepreneurial ventures and volunteer service are other forms of unretirement, too, according to Chris Farrell in his book, Unretirement: How Baby Boomers are Changing the Way We Think About Work, Community, and the Good Life.

Unretiring is an important decision. Here are some articles to help you think through unretirement:

Ageism and Unretirement

Unretirement is optimized when we break down ageism or the negative stereotypes we have of older people. There may be societal beliefs that life beyond a certain age is a time of physical and mental decline, obsolescence, and worthlessness. Some managers may also perceive older workers as being set in their ways and resistant to change. That’s ageism.

Ageism in the workplace causes older employees to miss out on professional development opportunities. It also forces workers into mandatory retirement once they reach a specific age—even if they've got excellent health and mental capacity and are happy to keep working. Another form of ageism is opening up job opportunities only to people who belong to an age demographic.

retirees jobs - ageismretirees jobs - ageismretirees jobs - ageism
The percentage of older employees who experienced ageism has increased. (Image source: Envato Elements)

And ageism seems to be getting worse. According to research by the American Association of Retired Persons (AARP) in 2020, 78% of older workers have either seen or experienced age discrimination in the workplace—up from 61% in 2018.

Unretirement helps fight ageism, too. With more older employees in the workforce, they can prove that age doesn’t matter. In fact, having a longer work experience can be an asset.

"Retirees who return to the workforce now are finding employers desperate for their skills and experience," noted Julia Pollock, ZipRecruiter’s chief economist.

Unretirement: A Fresh New Option for Work

retirees jobs - retirement is not foreverretirees jobs - retirement is not foreverretirees jobs - retirement is not forever
Retirement doesn't have to be forever. (Image source: Envato Elements)

Unretirement can be a terrific new option for both employers and retirees alike. Employers can use it to gain experienced, trained workers while saving on recruitment and training costs.

For retirees, unretirement can give meaning, stimulation, socialization at a more relaxed pace than regular employment. It can also provide financial and health benefits. Who knew working could be so good for you?

The bottom line is: retirement doesn’t have to be forever. If you’re an employer, remember that retired former employees may be enticed to come back. They’re another talent pool and resource you shouldn’t overlook. If you’ve gone into retirement and found it underwhelming, then see if unretirement could be for you. This just might be your moment for a comeback.