DEV Community
The most recent home feed on DEV Community.ActionChat to start your day off right!
20 May 2018, 6:48 am
Announcing ActionChat, a mobile app where you are surrounded by like-minded people who inspire each other to make the most of the day!
I often hear that the key to a productive day is having a solid morning routine. When people talk about morning routines, they usually mention exercising, a shower, meditation, a cup of coffee, and reviewing the day's tasks. This is a great way to start the day, but many people struggle to get into their routine. The goal of this app is to allow people to chat with each other first thing in the morning to motivate each other to take control of their day!
I think Pusher Channels will be a great API for this app. I've done some tutorials with Firebase in the past, but I'm always on the lookout for the best tools out there. I'm looking forward to trying out Pusher Channels and making an awesome app!
Tech stack
Stay tuned for updates!
Thanks for reading,
- Andrew
Intersection of a vector with a sphere
20 May 2018, 6:02 am
A good friend of mine wanted some help with a VR project to see if a ray (controller's motion vector) is intersecting with a spherical viewport of the user. Here's a rudimentary java program to check for a vector intersecting a sphere.
User input <- Coordinates of the two points of the vector and the coordinates of the sphere center and sphere radius
Output -> Coordinates of the point(s) of intersection
Have not programmed in Java for a couple of decades so was an interesting and enriching experience as the program slowly got built out, refined and refactored (to the best of my ability). Sure it's not computationally efficient but hoping to make it an API to use within Unity at some point!
/** Copyright - Trivikram Prasad
Date: May 19, 2018
All Rights Reserved
*/
// Program to calculate the points of intersection of a vector with a Sphere
import java.util.Scanner;
// DEFINE ALL CLASSES
// 3D Point class
class Point3D{
double x,y,z; //Coordinates of a point
public Point3D (double x, double y, double z)
{
this.x = x;
this.y = y;
this.z = z;
}
}
// Sphere Class
class Sphere{
double cX, cY, cZ; // Coordinates of the sphere center
double cR; // Radius of sphere
public Sphere (double cX, double cY, double cZ, double cR)
{
this.cX = cX;
this.cY = cY;
this.cZ = cZ;
this.cR = cR;
}
}
// String class -- only for formatting output
class StringPoint{
String pX, pY, pZ; // Converting coordinate values to string values for formatting
public StringPoint (String pX, String pY, String pZ)
{
this.pX = pX;
this.pY = pY;
this.pZ = pZ;
}
}
// The main class. This is where the real s**t happens
public class lineSphereX {
public static void main(String[] args){
double a,b,c; // Coefficients of the quadratic equation
double discr; // Square of the discriminant of the quadratic
double t1 = 0.0; // parameter 1
double t2 = 0.0; // parameter 2
Scanner in = new Scanner(System.in);
// Read coordinates of the first point on the line
System.out.print("Enter x, y, z coordinates of the 1st point on the line: ");
Point3D point1 = readLineInputCoordinates(in);
// Read coordinates of the second point on the line
System.out.print("Enter x, y, z coordinates of the 2nd point on the line: ");
Point3D point2 = readLineInputCoordinates(in);
// Read center coordinates and radius of sphere
System.out.print("Enter x, y, z center coordinates and RADIUS 'r' of the sphere: ");
Sphere sphCenter= readSphereInputCoordinates(in);
in.close();
//Calculate coefficients: 'a', 'b', 'c' for the equation 'ax^2 + bx + c = 0
a = Math.pow(point2.x - point1.x,2) + Math.pow(point2.y - point1.y,2) + Math.pow(point2.z - point1.z,2);
b = 2 * ((point2.x-point1.x) * (point1.x-sphCenter.cX) + (point2.y-point1.y) * (point1.y-sphCenter.cY)+ (point2.z-point1.z) * (point1.z-sphCenter.cZ));
c = Math.pow((point1.x - sphCenter.cX),2) + Math.pow((point1.y - sphCenter.cY),2) + Math.pow((point1.z - sphCenter.cZ),2) - Math.pow(sphCenter.cR, 2);
discr = Math.pow(b, 2) - (4*a*c);
// No intersection points`
if (discr < 0)
{
System.out.println("\nVector does not intersect the sphere");
return;
}
else if(discr == 0) // Single intersection point
{
System.out.println("\nVector intersects the sphere at a single point:");
if (a > 0)
{
t1 = -b/(2*a);
StringPoint XPoint = findXPoint(point1, point2, t1);
System.out.println("The tangent to sphere is at " + XPoint.pX + ","+ XPoint.pY + "," + XPoint.pZ + "\n");
}
else{
System.out.println("Not a line\n");
}
}
else // Two intersection points
{
System.out.println("\nVector intersects the sphere at two points");
t1 = (-b - Math.sqrt(discr))/(2*a); // 1st Vector equation parameter
t2 = (-b + Math.sqrt(discr))/(2*a); // 2nd Vector equation parameter
// Find the points of intersection
StringPoint XPoint1 = findXPoint(point1, point2, t1);
StringPoint XPoint2 = findXPoint(point1, point2, t2);
System.out.println("1st point of vector intersection with sphere: " + XPoint1.pX + "," + XPoint1.pY + "," + XPoint1.pZ);
System.out.println("2nd point of vector intersection with sphere: " + XPoint2.pX + "," + XPoint2.pY + "," + XPoint2.pZ + "\n");
}
System.exit(0);
}
// Function for user input of sphere center coordinates and radius
private static Sphere readSphereInputCoordinates(Scanner input) {
double sphere_ctr [] = new double[4];
Sphere input_sphere = new Sphere(0,0,0,0);
for (int i = 0; i < 4; i++)
{
sphere_ctr[i] = input.nextDouble();
}
input_sphere.cX= sphere_ctr[0];
input_sphere.cY = sphere_ctr[1];
input_sphere.cZ = sphere_ctr[2];
input_sphere.cR = sphere_ctr[3];
return input_sphere;
}
// Function for user inputs of point coordinates
private static Point3D readLineInputCoordinates(Scanner input) {
double line_pt [] = new double[3];
Point3D input_coords = new Point3D(0,0,0);
for (int i = 0; i < 3; i++)
{
line_pt[i] = input.nextDouble();
}
input_coords.x = line_pt[0];
input_coords.y = line_pt[1];
input_coords.z = line_pt[2];
return input_coords;
}
// Function to calculate the point of intersection
private static StringPoint findXPoint(Point3D point1, Point3D point2, double t) {
Point3D intPoint = new Point3D(0,0,0);
StringPoint XStrPoint = new StringPoint("","","");
// Parametric equation of the form L = P + tU
// where 'L' is the intersection point, 'P' is the point on the line and
// U is the unit vector (Point2 - Point1)
intPoint.x = point1.x + t * (point2.x - point1.x);
intPoint.y = point1.y + t * (point2.y - point1.y);
intPoint.z = point1.z + t * (point2.z - point1.z);
XStrPoint = formatString(intPoint);
return XStrPoint;
}
// Function to format the coordinates to string for display/output to console
private static StringPoint formatString(Point3D intPoint) {
StringPoint strPoint = new StringPoint("","","");
strPoint.pX = String.format("%.2f", intPoint.x);
strPoint.pY= String.format("%.2f", intPoint.y);
strPoint.pZ = String.format("%.2f", intPoint.z);
return strPoint;
}
}
Data Transformed into Knowledge, & Knowledge into Power
20 May 2018, 5:50 am
âIt is about becoming a mathematical thinker, not a calculatorâ
Whenever someone asked a crowd of people, if they agree that Knowledge is Power, surely you're going to get a BIG YES as an answer. 21st century, is experiencing the fourth industrial revolution: Data. Rarely, we think in the amount of new data that we are creating everyday without noticing it, and thanks to some mathematical thinkers, linear regressions may be used to give a meaning to the data that surrounds us, and transform it into knowledge so that people that manage industries and companies, can make the right decision for their businesses.
And once again, mathematics is behind of this discovery: linear regressions. It is a method that belongs to a section called, Numerical Methods, which are iterative, high performance and high precision algorithms designed to solve numerical problems by finding convergence points, that are an approximation of the solution for a mathematical problem. What linear regressions do, is find an approximated relation between independent variable(s) and a dependent variable, which lie in x-axis and y-axis respectively. This relation is represented in an equation that is measured and chosen under the least square method criteria, because we are seeking an enough accurate equation that can be used to make future predictions. For example, find out the expected number of car accidents in a certain location, like Miami, for a certain period, like New Years Eve.
Linear Regression Model
Now that we know what linear regressions are for, I'm going to describe the steps to implement it with a simple example. First, it is important for you to know that linear regressions need data as an input, in order to give statistical results as an output. The steps to follow are:
- create a function for least square (lsq) method
- create/import data
- chose feature(s) as your independent variable(s)
- choose target as your dependent variable
- assign coefficients m & c with lsq method
- define regression line (linear, logarithmic, exponential)
- graph dispersion data with regression line
- create a table of approximated predictions
This is the process to follow if you want to run linear regression models with your own methods, but there is another way in R to code linear regression models by using some R packages and functions, in which you won't have to create lsq method nor assign coefficients m & c. If you want to see this other option, I'll leave you my complete code for linear regression demo.
Linear Regression Example
For this example, I'll import a dataset that shows China population in millions from 1900's through year 2010. We'll compare linear and exponential regressions, to see which fits best, and predict China's population for next years.
#Independent Variable
years <- c(1900,1950,1970,1980,1990,2000,2010)
years2 <- seq(1900,2010,1)
#Dependent Variable
people <- c(400,557,825,981,1135,1266,1370)
people_ln <- log(people)
#Coefficients m & c
m2 <- lsq_m(years, people_ln)
c2 <- lsq_c(years, people_ln)
people2<-c()
i=1
while(i<(length(years2)+1)) {
value<-exp(c2) * exp(m2*years2[i])
people2<-c(people2,value)
i=i+1
}
Dispersion of Data
ggplot() +
geom_point(aes(x = years, y = people), colour = 'red') +
ggtitle('Population by Year Dispersion') + xlab('Year') + ylab('Population')
Linear Regression Model
ggplot() +
geom_point(aes(x = years, y = people_ln), colour = 'red') +
geom_line(aes(x = years, y = m2*years + c2), colour = 'blue') +
ggtitle('Example 2: Linear Regression') + xlab('Years') + ylab('Population')

It returns a 91.06% of accuracy, which means that 91.06% of variance in China Population is due to the variance of years. With this indicator, we could accept it as a fair model, but not so fast! Let's see how it behaves the exponential regression model before we run into conclusions.
Exponential Regression Model
ggplot() +
geom_point(aes(x = years, y = people), colour = 'red') +
geom_line(aes(x = years2, y = people2), colour = 'blue') +
ggtitle('Example 2: Exponential Regression') + xlab('Years') + ylab('Population')

As I suspected, exponential regression model return a better percent of accuracy. This model shows that 96.27% of variance in China Population is due to the variance of years.
Don't get confused, linear regression model isn't bad, but for this dispersion of data, an exponential regression model has proved to be a more accurate model. So now, we can conclude that China Population shows an exponential growth rather than a lineal growth.
Predictions
For this section of the article, we want to predict China's population from 2011 to 2020. And this are the following results:
| Year | China Approximated Population (millions) |
|---|---|
| 2011 | 1386.023 |
| 2012 | 1402.740 |
| 2013 | 1419.658 |
| 2014 | 1436.779 |
| 2015 | 1454.108 |
| 2016 | 1471.645 |
| 2017 | 1489.394 |
| 2018 | 1507.357 |
| 2019 | 1525.537 |
| 2020 | 1543.936 |
Conclusion
Hope you could see how data can be transformed into knowledge, because having an accurate approximation of China's Population for example, could be useful for multiple things and multiple individuals, like government, marketing agencies and investors. Personally, I consider that this is the objective of linear regressions, to be used in order to explore through the data you and I, and everybody is generating, so that we can discover insights and conclusions that we couldn't have found without having the correct information in our hands.
The right way to implement authentication using cookies, according to you.
20 May 2018, 3:52 am
The internet is full of opinions when it comes to implementing authentication and the use of sessions/cookies. We all agree that storing passwords in cookies or setting a value like admin = true is a very bad idea. We also have to deal with the prevention of XSS cookie stealing. (appending document.cookie to an <IMG> element src attribute or whatever)
In many cases we also want to prevent that a 'saved' cookie will successfully authenticate a different client or device when copied.
In your experience, what is the right way to handle authentication? In PHP, JavaScript or whatever language / framework you happen to prefer?
Going to bed by 10pm and stop playing World of Warcraft - Day 5
20 May 2018, 12:33 am
Good day boys and girls.
Welcome to another entry on this journey:
- Go to bed by 10pm
- Stop playing World of Warcraft (again).
If you are not familiar with what's going on here, I invite you to check out the intro to the series.
I hope while you read this, it helps you take action on whatever you are trying to improve in your life.
Let's continue the journey.
Day 5
-
Coming homeđ
I had to rush home, shower and get back out.Why? It was date night. It was the first date night the missus and I had in a very long time. It was long overdue.
We had been looking forward to it since the beginning of the week. We had been talking about it like two teenagers whose parents were out of town!
-
Da plan đ
The night plan was very simple:- Drop off the kids (6pm-9pm)
- Have some drinks
- Watch a movie (Deadpool 2)
A fine evening if you ask me.
Luckily, all places were very close to each other. This helped us save a lot of driving time.
-
Drinks đ„
After dropping of the kids, we went to our favorite spot for food and drinks.It was great taking off the parent hat. We have a rule when we go out on dates: we don't talk about our kids.
It may sound harsh and probably heartless, but it works for us.
The drinks and food were good as always. We were just shooting the breeze until the movie started. We were having such a great time that we almost ditched the movie and continue drinking and just chillin'.
-
Movie đŠ
The movie was great. I won't spoil it for you.It had been a very long time since we sat next to each other. I felt like our early days when we used to go out to the movies on a weekly basis.
We agreed that we needed to go out alone more often.
-
Pick up + Home đ
After the evening was over, we were all home at around 9:30pm. I was about to stay in bed and crash for the night.Then, I remember I had to wrap up my Day 4 entry. It drove me passed 10pm.
No regrets. I'm glad to share this adventure to you.
The good news is that I passed out as soon as I got to bed shortly after 10pm.
How did we do? đ€
-
Get to bed by 10pm? â
Missed it by a few minutes.It's OK. I won't let my judge guilt trip me because I was late only a few minutes.
I got to spend more quality time with my best friend. Also, letting out some steam without wearing the parent hat helped me out a lot.
-
Stop playing World of Warcraft â
A day like this one made this part super easy.I'm glad I stopped playing a few days ago. I was present while having some drinks with the missus and enjoying the movie.
I wasn't distracted by rushing to come home to get my "fix". This is already paying itself in less than a week.
Conclusion
After a great evening with the missus, I'm OK not getting to bed at 10pm. As I mentioned, I got in bed very shortly after 10pm.
I'm slowly getting back to my old self. My anxiety and withdrawal are improving because I didn't feel rushed to get home to play World of Warcraft.
I like where this is going.
What would your journal say? đ
Thanks for reading. Till tomorrow1
3 Reasons Why You Should Use Figma Instead of Adobe XD For UI/UX Design (Read Time: 1 Mins)
20 May 2018, 12:00 am
Introduction
For those who had been living under the rock. You might have heard that Adobe has just started to offer a free tier plan of Adobe XD.
I just dropped XD cause there wasn't a free tier plan when it was first released. Which lead me to stumble across Figma while searching for videos on Youtube to gain knowledge in building UI/UX designs.
When it became relevant for my job in finding free and useful design tool that works on Linux. I used Figma to design UI/UX prototypes to save time and avoid effort before building it on Django.
Reason 1 - Awesome Free Tier Plan
Figma allows you to share your designs to your developer, product manager and clients without them needing to download any software to view/edit using your web browser.
Besides that, it allows up to 2 people to edit the same design with an endless amount of viewers at real time.
Therefore it's great for startups who have small development teams to take advantage of this to build their own MVP or UI/UX designs with it.
Reason 2 - Non-Designer Friendly
Most UI/UX design tools that I came across are usually catered for 2 types of users.
One that is feature rich but has a huge learning curve and the other which is minimalist to the point that you can't do much with it unless you pay for additional features.
What Figma offered was minimalist in design like working in Google Docs but jam pack with features that truly lets you get things done to avoid effort to build awesome designs.
Reason 3 - Developer Handoff
The awesome part of Figma is the developer handoff aspect for Figma,
When you hand off your UI/UX designs to your developer, it allows mobile app developers for Android or iOS to download the code of your Figma design to be used for their development.
If your a web developer like myself you can actually look at the CSS code to make your website look almost exactly like your design in Figma.
Plus you get to be able to download various components of your design to SVG that greatly speeds up your time to develop your frontend on React, Angular or Vue.
With the latest update, there's a REST API that allows you to export your Figma designs to React.
References
If you like my article either sign up for max adventurer's newsletter or you can follow to get the latest update of my article on Dev
This post was originally posted on max's blog at 3 Reasons Why You Should Use Figma Instead of Adobe XD For UI/UX Design (Read Time: 1 Mins) and Photo by Jeff Sheldon on Unsplash
How Static Code Analysis Taught Me About Change Management
20 May 2018, 12:00 am
This was originally published on my blog, http://angelariggs.github.io.
Recently, I helped spearhead our departmentâs adoption of centralized static code analysis. I worked with one of our mobile engineers to research various tools and create a decision matrix for comparing options. Iâve introduced new tools to my team before, but this was my first time selecting a tool that would be rolled out and used by my entire engineering department. It was also our departmentâs first time trying centralized static code analysis. Now that Iâve had the experience of researching and selecting tools that other people will use, I thought it would be interesting to lay out why we chose to implement centralized static code analysis, how we chose a tool for it, and maybe most important of all - how we introduced these changes to our department.
Centralized Static Code Analysis
First, letâs cover why we decided to implement static code analysis in the first place. After an engineering offsite last year, Metal Toad set goals for creating a standard of quality throughout the company. Static code analysis - comparing written code against a set of âbest practiceâ rules - is part of that process.
But why centralized static code analysis? People can just user linters in their text editor - why spend money and time for a new tool that does the same thing, and forces people to change their workflow?
One main difference is that local linters donât offer standardization across people, teams, and projects. By running static code analysis via a single source of control (in this case, weâre using a product called Codacy), code rules are set at the project level, not the individual level - so everyoneâs code is analyzed against the same set of rules.
Centralized analysis also offers visibility into the feedback. Programming is inherently collaborative, and our tools should support that. By using centralized analysis, the feedback is placed directly on the pull request in GitHub. This allows the team to have a better understanding of other peopleâs coding decisions, and prompts more conversation during code review.
Choosing a Tool
There are several tools on the market for static code analysis. Before we could select one, we needed to think about our requirements. We threw together a Google Sheet with categories that we thought were important to consider: cost, run environment, inline comments, language support, and documentation.
Cost: We didnât necessarily have a set budget in mind, but it had the potential to be a tie-breaker if we needed to choose between two tools.
Run environment: Our preference was for the analysis to be run through GitHub, ideally when a pull request was opened. This would cut down on the sweat and tears of installing a tool on our Bamboo server.
Inline comments: We strongly preferred inline comments - that is, analysis feedback directly on the pull request, instead of being forced to sign into a separate UI to view the feedback.
Language support: Metal Toad has a wide variety of projects. We needed support for .NET, Java, Kotlin, Swift, CSS/SASS, React, Ruby, and Python.
Documentation: Documentation for anything in engineering can be very hit-or-miss, and these were no exception. We graded with a gut check on an A-F scale, and the grades were A+, B-, C+, and F.
Of the four tools we compared, two had to be run on Bamboo, and two could be run through GitHub. All offered inline commenting, but one of the GitHub-based tools required a browser extension to do so. Not a big deal, but it meant an extra step for our engineers, so it was a mark against. Language support differences were negligible, except for one tool that excluded CSS / SASS analysis entirely. And when it came to documentation, most of the tools we looked at had decent enough docs for our purposes.
Implementing the Change
So once we decided that static code analysis was important, and once we found a tool for it - how do you go about adopting it in the workflow?
First, you need buy-in. Without executive support, thereâs no funding, and the project is over before itâs begun. You also need support at the manager level. Your managers can help make the case to your executives, but they can also help make the case to your peers. Lastly, you need buy-in from your peers. If the changes youâre introducing create FUD (fear, uncertainty, doubt), then theyâll push back and avoid the changes.
It can also be helpful to start small and iterate. We selected a few projects to start with, so we could have examples when we started rolling out static code analysis to the department at large. We worked with a few people for each project to set the code patterns - this meant that more people were invested in what we were doing, and it showed that we valued the input from people who would be using the tool we chose.
We were also very proactive in our communication. We let people know ahead of time that static code analysis would be rolled out, and we made sure to announce that we wanted to encourage feedback. And as much as possible, we made changes based on peopleâs feedback; where we couldnât or decided not to iterate on feedback, we communicated why we made that decision.
Expectations for Use
So weâve talked about how we chose a tool for static code analysis, and why we think implementing it into our workflow is beneficial. But how does it actually get used day-to-day?
The messaging around expectations was particularly important for our engineers. Change is always hard. Change that points out mistakes and causes more work? Way harder. So it was really critical to have open communication around the expectations we had for people using this tool.
One of the most important steps was actually setting the code pattern rules for the analysis. This step was also a way to have people be more involved in adding static code analysis, instead of just throwing it over the wall at them. We scheduled meetings with 2-3 people in each group to set the default rules, so the input would be collaborative and cross-team. We focused on the more objective categories - Security, Performance, Error Prone, and Unused Code. We decided that Code Style rules would be set at a team level, since these tend to be more subjective and can be highly opinionated (tabs vs spaces! Single quotes vs double quotes!).
And throughout this experience, we were proactive in our communication around the intent of this tool. We emphasized that errors and issues would never block merges, and the analysis would never be used punitively. We explained that the intent was to improve our codebases with a focus on readability, security, and consistency. The goal was high-level best practices - the code weâd want other people to have written if we took over their project.
Overall, the experience of introducing and using centralized static code analysis has been pretty positive. There were some bumps along the way, to be sure. There was some frustration from adjusting to an extra step in the workflow, and we didnât set up the code patterns as quickly as we could have, which led to some spamming from pull request feedback that we actually didnât care about (e.g. those darn quote styles!). But by and large, I feel confident in calling this process a success - not only because of the benefits from static code analysis, but because I learned a lot from the experience.
What I Learned
I didnât have any previous experience around how to select a tool for internal use. This process gave me some insight into how to research and consider requirements, and how to present those in a meaningful way to the higher-up decision makers. It was actually fun getting to compare products and make the choice on the one we should implement!
My biggest lessons were about leading change management! Getting buy-in from both our exec team and our peers was so important. Investment from the top meant that we had the funding and credibility that we needed. Investment from peers meant that we primed the acceptance of adopting a new tool, and made it easier to pick up momentum of acceptance from everyone in the department.
We made sure to communicate. Nobody likes to be surprised with change, especially when itâs someone elseâs choice. We told people in advance that this change was coming, so theyâd have time to adjust their expectations and be ready for their workflow to change.
We kept our department mantra of âshoulder-to-shoulderâ in mind. We didnât just introduce the tool and wish everyone good luck - we created docs for onboarding, paired with small groups to set the code patterns and add projects, and invited feedback from engineers that we responded to.
Notice that almost every sentence in the section about change management starts with a âweâ. That ownership over the changes you introduce is incredibly vital. For one, it lets people know who to go to with questions or concerns. It highlights the fact that when you introduce change, you are responsible for that change, and for its results. Itâs also a reminder that you need to be invested in your change. You need to pay attention to how youâre introducing it, what the reactions are, and what the outcomes are. Change is emotional, and you need to care.
What are some pitfalls and successes youâve experienced around change management or introducing new tools? Let me know in the comments!
Node.js has a higher cognitive load than Java
19 May 2018, 10:25 pm
I'm going to preface this by saying that I'm a much bigger user of Java than I am of node. I do like node, but I just don't use it as much.
I'm also going to say that it's entirely possible that my lack of experience with node is colouring my thinking here.
I think Java is easier to work with than node. And I know that's going to be a hugely unpopular opinion, and even that people will wonder how I can ever think that. So here's my reasoning.
Imagine I'm writing a simple single page application. I'm going to use:
- Some form of HTTP server to act as a REST/GraphQL/whatever service.
- Create React App to build the UI (for arguments sake - I like it)
- Postgres for the data layer. (See above)
- Full stack end to end tests using selenium
In the Java world, I can set up a build that allows me to do this. The end result can, remarkably easily, be that I execute mvn clean install to:
- Download all dependencies
- Build the backend application
- Compiling all code
- Running all unit tests
- Running static checks - e.g. checkstyle
- Full integration tests
- Build a docker image for the application
- Build the webapp
- Producing the output files
- Running all unit tests
- Build a Docker image for the webapp
- Build the end up end tests
- Build a Docker image for the tests
The output of this I can then start the front-end and backend together or individually, and - importantly - I can run a Docker compose stack of the entire system including the end to end tests...
The interesting thing here is the integration tests. I can start up the server, using a library automatically start and stop the database, automatically manage the database schema, then run a whole barrage of tests against it. And all of this is just one thing hidden behind one standard build command, the same used by millions of other projects...
Now let's consider node.
Firstly, as best I know there's no way to do multi module builds in node. This means that I've got to know to build the three different modules individually.
Secondly, the integration tests. Having asked around, it seems that the idea of having an all-in-one process is actively disliked. Instead of running the tests with one command and it does it all for you, it's generally expected that you will:
- Start up all dependant services yourself - maybe using Docker
- Start up the service to test yourself - maybe using docker
- Then run the tests against this
- Then tear it all down yourself
That's a lot of effort to achieve this.
Thirdly, executing multiple step builds is clunky. Tools like grunt can make it easier, but that's adding one layer of complexity just to hide another. Alternatively you can use shell scripts, but that's not cross platform.
This is only a sample of things, but it already shows that running a build in node is more complicated than in Java. A lot of people argue that each of these steps are significantly simpler than the Java version, and that's true. But the fact that you've got to know it all just makes things more difficult to pick up.
Now, that's not to say it's all bad. There are a lot of good things here to. It's remarkably easy to get a very fast cycle time in node - write code, get unit test results flash up a second later, repeat. Or write code, have the server restarted a second later, and repeat. Java just takes longer to achieve these same things. However, it's got a lot of additional understanding needed by the developer to get to the same point.
At least, that's how it seems to me. I might well be missing things that make all of this a lot easier to understand.
How to find nearby places using Latitude and longitude in Laravel 5
19 May 2018, 10:23 pm
Often, in real-estate , dating and other similar websites, you might have noticed how they allow you to search nearby to any location. You can easily accomplish that in your laravel application using Haversine formula.
Source -- Tighten.co
Last year, I worked on real-estate project in my college as an capstone project and that's when I got to work on this query. Though haversine formula is easy to find but to use it in laravel through Eloquent was very difficult. I tried many solutions found in Stackoverflow, laracasts forum and other sources but couldn't make them work. Some of them did work but since they were using raw queries, I couldn't paginate the results which is what I needed.
After some trial and error, I finally make it working. So, here I am sharing the code snippet.
$gr_circle_radius = 6371;
$max_distance = 500;
$distance_select = sprintf(
"
( %d * acos( cos( radians(%s) ) " .
" * cos( radians( lat ) ) " .
" * cos( radians( long ) - radians(%s) ) " .
" + sin( radians(%s) ) * sin( radians( lat ) ) " .
" ) " .
")
",
$gr_circle_radius,
$lat,
$long,
$lat
);
$properties = Property::select('*')
->having(DB::raw($distance_select), '<=', $max_distance)
->groupBy('properties.id')->paginate(1);
Here, I have set maximum distance = 500 Km so it will show all results within 500 Km of the given Latitude and Longitude (used $lat, $long as variables).
To see the Demo, Check out my real estate project -- FirstFloor
The post How to find nearby places using Latitude and longitude in Laravel 5 appeared first on Parth Patel - a Web Developer.
How closely do you adhere to your architecture: Navigation edition
19 May 2018, 8:21 pm
(Note: I am not talking about the new Navigation Controller announced at Google I/O. If you think I should be, you're welcome to tell me in the comments!)
As I mentioned in this post, Chess.com is rewriting its Android app from scratch. As part of that process, we've spent a lot of time thinking about the architecture we want, and how we want various screens to relate to one another.
In the current production app, we follow essentially a "one Activity, multiple Fragment" approach, embedded in a traditional Ball of Mud (or Plate of Spaghetti, if you prefer) architecture. And over the past couple of years, we have experimented with various architectural patterns under the rubric "refactoring" (an overused word if ever there was one). We have used at least three different variants of MVP (all hand-rolled), but lately we have ended up settling on a kind of MVVM with heavy use of the Android Architecture Components, particular ViewModels and LiveData. They are really, really great â and unit testable! If you use the app at all, you may be interested to learn that the upcoming version (3.7, in beta soon) will have several new features all written with ViewModels, LiveData, and even the Paging library: Arena tournaments, News, and Achievements.
Our experience with ViewModels and friends has led us to decide that our "v4" app's architecture will rely heavily on them. One particular area of concern is Navigation. In the current prod app, essentially any screen can navigate to any other screen, and the chaos is real.
How v4 is handling navigation
We have made navigation a top-level concern and are beginning to write the abstractions to manage it. We have a Router class that implements a number of interfaces (HomeRouter, LoginRouter, etc) that clearly define how each screen is tied to other screens. And thanks to some clever work with Dagger, the Router class's methods can be named things like goToWelcome() and have no parameters, and the router can handle everything from there. For example:
@ActivityScoped
class Router<T : BaseActivity> @Inject constructor(
private val activity: T
) : SplashRouter, LoginRouter, OnboardingRouter, HomeRouter {
override fun goToWelcome() {
// startActivityAndFinish() is an extension function
activity.startActivityAndFinish(
OnboardingActivity.getStartIntent(activity),
activity.crossfadeAnimation()
)
}
We're injected a scoped activity that lets us handle everything right in this class and also prevents accidental memory leaks.
This is all well and good, but it finally brings me to the point of this post: how far do we take this?
What about 'back' and 'up' navigation?
At the moment, we're letting the framework handle these two forms of navigation. If a user presses the back button, super.onBackPressed() is called (with a few minor caveats). We also let the framework handle 'up' navigation by setting the parent activity in the manifest and enabling up navigation on the action bar.
But... could we do more? Clearly this is now a schizophrenic system. In some cases, we are manually wiring together activities (and some fragments), while in others, the framework handles this "automatically". Maybe the following would be better:
override fun onBackPressed() {
viewModel.onBackPressed()
// no call to super!
}
and similarly we could capture 'up' nav events and manually handle them.
What do you think?
How to think like a programmerâââlessons in problem solving
19 May 2018, 7:19 pm
This post originally appeared on Medium
If youâre interested in programming, you may well have seen this quote before:
âEveryone in this country should learn to program a computer, because it teaches you to think.ââââSteve Jobs
You probably also wondered what does it mean, exactly, to think like a programmer? And how do you do it??
Essentially, itâs all about a more effective way for problem solving.
In this post, my goal is to teach you that way.
By the end of it, youâll know exactly what steps to take to be a better problem-solver.
Why is this important?
Problem solving is the meta-skill.
We all have problems. Big and small. How we deal with them is sometimes, wellâŠpretty random.
Unless you have a system, this is probably how you âsolveâ problems (which is what I did when I started coding):
- Try a solution.
- If that doesnât work, try another one.
- If that doesnât work, repeat step 2 until you luck out.
Look, sometimes you luck out. But that is the worst way to solve problems! And itâs a huge, huge waste of time.
The best way involves a) having a framework and b) practicing it.
âAlmost all employers prioritize problem-solving skills first.
Problem-solving skills are almost unanimously the most important qualification that employers look forâŠ.more than programming languages proficiency, debugging, and system design.
Demonstrating computational thinking or the ability to break down large, complex problems is just as valuable (if not more so) than the baseline technical skills required for a job.ââââHacker Rank (2018 Developer Skills Report)
Have a framework
To find the right framework, I followed the advice in Tim Ferrissâ book on learning, âThe 4-Hour Chefâ.
It led me to interview two really impressive people: C. Jordan Ball (ranked 1st or 2nd out of 65,000+ users on Coderbyte), and V. Anton Spraul (author of the book âThink Like a Programmer: An Introduction to Creative Problem Solvingâ).
I asked them the same questions, and guess what? Their answers were pretty similar!
Soon, you too will know them.
Sidenote: this doesnât mean they did everything the same way. Everyone is different. Youâll be different. But if you start with principles we all agree are good, youâll get a lot further a lot quicker.
âThe biggest mistake I see new programmers make is focusing on learning syntax instead of learning how to solve problems.ââââV. Anton Spraul
So, what should you do when you encounter a new problem?
Here are the steps:
1. Understand
Know exactly what is being asked. Most hard problems are hard because you donât understand them (hence why this is the first step).
How to know when you understand a problem? When you can explain it in plain English.
Do you remember being stuck on a problem, you start explaining it, and you instantly see holes in the logic you didnât see before?
Most programmers know this feeling.
This is why you should write down your problem, doodle a diagram, or tell someone else about it (or thing⊠some people use a rubber duck).
âIf you canât explain something in simple terms, you donât understand it.ââââRichard Feynman
2. Plan
Donât dive right into solving without a plan (and somehow hope you can muddle your way through). Plan your solution!
Nothing can help you if you canât write down the exact steps.
In programming, this means donât start hacking straight away. Give your brain time to analyze the problem and process the information.
To get a good plan, answer this question:
âGiven input X, what are the steps necessary to return output Y?â
Sidenote: Programmers have a great tool to help them with this⊠Comments!
3. Divide
Pay attention. This is the most important step of all.
Do not try to solve one big problem. You will cry.
Instead, break it into sub-problems. These sub-problems are much easier to solve.
Then, solve each sub-problem one by one. Begin with the simplest. Simplest means you know the answer (or are closer to that answer).
After that, simplest means this sub-problem being solved doesnât depend on others being solved.
Once you solved every sub-problem, connect the dots.
Connecting all your âsub-solutionsâ will give you the solution to the original problem. Congratulations!
This technique is a cornerstone of problem-solving. Remember it (read this step again, if you must).
âIf I could teach every beginning programmer one problem-solving skill, it would be the âreduce the problem technique.â
For example, suppose youâre a new programmer and youâre asked to write a program that reads ten numbers and figures out which number is the third highest. For a brand-new programmer, that can be a tough assignment, even though it only requires basic programming syntax.
If youâre stuck, you should reduce the problem to something simpler. Instead of the third-highest number, what about finding the highest overall? Still too tough? What about finding the largest of just three numbers? Or the larger of two?
Reduce the problem to the point where you know how to solve it and write the solution. Then expand the problem slightly and rewrite the solution to match, and keep going until you are back where you started.ââââV. Anton Spraul
4. Stuck?
By now, youâre probably sitting there thinking âHey Richard... Thatâs cool and all, but what if Iâm stuck and canât even solve a sub-problem??â
First off, take a deep breath. Second, thatâs fair.
Donât worry though, friend. This happens to everyone!
The difference is the best programmers/problem-solvers are more curious about bugs/errors than irritated.
In fact, here are three things to try when facing a whammy:
- Debug: Go step by step through your solution trying to find where you went wrong. Programmers call this debugging (in fact, this is all a debugger does).
âThe art of debugging is figuring out what you really told your program to do rather than what you thought you told it to do.âââââAndrew Singer
- Reassess: Take a step back. Look at the problem from another perspective. Is there anything that can be abstracted to a more general approach?
âSometimes we get so lost in the details of a problem that we overlook general principles that would solve the problem at a more general level. [âŠ]
The classic example of this, of course, is the summation of a long list of consecutive integers, 1 + 2 + 3 + ⊠+ n, which a very young Gauss quickly recognized was simply n(n+1)/2, thus avoiding the effort of having to do the addition.ââââC. Jordan Ball
Sidenote: Another way of reassessing is starting anew. Delete everything and begin again with fresh eyes. Iâm serious. Youâll be dumbfounded at how effective this is.
- Research: Ahh, good olâ Google. You read that right. No matter what problem you have, someone has probably solved it. Find that person/ solution. In fact, do this even if you solved the problem! (You can learn a lot from other peopleâs solutions).
Caveat: Donât look for a solution to the big problem. Only look for solutions to sub-problems. Why? Because unless you struggle (even a little bit), you wonât learn anything. If you donât learn anything, you wasted your time.
Practice
Donât expect to be great after just one week. If you want to be a good problem-solver, solve a lot of problems!
Practice. Practice. Practice. Itâll only be a matter of time before you recognize that âthis problem could easily be solved with .â
How to practice? There are options out the wazoo!
Chess puzzles, math problems, Sudoku, Go, Monopoly, video-games, cryptokitties, bla⊠bla⊠blaâŠ.
In fact, a common pattern amongst successful people is their habit of practicing âmicro problem-solving.â For example, Peter Thiel plays chess, and Elon Musk plays video-games.
âByron Reeves said âIf you want to see what business leadership may look like in three to five years, look at whatâs happening in online games.â
Fast-forward to today. Elon [Musk], Reid [Hoffman], Mark Zuckerberg and many others say that games have been foundational to their success in building their companies.ââââMary Meeker (2017 internet trends report)
Does this mean you should just play video-games? Not at all.
But what are video-games all about? Thatâs right, problem-solving!
So, what you should do is find an outlet to practice. Something that allows you to solve many micro-problems (ideally, something you enjoy).
For example, I enjoy coding challenges. Every day, I try to solve at least one challenge (usually on Coderbyte).
Like I said, all problems share similar patterns.
Conclusion
Thatâs all folks!
Now, you know better what it means to âthink like a programmer.â
You also know that problem-solving is an incredible skill to cultivate (the meta-skill).
As if that wasnât enough, notice how you also know what to do to practice your problem-solving skills!
Phew⊠Pretty cool right?
Finally, I wish you encounter many problems.
You read that right. At least now you know how to solve them! (also, youâll learn that with every solution, you improve).
âJust when you think youâve successfully navigated one obstacle, another emerges. But thatâs what keeps life interesting.[âŠ]
Life is a process of breaking through these impedimentsâââa series of fortified lines that we must break through.
Each time, youâll learn something.
Each time, youâll develop strength, wisdom, and perspective.
Each time, a little more of the competition falls away. Until all that is left is you: the best version of you.ââââRyan Holiday (The Obstacle is the Way)
Now, go solve some problems!
And best of luck đ
Special thanks to C. Jordan Ball and V. Anton Spraul. All the good advice here came from them.
Also, all the programming knowledge Iâve acquired in such a short time wouldnât have happened without Lambda School. Canât thank/ recommend them enough.
Thanks for reading! đ
Page processed in 8.306 seconds.



