How run a bash script in it’s directory

Posted by admin on November 18, 2017
linux / No Comments

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 / No Comments
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.

Tags: , , , , ,

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

Posted by admin on November 01, 2017
Programming / No Comments

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 / No Comments

“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 / No Comments

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.

Tags: , , , , , ,

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 / No Comments

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! 🙂

Tags: , , , , , , , ,

Connect Sql Server 5.6 from Php in Linux CentOS 6

Posted by admin on March 28, 2016
sql server / No Comments

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 🙂

Tags: , , , , , , ,

Sql Server object creation scripts, the right way

Posted by admin on March 28, 2016
sql server / No Comments

The right way to write object creation scripts in Sql Server (create tables, procedures, functions, constraints, etc) is as follows:

  1. First, check is the object exists.
    • If it does, delete it.
  2. Then, create the object
  3. Next, repeat for all the objects that depend upon the object we just create

**Important** Always write “USE Database GO” at the beginning of the script.

**Importante** Always include descriptive comment about the objects, always write your comments as if you were explaining to a kid, make them clear and short.

Let’s see an example, table creation script.

USE
    MyDataBase
GO

/* Object: MyTable */
-- If exists, delete it
IF EXISTS (
    SELECT
        *
    FROM
        INFORMATION_SCHEMA.TABLES
    WHERE
        TABLE_NAME = 'MyTable'
)
BEGIN
    DROP TABLE
        MiTabla
END
GO

/*
 * MyTable
 *     - Test table, stores testing data
 * Include relevant information as author, date, project name, reason for creation, etc.
 */
CREATE TABLE
    MyTable(
        MyTableId int NOT NULL,
        Description varchar(30) NOT NULL,
    )
GO

/**
 * PK_MiTabla
 *     - Primary key constraint
 */
ALTER TABLE
   MyTable
ADD CONSTRAINT
   PK_MyTable
PRIMARY KEY (
   MyTableId
)
GO

As we can see, the identation is very important for the code to be clear and legible. I like the following format:

COMMAND
    arguments

With this format I can read the instructions vertically with ease. Now will see an example for a stored procedure. It is really important to document the following:

  1. Functionality: What the procedure does
  2. List of parameters, including type and description
  3. Usage example

There are other important data to include, as change history, where at least we must specify:

  1. Who write the change
  2. Why
  3. When

Write our scripts this way, in case we want to run them in another server, they will not cause conflict if they run twice by mistake, and if the execution is made for somebody else, it will very clear for the other person know what is doing and why.

/* Object: myStoredProcedure */

-- If exists, delete it
IF EXISTS (
	SELECT
		*
	FROM
		INFORMATION_SCHEMA.ROUTINES
	WHERE
		ROUTINE_NAME = 'myStoredProcedure'
		AND ROUTINE_TYPE = 'PROCEDURE'
)
BEGIN
	DROP PROCEDURE
		myStoredProcedure
END
GO

/*
	myStoredProcedure:
	-	Select all records of my table using the key @myParameter
	Parameters:
		@myParameter INT - The table id
			
	Usage:
		EXEC myStoredProcedure 1001
	
	// Other relevant information
        Luis Espino, March 27, 2016, procedure creation
            - Example of creation script for the blog
*/
CREATE PROCEDURE
	myStoredProcedure (
		@myParameter INT
	)
AS
BEGIN
	--	Logic brief description
	--	    Select the records using the parameters
	SELECT
		*
	FROM
		MiTabla
	WHERE
		MiTablaId = @miParametro
END
GO

-- Grant permissions to users that can use the procedure, public in this case
GRANT EXECUTE ON
	myStoredProcedure
TO
	PUBLIC
GO

It’s really easy, the important thing is to keep order and structure in the code.

Upgrading PHP to 5.6 in linux Centos 6

Posted by admin on March 27, 2016
Php / No Comments

Php by default in Centos 6 may be versión 5.3. If you want to make the most of php with useful functions lie hex2bin, you need the 5.6 version.

In order to upgrade, first we must add the repo, then remove the current version and finally install the new version.

This script contains the commands needed to carry out the tasks:

sudo rpm -Uvh http://mirror.webtatic.com/yum/el6/latest.rpm
sudo yum remove php-common
sudo yum install php56w
sudo yum install php56w-mysql
sudo yum install php56w-common
sudo yum install php56w-pdo
sudo yum install php56w-opcache
sudo yum install php56w-pgsql
sudo yum install php56w-pear
sudo yum install php56w-mcrypt
sudo yum install php56w-xml
sudo yum install php56w-xmlrpc
sudo yum install php56w-devel
sudo yum install php56w-pecl-memcache
sudo yum install php56w-gd
sudo yum install php56w-pspell
sudo yum install php56w-snmp
php --version               

With the last line we can verify the success of the upgrade.

Happy coding! 🙂

Tags: , , , , ,