Counting Valleys – Solution explained

Posted by admin on October 24, 2021
Data structure and algorithms / Comments Off on Counting Valleys – Solution explained

Counting valleys is a entry-level problem in Hackerrank.com site. Here I present an explanation and a solution approach, for beginners to data structures and algorithms problems.

You can find the site’s description at Hackerrank.com, here I start with an understanding approach.

Description

Imagine a straight line, a sea level.
If we go Up, we’re above the sea level, in a hill.
While there, if we go down, we got to sea level again.
If we go down again, we’re below sea level, in a valley.
If we go up again, we’re again at sea level.

Problem is the following: Given a series of movements, represented by a string, in which “U” means “go Up” and “D” means “go Down”, count all the times we’re below sea level, in a valley.

For example: DUDDUUUD
Meaning: Down, Up, Down, Down, Up, Up, Up, Down

Solution

Data structure

First thing is to determined which data structure we need.
As we view in the graphical representation, we can count the valleys in a linear way, by an iteration of every command (Up or Down).
So the data structure we need is an array. A string is an array of characters.

Algorithm

Next to define is the steps we’re going to perform.

• To solve the problem, we need to know when we’re down the sea level, and when we reach sea level again.
• Easiest way is assign a value to up’s and downs, 1 and -1, and sum them on every iteration.
• If the sum is smaller than 0 (negative), we’re in a valley.
• We should count the valley once we reach sea level again, when sum is equal to zero once more time.

Desktop Test

Now, let’s put our algorithm to test, for every iteration we’re gonna calculate:

• The letter we’re receiving.
• The value of that letter.
• If ‘U’, is 1.
• If ‘D’, is -1.
• The accumulated sum of the values.
• If we’re in a valley (negative sum).
• The accumulated value count.

For example, for the first iteration, the letter is ‘D’, meaning a value of -1, as we’re starting adding value, the accumulated sum is -1, and as we’re currently in negative number, we’re in a valley, and as we haven’t surpassed the valley, we have a valley count of zero.

And so on, we perform the calculations for each letter.

Code

Once our algorithm is validated, then we can code it with confidence.
The language used here is JavaScript.
Good practices is write the algorithm in comments, to describe what the program is doing.
We can easily follow the commented code to review the algorithm.

Signature

First thing we got to do is to get the signature right, meaning the parameters and the output are setup correctly.

```/**
* We receive a number of steps
* and a string representing a path
*/
function countingValleys(steps, path) {

//  we return a number of valleys
return valleys;
} // end function counting valleys

```

Variable declaration

As we’re starting with algorithms and data structures, a good practice is to declare all variable we’re gonna need and give them descriptive names.
Also, it will be easier for the the person reading the code to follow the algorithm.

```    //  to store the amount of valleys
let valleys = 0;

//  to sum the value of every step
let sum = 0;

//  to know if we're on a valley
let inValley = 0;

```

Notes

Now we implement the validated algorithm.
Code can be pretty short and concise, nevertheless the example here is verbose for clarification purposes.
Readability and clarity are key whenever you’re learning or reviewing a piece of code.
You can always refactor it to make it neat and simple.

Cycle

Let’s review the cycle process.
For each step (letter) of the path (the string), we must perform the described algorithm.

```    //  loop the steps
for (let step of path) {

// here we code
// the algorithm

} // end for each step

```

Inside the loop

First thing we’re gonna need is determine the movement.
If ‘Up’, add one unit to the total sum, otherwise (is ‘Down’), subtract one unit.

```        //  add the step value
if (step == 'U') {
//  if up, positive
sum++;
} else {
//  if down, negative
sum--;
} // end if step is 'U'

```

Next step is search if we must add any valleys.
To do this, apply the condition:

• If we were in a valley, and now we’re again at sea level, add a valley to the counter.
• As we reach sea level, now we’re not in a valley.
```        //  if we were on a valley
//  and reach sea level
if (inValley && sum == 0) {

//  value counter increase
valleys++;

//  we're not
//  in a valley anymore
inValley = 0;
} // end if we were in a valley

```

Finally, if the total sum of values for the positions (up’s and down’s) is negative, we’re in a valley.

```        //  if the sum is negative
if (sum < 0) {
//  we're below
//  sea level
//  in a valley
inValley = 1;
} // end if sum < 0

```

And with this we’ve finished implemented the algorithm for the iteration.
After cycle ends, program return the counter of valleys.

Let’s view how the complete code looks like:

```/**
* We receive a number of steps
* and a string representing a path
*/
function countingValleys(steps, path) {

//  to store the amount of valleys
let valleys = 0;

//  to sum the value of every step
let sum = 0;

//  to know if we're on a valley
let inValley = 0;

//  loop the steps
for (let step of path) {

//  add the step value
if (step == 'U') {
//  if up, positive
sum++;
} else {
//  if down, negative
sum--;
} // end if step is 'U'

//  if we were on a valley and reach sea level
if (inValley && sum == 0) {
//  value counter increase
valleys++;
//  we're not in a valley anymore
inValley = 0;
} // end if we were in a valley

//  if the sum is negative
if (sum < 0) {
//  we're below sea level, in a valley
inValley = 1;
} // end if sum < 0
} // end for each step

//  we return a number of valleys
return valleys;
} // end function counting valleys

```

Time and space complexity

As we only need to loop the array once, the time complexity is O(n).
As we do not need to copy the array, the space complexity is O(n) also.
This is an efficient algorithm.

Test the solution

Our algorithm most run for a variety of cases:

• Plain straight, happy path cases.
• Edge cases (very short of very large).
• Empty of null cases (what if no input is provided).
• Time execution and memory allocation.
• Must perform in a short amount of time and with as little resources as possible.

We need to know the answer beforehand in order to be able to test it.
There’s a myriad of testing tools, or we can simple code a test function that evaluates the code and check against a pre-defined answer.

Key takeaway

• Understand and create a clear image of the problem in your mind.
• Draw it helps a lot.
• Determine the data structure to use is solve the half of the problem.
• Write the algorithm steps and perform a desktop test to validate it before writing the code.
• Write clear and readable code, with comments about what the program is doing.
• Perform tests for major categories of problems, short, long, straight-forward, special cases.

Project Management 101 – Part 1

Posted by admin on September 03, 2021
management / Comments Off on Project Management 101 – Part 1

First of all, let’s define both concepts:

Project

A unique and temporary endeavor, with a clear beginning and end, that delivers value, either tangible, like a product, or intangible, like services or knowledge.

Management

A process to achieve goals, that is composed by Plan, Organize, Execute and Control activities.

Project management

Is the process to produce unique deliverables in a defined period of time, applying a series of management techniques to make sure the results to be accomplished.

Pretty simple, right? well it is. Projects themselves may became tremendously complex though, but don’t worry, the fundamentals to manage them remains the same.

Let’s define what a Project Manager is:

Project Manager

Is the person responsible of manage the project, assure that delivers the desired outcome, accomplishing this on time and within a budget.

Commonly, PMs (Project Managers) are in charge of planning, organizing, controlling, and make sure that the tasks, the activities that must be carried on are executed, but do not execute them him/her self.

So, we can define his/her responsibilities

Project Manager Responsibilities

• Plan and organize the project.
• Communicate regularly the project need.
• Help to solve issues to ensure the project is carried on.
• Keep the project within budget and time.
• Assure the quality of the project outcome.
• Managing tasks
• Update status to all people involved, the stakeholders.

So, who are the stakeholders?

Stakeholders

Are the people involved in the project, who are affected by it and are interested in its results.

For example, the founders of an startup that have a project to developing their website, and the investors that fund it are clearly stakeholders in this example, but also are for example, the manager of the web design agency hired to develop the website. And there may be more people involved, but I think it’s clear now.

Are the customers stakeholders? Yeah, of course. Let’s dig in:

Customers

Any person or entity (companies, businesses and other organizations) that decides about the requirements of the project outcome and budget. So, for the Project Manager’s point of view, there are two types of customers:

Internals

The team, and the managers and executives within the company are internal customers of the project.

Externals

The typical customers: Consumers, clients, etc. Also, the vendors and providers are considered external customers.

With this in mind, we can redefine the modern role of Project Manager, due that deals with two kind of people, the internal and the external customers. We mention the team in the Internal customers, let’s extend on this topic:

Team

The project activities are performed by a team that is managed by the Project Manager, even if is not their direct manager in the company, he/she is their leader in the accomplishment of the project.

Each team member is responsible of perform it’s work, in the form of assigned tasks, and also, the expert in their part of the project.

The Project Manager helps the team, to adopt a Project Management methodology, to solve issues that may become impediments for the team to work, and collaborating with other teams to assure meeting the project’s requirements.

Every person in the team have motivations, skills, strong and weak points, and needs. Is the Project Manager job to value, trust, appreciate the team and address their needs, recognize their effort and to maintain the workflow smooth.

Relationships

Also, the Project Manager deals with the external customers and the stakeholders, to fulfill their expectations about the project’s outcome. As you can see, the Project Manager focus is on the customers, the externals and the internals, his/her focus is on the people.

The Project Manager is the link between the team and the stakeholders, it’s in charge of guiding the team to accomplish the desired outcome, and to manage effectively the communication with the stakeholders, it’s all about relationships, that’s why is very important to communicate effectively, be respectful and considerate, listen carefully and value others. Diplomacy is the name of the game.

Communication

To communicate effectively is to be clear, understandable, focused and timely. Project Manager must communicate the high level goals, a clear vision, specially to the team, in order for them to understand where the project is going and why.

Also, communicate the highlights and achievements of every team member is very important, it will build trust and an acknowledgement environment.

Possibly the most important thing to consider in communication is availability, Project Managers doors are always open.

Removing Impediments

Big part of the job is to make sure that people are able to work, providing tools, access, information, from the team and other teams and the stakeholders. This will empower the team and induce them to be creative and innovative, to be able to focus in their work, in solving problems to achieve the project’s goals. Take away the barriers and the stoppers allows easy and fluid collaboration in the team.

Soft Skills

Gift of people is something that really shines in Project Management, the ability to interact with other people, behave accordingly and assure a fluid communication between the parts.

Leadership

A Project Manager is a leader and must behave accordingly, to be an example for the team to follow in his/her behavior. Paying special attention to what people have to say and act accordingly is vital to make the project succeed.

A good leader cares about his/her team, get to know them, their lives, what they like and what don’t, showing real interest in them. In project management, both the team that performs project activities and the stakeholders are the Project Manager’s team.

Mentoring

Project Managers helps the team to achieve high performance, explaining them clearly the expectations of the project and the stakeholders, to avoid ambiguity, which may lead to rework.

Also, helps the team to solve problems, take their feedback in consideration for the project’s plans and empower team members, delegating responsibilities and assure they can work with the stakeholders.

Agility

Modern project management must deal with constant change, adjust, adjust, adjust, to the stakeholder needs, the market changes, from the customer feedback, the Project Manager must identify the possible changes and evaluate their impact, in the budget, the time and the task to be done.

Task Management

Project’s completion require work. This work is break down into activities, that can be break down in smaller task. This is most likely the famous part of project management, the To-Do lists.

Open a project management tool, write some task, setup deadlines, assign them to the team members, is possible that this is what we most know about project management, and is not far from reality, but is deeper, every task in the plan must be valuable, the progress should be updated constantly, milestones to indicate significant progress must be set and every issue, every delay and every completed work must be documented. It’s hard work, but organization and monitoring really pays off.

Conclusion

Well, that’s it for the first part of Project Management 101, I hope all concepts were easy to understand, simple enough to comprehend them and put them into practice. There’s a lot more on project management, and we will get to it soon. Good managing!

Three good free courses on Udemy

Posted by admin on August 30, 2021
Software / Comments Off on Three good free courses on Udemy

Udemy has many free courses, and the following are the one I recommend, and have remained free for a long time:

Katalon Studio – Step by Step for Beginners

Katalon Studio is a great piece of software for testing, able to automate tests for APIs and E2E. This course will guide you through the entire process, from installation to enterprise projects.

JENKINS Beginner Tutorial – Step by Step

Continuous integration is becoming more and more important in the world of software, for DevOps, testing and for the developers too. This simple course will introduce you to the current mainstream DevOps tool.

MS Excel – From 0 to Working Professional in 1 hour

Everybody should learn Excel, not only IT people. Excel is a great office tool and can be used pretty much for everything, calculations, documenting, reporting, etc. This course will show you how to use Excel, in a short, concise way.

Tags: , ,

How run a bash script in it’s directory

Posted by admin on November 18, 2017
linux / Comments Off on How run a bash script in it’s directory

To run a script in it’s directory and not in the directory we’re calling it, we can use the dirname command, pass their result to a variable, cd to the path and then execute the tasks.

```# Here we pass the dirname to a variable
dirname=`dirname \$0`

# Change current directori
cd \$dirname

# Execute the task, in this case, copy html files and save them as php files
for file in ./*.html; do
#cp ./mondial.* ./"\$file"
cp \$file "\${file/html/php}"
done
```

I hope this little script be useful to you.

Best,
L.

Tags: , ,

The Good Programmer Definitive Path

Posted by admin on November 13, 2017
Programming, Software / Comments Off on The Good Programmer Definitive Path

1. Focus on fundamentals

Focus in structure, architectural point of view, abstract thought instead of specific language implementation. Spec is half development, to have a clear vision before you code everything is half the work. Think in paper, get use to the whiteboard, develop a solid process of thought with the focus in solving the problem.

2. Code every day.

Every day, at least in paper, code something. Really, every day. Code for fun, code for progress, code for learning, not just for work. Setup a personal project, It could be some repository for algorithm solution exercises or a personal website, but work in it as your own pace, no pressure, all enjoyment, all reward.

3. Tune your ride.

Introduce your favorite tools and make them available for you in a easy way. Customize your editor, IDE, compiler, automate some scripts, include your favorite plugins, make it portable, automatic, pimp your ride, honey your axe every day, pimp your ride, get ready your tools, they’l become a part of you as a professional coder.

4. Learn management.

It will be more useful than you think. Basic management is as follows: Plan, Organize, Execute. Plan, Organize, Execute. And it’s repeated over and over in project, program, risk, time and every other kind of management. Always plan first, organize and then and only then execute. Get used to do this and your life, in every aspect, will be much more pleasant.

5. Fail soon, fail quickly, fail once.

Make mistakes. A lot, as sooner as possible, and make every mistake just once, learn from every mistake and make a system so you won’t make the same mistake once. For example, a very commonly fatal mistake is to forget the where in an update/delete query. So make a system to write the where first, then the command. Soon you’ll never forget the where, even if you write the sentence from top to bottom.

6. Pay no attention to critics. Specially from yourself.

Internet is full of resources to learn to code, but also full of trolls. If you make a “dumb question” to a group or forum, many people will just criticize you instead of help you. Those people have a problem, an emotional problem, they need to made someone else feel bad because they feel bad themselves. Made your part though, made your research, take some tutorial, have a background and make specific questions, don’t ask to a group something that you can ask google (or duckduckgo :)). But if some people try to bully you, just ignore them. Many will try to induce you the “real programmer syndrome”, that you’re not a “real programmer” unless you code free, just for fun, you know linux and do “all-nighters” all the time. The moment you make your first program you are a “real programmer”. The moment you get paid for a piece of software you code you are a “professional programmer”. Those people have the “atlas syndrome” and want you to feel like them.

Avoid criticize yourself. You learning and will improve everyday, if you code everyday. Avoid fall for the “imposter syndrome”, you’re you, just be honest about what you can’t do. If someone ask you something you don’t know, just plainly tell them, “I don’t know. But I will find out”.

7. Fear is your worst enemy.

You may think what you know enough to make a living, not updated, that you’re not learning “the right language”, that you have to learn what the trend is, or even try to predict the future. This is plain insecurity. What you’re saying is that you feel insecure, that you value stability over progress, that you are more worried about yourself than about deliver the best of you to others, and that’s what is all about in any job, in any field, in any industry.

Economics is no more than an exchange of values, if you want money, you have to deliver something valuable to your client, to your company or to your boss. So focus in solving problems and provide value, focus in systems not in technologies, improve yourself, become proactive and sharpen your abstract thought, in order to learn things and solve problems will be easy for you.

You know, the fundamentals are the same in every language and platform, develop an architectural point of view instead about worrying that if the trend change language you’ll be out of job. If you become good in solving problems and delivering value, you’ll never be out of job, I assure you.

8. Innovation and creativity must be your mantra

How can I make this faster? How can I make this more efficient? How can I improve this? Develop the habit to ask yourself these questions every time you finish coding a piece of software and soon you’ll be progressing exponentially.

Learn, apply, improve. Learn, apply, improve. It doesn’t need to be a major breakout improvement, the sum of all small changes makes wonders, what is important is to develop the habit of continuous improvement, to build a system, to grow a sense of awareness and promptness.

Some days you’ll be on fire, some days will be lame, but do it anyway. Do it every time you apply something, and brick by brick, soon you’ll build a rock solid wall of knowledge, a set of skill, a profitable attitude. That alone counts for itself.

9. Give. Give frequently. Give more.

Give the most you can to the most possible people. Write some blog articles, make a video tutorial, code a plugin or a library and share it with the community, engage in groups, forums, open source projects. The more you give, the most value you return to the community, the more relationships you build, the more experiences you get the more you’ll open your mind and heart the more passion you’ll have, it’s unavoidable.

The more people you help the wider your vision, the bigger your world. You’ll get to know fantastic people, and the community will acknowledge you, you’ll get to participate in bigger and important projects, you’ll build a kick-ass resume and an amazing project portfolio before you even realize.

10. Trust your gut

Following this path will get you to a wiser, kinder version of you. Unavoidable you’ll be a mature coder, so trust your instincts, you’ll get a kind of sixth sense in your field, and awareness, super conscious mindset. It’s not magic, it’s the expertise of the craftsman. This is a system to get you there, expertise is no genius, or prodigy, it’s something you build by yourself and nothing can take from you, so trust yourself.

11. Keep going.

One more try, one more line of code, one more unit test, one more project, until you reach the top. Top-notch is achievable. Code every day. Give every day. Have fun, in a daily basis.

12. The Bonus: If you have no patience…

This approach takes time. Lots of it. Specially the young ones may have not the patience and are looking for a faster way to achieve success. My advice is to develop patience, but if you’re decied to find a quicker way, here you have it: Focus in give. Give more. Then give more to more people. Work like hell the way you want. If stress you choose, if your strategy is to try shortcuts and do a lots of all-nighters like crazy, and nothing I say will change your mind, then go ahead but never ever forget to focus in give. Avoid to close yourself, lock yourself in your ivory tower, focus in winning big by give the most value you can, and the most value you can give always is something that solves a problem to others.

Matter very little the technology you’re using or the complexity of your code, you can’t deposit pride in the bank, only money. Focus in helping your client, your boss, your company in a way than can be automated, repeated or that your solution will permanently solve a big problem. This way you can not be mistaken. If only one thing you take from this article let it be this: Focus in winning big by giving big.

Is better this language or this other language for the future?

Posted by admin on November 01, 2017
Programming / Comments Off on Is better this language or this other language for the future?

The future, the future, how many times must one read this question? It’s asked several times a week, as much as I can remember. One never know, really, what will happen in the future. Nothing is certain, machine learning exists since the 70’s and is until right now that is catching heap.

In the las two years things has change dramatically, the 90% of the data in the cloud is from the las two years compared against all history of mankind.

Don’t marry some language. Don’t preoccupied yourself what will happend in the future, instead focus in the fundamentals. The fundamentals will never change, the fundamental value is provide value to others, is solving problems, and that you can do with php, java o even cobol, still in this very day cobol programmers are wanted.

Do not fear. Be bold. Code in the language you like most, in the language you’re more productive, provide value, solutions, the principles for programming are the same in every platform, in every so’s, in every language.

Focus in understand the fundamentals, in abstract thought, in the architecture, in the engineering, in the efficient communication of ideas and information, write neat elegant bullet proof code, the language matters not much, do it every day and you will never be out of work.

Become an expert in the field you choose, and you will be just fine. Return something to the community and help others achieve success, and you will be successful. Be bold. Be constant. Be great.

Tags: , ,

The Principles Of Programming

Posted by admin on October 12, 2017
Software / Comments Off on The Principles Of Programming

“Computer science education cannot make anybody an expert programmer any more than studying brushes and pigment can make somebody an expert painter.”

– Eric S. Raymond, Open source defender

The Principles of Programming are:

1. Everything is about communication.
2. Every program models a reality.
3. Programs handle data.
4. Every program can be reduced to a command list.
5. Every program can be reduce to Input – Process – Output.

Principle 1: Everything is about communication

Everything is about communication, between us and the computers and between programs that run in them. It’s all about communication, you tell them what to do and they answer you, you speak to them in a way they can understand and they communicate the result to you in a way you can understand.

Whitout communication there’s nothing. Can you imagine the modern world without the Internet? We’d be using the “foot network” still. Well, Internet is a bigger scale of what happen inside the computers. A program have to communicate with many other programs in order to everything runs smoothly, from open a file to send an email, everything is communication.

Principle number 2: Every program models a reality

Have you made a plane’s model or a ship’s model? Basically you make a plane, emulating the reality. That’s the same with the programs.

Think about the most used operating system by personal computers: Windows. At the beginning, Windows was made for office workers, everything in its environmente was designed for the sake of user familiarity: The desktop, the calculator, the folders, the files, etc. Early versions of Windows even used to have a special folder called “Briefcase”, where you could put the files you need in travels.

The whole Windows software use to model a reality: The office workers reality. Every moder application model a reality, from the home software through Office Suites till the ERP’s that models business administration, and the virtual relity video games, that model a sensorial reality.

Every program you write will model a reality. To the process of take a reality, separate it in parts and create a model we call it abstraction.

Principle No. 3.- The programs handle the data, information manipulated by the programs

Tongue-twister? Not, but almost. Making a clear difference between the applications and the data is fundamental in programing. A clear example is MS Word: Word.exe is the application, the file *.docx is the data. The computer programs execute commands and calcutations with the data. The data files are storage for structured information.

The diferentiation, altough obvious, it’s very importan because allow us to separate the reality thart we’re going to model it in two fundamental parts: The data and the computer program, and believe it or not, in the professional but non-technical word, causes confusion.

Principle No. 4.- Every computer program can be reduced to a sorted list of commands.

Every application is no more than a command list, really. Any program, any language, for example, a simple sum operation, the instructions will be like the following:

1. Get the operands from the user.
2. Execute the sum calcultation.
3. Show the output.

This is a list of instructios, commands, that must be executed in that specific order for the computer to do its work properly. Change de order or skip one and the result will not be the same.

Principle No. 5 Every program is based in an Input, a Process and an Output

Every computer program take an Input (string, numbers, files, etc.), applies them a Process (arithmetichal, logical, financial operations, etc.) and produces a result, an Output (screen messages, a file written, an email sent, etc).

Any more complex program can be compound of many program or functions that can be reduced to the same Input -> Process -> Output.

The sum program is a good example:

1. Take an input (the numbers)
2. Applies them a process (the sum calculation)
3. Produce an output (the sum result)

Every time you have problems in software development, take a deep breath and return to these principles, they will light up your problem and surely you’ll be able to find a solution.

Next step is understand how computers work, and then how the programs work too, in order for us to know what are we doing when we code and remove most of the gray areas, but before, a quick reminder:

1. Everything is about communication.
2. Every program models a reality.
3. Programs handle data.
4. Every program can be reduced to a command list.
5. Every program can be reduce to Input – Process – Output.

Helper db.js for Cordova-sqlite-storage

Posted by admin on March 30, 2016
javascript / Comments Off on Helper db.js for Cordova-sqlite-storage

Espino316 dbhelper-cordova-sqlite-storage is a helper for plugin Cordova-sqlite-storage (https://github.com/litehelpers/Cordova-sqlite-storage).
The goal is make more simple the use of the plugin (already excellent), because I like to use shorter more maintainable code.

**Important** In order to use this component, you must first install Cordova-sqlite-storage (https://github.com/litehelpers/Cordova-sqlite-storage).

Usage

Include

```<script src="db.js"></script>
```

Declaration

```var db = new DbHelper("mydb");
// mydb Es el nombre de la db
```

Script execution (i.e. create initial structure):

```db.execScript ( "sqlscripts/setup.sql" );
```

In sqlscripts/setup:

```CREATE TABLE IF NOT EXISTS
schools (
school_id int PRIMARY KEY ASC,
school_name text
);
```

Simple query:

```// Variable to store the sql
var sql = "SELECT * FROM schools WHERE school_id = :schoolId";

// Variable to store the parameters, if any
var params = {};
params['schoolId'] = 9901;

// Variable for store the function to apply
// Expects an object, assoc array.

// prints:
// [{ school_id: "9001", "school_name":"PABLO LIVAS"},{ school_id: "9002", "school_name":"ADOLFO PRIETO"}]
var fn = function ( result ) {
console.log( result );
};

// Call query
db.query(
sql,
params,
fn
);

/*  Anothe example */
// We can also declare params simply with ?

// Variable to store the sql
var sql = "SELECT * FROM schools WHERE school_id = ?";

// Variable to store the parameters, if any
var params = [9901];

// Variable for store the function to apply
// Expects an object, assoc array.

// prints something like:
// [{ school_id: "9001", "school_name":"PABLO LIVAS"},{ school_id: "9002", "school_name":"ADOLFO PRIETO"}]
var fn = function ( result ) {
console.log( result );
};

// Call query
db.query(
sql,
params,
fn
);
```

To query with no parameters:

```db.query(
sql,
null,
fn
);
```

Inserts and updates:

The helper uses “upserts” statements. If record exists, updates, else, inserts.

```// Name of the table
var tableName = "schools";

// Object with data
var tableData = {
"shool_id": 9003,
"school_name": "MOISEIS SAENS";
};

// Array with list of key fields
var keyFields = ["school_id"];

// Call upsert
db.upsert(tableName, tableData, keyFields);

```

Batch inserts / updates:

Same as previous function, but the data is an array of objects.

```// Table name
var tableName = "schools";

// Object array (the data)
var tableData = [
{
"shool_id": 9003,
"school_name": "MOISEIS SAENS";
},
{
"shool_id": 9004,
"school_name": "JERONIMO SILLER";
}
];

// Array with a list of the key fields
var keyFields = ["school_id"];

// Call bulkUpsert
db.bulkUpsert(tableName, tableData, keyFields);
```

The use is simple, useful, short and elegant.

7 functions extendind Strings in Javascript that will save you a lot of code and are very elegant

Posted by admin on March 29, 2016
javascript / Comments Off on 7 functions extendind Strings in Javascript that will save you a lot of code and are very elegant

These 7 basic string functions are easy to implement adding them to the String object, are very useful and the resulting code is a lot more legible, maintainable and elegant.

1 y 2: Encode y Decode Uri

I use these functions a lot and very often forgot to add the suffix “Component” to them. It’s kind of unnatural. With these simple extensions, my problems just went away.

```/**
* Encodes the string to URI format
* Usage:
*  var str = "This is a string";
*  str = str.encodeUri();
*  console.log( str );
*  // Outputs "This%20is%20a%20string"
*/
String.prototype.encodeUri = function () {
return encodeURIComponent( this );
}; // end encodeUri

/**
* Decodes the string from Uri format
* Usage:
*  var str = "This%20is%20a%20string";
*  str = str.decodeUri();
*  console.log( str );
*  // Outputs "This is a string";
*/
String.prototype.decodeUri = function () {
return decodeURIComponent( this );
}; // end decodeUri
```

3 y 4: EscapeRegEx & ReplaceAll

For some strange reason, when replacing one string for another only the first match is replaced. This is a problem, but easily solved with these two functions and adding these extensions, use is much simpler.

```/**
* Creates a regular expression string from the string,
* Prepending "\" special characters "escaping" the chain
* Usage:
*  var str = "Hi!";
*  str = str.escapeRegExp();
*  console.log( str );
*  // Outputs: "Hi\!"
*/
String.prototype.escapeRegExp = function () {
return this.replace(/([.*+?^=!:\${}()|\[\]\/\\])/g, "\\\$1");
}; // end function escapeRegExp

/**
* Replace all instances of "find" by "replace"
* in the string
* Usage:
*  str = "Hello my name is \$nombre, \$nombre is my name";
*  str = str.replaceAll( "\$nombre", "Luis" );
*  console.log( str );
*  // Outputs: "Hello my name is Luis, Luis is my name"
*/
String.prototype.replaceAll = function ( find, replace ) {
return this.replace(new RegExp(find.escapeRegExp(), 'g'), replace);
}; // end function replaceAll
```

5, 6 y 7: Right, Left & Contains

If VB was your first language you surely miss these functions. To implement for all strings is quite simple, saves keystrokes and the result is very intuitive:

```/**
* Returns "n" charactes to the left
* Usage:
*  var str = "ABCDE";
*  str = str.left(3);
*  console.log( str );
*  // Outputs: "ABC"
*/
String.prototype.left = function ( n ){
if (n <= 0)
return "";
else if (n > this.length)
return this;
else
return this.substring(0,n);
}; // end function left

/**
* Returns "n" characteres to the right
* Uso:
*  var str = "ABCDE";
*  str = str.right(3);
*  console.log( str );
*  // Outputs: "CDE"
*/
String.prototype.right = function ( n ) {
if (n <= 0)
return "";
else if (n > this.length)
return this;
else {
var iLen = this.length;
return this.substring(iLen, iLen - n);
}
}; // end function right

/**
* Returns true if the string contains the parameter "str"
* Usage:
*  var str = "Hello world!";
*  var lookFor = "world";
*  var inString = str.contrains(lookFor);
*  console.log(inString);
*  // Outputs: true
*/
String.prototype.contains = function ( str ) {
return (
this.indexOf( str ) > -1
);
}; // end function contains
```

Running this script at the beginning of your code will allow you to use these extensions, will make your life easier and allows you to have a clean and elegant code. Happy Coding! 🙂

Connect Sql Server 5.6 from Php in Linux CentOS 6

Posted by admin on March 28, 2016
sql server / Comments Off on Connect Sql Server 5.6 from Php in Linux CentOS 6

To connect to SQL Server from Linux use this command to install the driver:

```\$ sudo yum install -y php-mssql
```

For example, to php5.6:

```\$ sudo yum install -y php56w-mssql
```

This command installs freetds , a collection of libraries to connect to SQL Server from Linux. With this library we can not only connect from Php, but from the command line with the tsql program.

After installing, do not forget to restart apache:

```\$ sudo apachectl restart
```

Happy coding 🙂