Enumerate in Python

Learning python is extremely easy though mastering it, is extremely difficult – by known

This post discusses the Enumerate function in python. It is a built-in function in Python.

enumerate (iterable, startIndex=0)

It takes an iterable object such as a list. The startIndex is a number by default it is 0 and denotes the starting index the function should return. The returned object is enumerate object.

Lets consider an example first.

Example

Print the values and indexes of the following list

list = [“Apple”, “Banana”, “Cherries”, “Dragon Fruit”, “Fig”]

Following python code will do the work:


fruit = ["Apple", "Banana", "Cherries", "Dragon Fruit", "Fig"]

for i in range(0, len(fruit)):
print(fruit[i] + ' is at index ' + str(i))

The same can be achieved with enumerate function as follow

fruit = ["Apple", "Banana", "Cherries", "Dragon Fruit", "Fig"]

for index, value in enumerate(fruit):
print(value + ' is at index ' + str(index))

Output of the script

$python main.py
Apple is at index 0
Banana is at index 1
Cherries is at index 2
Dragon Fruit is at index 3
Fig is at index 4

Hope you have understand how the function works. Indeed it is an easier and a cleaner way to select elements of a list.

Challenge

Can you try following:

The function should take a word and then the output should be something as in following pattern.

input – “Apple”
output – “A-Pp-Ppp-Llll-Eeeee”

input – “baNanA”
output – “B-Aa-Nnn-Aaaa-Nnnnn-Aaaaaa”

Simple Approach


def accum(s):

text = []

for i in range(0, len(s)):
getChar = s[i]
text.append(processChar(getChar, i))

return '-'.join(text)

def processChar(char, times):
text = char.upper()
for i in range(0, times):
text = text + char.lower()

return text

print(accum('Apple'))

The above code can be factored as follow, in just one line using enumerate


def accum(s):
return '-'.join(s[i].upper() + s[i].lower() * i for i in range(0, len(s)))

print(accum('Apple'))

However, it can be written as follow without using enumerate in one line.


def accum(s):
return '-'.join(t.upper() + t.lower() * i for i,t in enumerate(s))

print(accum('Apple'))

Even though it is possible to get the same output in different approaches, the code with enumerate looks clear, isnt it?

Advertisements

JWT – JSON Web Token – An Introduction

While RESTful APIs are conquering the web development space, session based authentication or cookie based authentication is getting obsolete. Since RESTful APIs are stateless, the client is responsible to maintain the state. Some technologies are available and JWT is one of them. indeed my favourite, in this post will get to know what JWT is.

What is JWT?

JSON Web Token (JWT) is an open standard which provides authentication and integrity for secure transmission of information between two parties or more in a form of JSON objects.

JWT based Authentication

JWT can be used to maintain sessions or states, so it can be used to authenticate users as well. For an example in a web application, assume that information is retrieved after the user logs in to the application. Once the user enters the username and the password, the server can authenticate the user and issue a JWT. Then after, the user produce the JWT when requesting information from the server. The server verifies the authenticity of the JWT and send requested information.

Information integrity

JWT can also be used to transfer information securely. Initially it does not provide any confidentiality, though it provides integrity. That means, since the JWT contains a signature, a 3rd party cannot tamper information the token holds, hence it assures the JWT holds information that the original issuer entered.

JWT is an open standard

JWT is an open standard, it is available as RFC 7519.

Structure of JWT

JWT consists of 3 parts. The header, the payload and the signature. Indeed, it is two JSON objects plus a string (signature). The JWT is a string where the above mentioned three parts are base64 encoded and appended, separated by . (dots).

The Header

In general, there are two fields in the header, the algorithm and the type.

for an example:


{
"alg": "HS256",
"typ": "JWT"
}

alg stands for the signing algorithm and the typ denotes the type which is obviously JWT.

The Payload

This is the second part of the token and it holds all required information. In the standard these information are termed as claims. Altogether claims are divided into 3 sections, registered, public and private.
registered – These are set of predefined claims, for an example claim iss denotes the issuer, exp denotes the expiry date. Other registered claims include iss, sub, aud, exp, nbf, iat and jti. If you are interested refer to the RFC.
public – these claims can be defined by the specific standards. However to avoid collisions it is better to check JWT Claims Registry before hand.
private – these claims are custom defined based on the requirement of the application. In order to avoid collisions make sure the claims are namespace bound.

Following is an example:

{
"iss": "mybloginc.",
"jti": "a676e7683c10263f",
"myblog-username": "john",
"myblog-admin": true
}

Note that registered claims such as iss and jti are used along with private claims such as username and admin which are application specific. To avoid collisions, there are used with the namespace prefix ‘myblog-‘.

The Signature

This is the last part of the JWT. It contains the signature of the JSON objects of the header and the payload.

signature = hash {json of header + “.” + json of payload}

Implementing JWT in PHP

Following is a simple implementation of a JWT. The code is self-explainable. The final value which is the JWT can be checked using www.jwt.io

<?PHP
//used to sign the JWT, this must be a secret, only the server knows
$secret = 'NobodyKnows123***';

//creating application specific information
$session_id = md5(rand(100000,1000000).time());
$username = 'AuthenticatedUser';

//define JWT header
$header_array = array("alg"=>'HS256', "typ"=>'JWT');

//define JWT payload
$payload_array = array(
"iss" => 'ebckurera JWT blog post',
"sub" => 'creating JWT using PHP',
"exp" => time()+60,
"nbf" => time(),
"iat" => time(),
"jti" => md5(rand(1000,10000).time()),
"myapp-username" => $username,
"myapp-session_id" => $session_id
);

//arrays converting to JSON objects
$header_json = json_encode($header_array);
$payload_json = json_encode($payload_array);

//constructing the string to be signed
$unsigned_token = base64_encode($header_json) . '.' . base64_encode($payload_json);

//signing the content
$signature = hash_hmac('sha256', $unsigned_token, $secret);

//constructing the JWT
$signed_token = $unsigned_token . '.' . $signature;

echo $signed_token;

?>

JWT

Note that the header, the payload and the signature are separated by dots ( . ). Both the header and the payload are base64 encoded.


eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJpc3MiOiJlYmNrdXJlcmEgSldUIGJsb2cgcG9zdCIsInN1YiI6ImNyZWF0aW5nIEpXVCB1c2luZyBQSFAiLCJleHAiOjE1MjY5NjI3NTAsIm5iZiI6MTUyNjk2MjY5MCwiaWF0IjoxNTI2OTYyNjkwLCJqdGkiOiIxMzRhYTlkODlmOWU3NDUxMDdiNzkyNzFmZWIyNzQzNCIsInVzZXJuYW1lIjoiQXV0aGVudGljYXRlZFVzZXIiLCJzZXNzaW9uX2lkIjoiMjMzNGZjYzEyZmI3ZDJlOTdiOWJmNTg5NWEzY2Q0MzQifQ==.b51b39d6a780cd5dff26fa89bd912b59af623cfffa467652b499f08da3520fb2

Security

Is JWT a secure medium? In general it is not, nevertheless it depends on the implementation. Always make sure JWT is used over HTTPS only. Otherwise it is very easy to employ a Man-In-the-Middle (MIM) attack. Then if there is no proper mechanism used, it is vulnerable to replay attacks as well. It can be easily avoided using a JWT per transaction. Further the payload can be encrypted so that it provides confidentiality as well (in this case the, JWS’s capability of information transmission gets limited). As JWT use signatures, in default it is non-repudiation as well.

With proper mechanisms in place JWT is a well secured to be used for web applications for both user authentication and information transmission.

Conclusion

JWT is a fairly secure mechanism that can be used in user authentication and information transmission between clients and RESTfull APIs, in general with all web applications as well. By default it provides, authentication and integrity, it uses signatures therefore it is non-repudiation as well. It is subjected to replay attacks and Man-In-the-Middle attacks though. However with proper implementation, JWT becomes more secure and powerful.

Combining CodeIgniter and WordPress (back-end)

CodeIgniter is a light-weight web framework which enables speedy development, hence it would be a great tool for evolutionary prototyping. In fact for small scale prototypes, my favorite web framework is WordPress. Yes, WordPress is a CMS but with the creativity you can convert it to a framework too. Then comes CodeIgniter, it comes with a comprehensive framework and the best thing in CodeIgniter is, it is easy to control, easy to override. Often I combine WordPress and CodeIgniter to harness the power of the admin panel of the WordPress for small scale web sites.

Plan

The plan is to extract a post from WordPress database by it’s id and show the title and the content of the news.

Prerequisites

Make sure WordPress database and CodeIgniter (get it from https://www.codeigniter.com/download) is ready on the server. Specially make sure mod_rewrite (.htaccess) is enabled in apache too.

Connecting the database to CodeIgniter

Database configuration file resides in application/config/ and it is a matter of editing database.php file. Open the file and provide required information such as username, password and database name.

Getting Ready

CodeIgniter is Model-View-Controller (MVC) based. Therefore it is required to create three classes, Controller, Model and View. Lets name, the controller as News, model as Model_News and view as View_Model. In CodeIgniter class names should start with a capital letter. Prefixing it not mandatory, nevertheless a good practice for easy identification.

The View

Will start from the View, the view class should resides in View_News.php. View needs to be created inside the folder application/view.

<?PHP

echo "<h3>$head_line</h3>";
echo "$news_text";

echo "<hr/>Generated on ". date('Y M d', time()) . " - powered by CodeIgniter + WordPress";
?>

The Model

The model should be in the folder application/models and should be named as Model_News.php. The class Model_News should be extended form the CI_Model class. As the database is added to configuration, it is possible to get it connected with less code lines. The output of the db->query( ) is an object.

<?PHP
class Model_News extends CI_Model{
function query_news_by_id($id){

$this->load->database();

$sql = "SELECT * FROM wp_posts WHERE post_status='publish' AND ID=$id";
$query = $this->db->query($sql);

$output = new News_Objects();

if($query){
foreach ($query->result() as $row)
{
$output->Title = $row->post_title;
$output->Body = $row->post_content;
}
}
return $output;
}
}

class News_Objects{
}

?>

The Controller

Controller needs to be created inside the application/controllers folder. Create News.php file inside the folder and create the News class by extending the CI_Controller class. In side the class there is a function to manage the flow. It takes an argument which is the news id and pass it to the model, the output from the model then passes to the view. To pass data to the view, an array is used. $objData helps passing data from model to view. All elements of this array become variables in the view, the element name, index becomes the variable name. Notice that load->model( ) and load->view( ) are used to load model and view respectively.

<?PHP
class News extends CI_Controller{
function show($id=1){
$this->load->model('Model_News');
$news = $this->Model_News->query_news_by_id($id);
$objData['head_line'] = $news->Title;
$objData['news_text'] = $news->Body;
$this->load->view('View_News', $objData);
}
}
?>

Accessing the content

To access the content following URL can be used.

http://localhost/index.php/news/show/1

Make sure to replace localcost with your server root.

After index.php it is the controller name follow by the method and it’s parameters.

That is it, it is really easy to understand, isnt it ? Give a try and let me know if you encounter any issues.

Make the code readable – JavaScript coding styles

In my opinion, JavaScript (JS) is not a language that is very coding-friendly. Well, it depends on your background though. Indeed, the language (JS) is event driven therefore people coming from procedural language world go crazy when try to understand the flow of the code. On top of such complications, the next hurdle is to understand the code, or perhaps can be referred to as reading the code.

I prefer the readability to reducing the number of lines in the code. As a best practice, it is worthwhile to write your code in easy to read and understand manner. This is not because others need to understand the code, but because in future you need to understand the code written by you. Believe me, it backfired on me few times and then I realized I need to stick to a coding style, no matter the size of the code.

Once I started using Python, I learnt how important the tidiness of a code. That is because you need to maintain indentation or else there will be bunch of errors when the code is getting compiled.

Coming back to JS, as it is the main focus in this post, what are the coding styles that can be followed when coding in JS. Have you ever wondered?

Following are some of the starting point, few good ones:

node.JS style guidenode.js style guide could be a good choice for not only node.js developments but also for JS in general.

Google JavaScript Style GuideGoogle JS Style guide is also very informative and easy to understand.

JavaScrip Standard StyleJS Standard is a module which come with automation and it available in npm.

Most of the styles shares common styles therefore you can choose anything.

But, some golden rules I would like share are:

  • Use === over ==, type checking of variables would be a good idea to eliminate runtime logic explosions.
  • Avoid tabs, use 2 spaces instead.
  • Mind the brackets, semicolon
  • Callbacks should take err as the first argument where callback as the last argument, e.g. function1(err, arg1, arg2, arg3, callback)
  • Always declare your variables with var in the appropriate scope and use camel case for naming the variables.
  • Write a descriptive short comment on what the function does. or you can do it for each line if the logic quite complex.
  • try to stick to object oriented approach is possible.
  • some would prefer to omitting the semicolon but I always use it.
  • Important to have a space after a key word, e.g. if { (mind the space between if and {)
  • Last but not the least, refactor your code as much as possible, make it readable and understandable.

What else I missed? What are your best practices or preference? leave a comment.

Coding is a lifestyle and the happiness

When I was surfing Quora, I accidently happened to read the following post and thought of sharing as it truly speaks the passion of a software developer.

Quora answer by – Balaji Viswanathan, CEO of Invento Robotics

How does one get a job at tech giants such as Google, Microsoft, and Amazon? I know C++ and Python, and currently learning Java, but don’t have any project or competitive coding experience.

I have been through the interview processes of all the 3 companies and worked for one of them. I know for a fact that they all are desperate to hire top notch software developers.

This is the golden age for developers. Companies run after great developers and the kind of opportunities that Github and other tools offer in terms of showcasing your talent never existed in the past.

You have to live it. It has to be something you think in the shower, while having dinner, while you drive and while you shop. Coding is an art and great artists get consumed in their art.

However, you cannot just “know” C++/Python. You have to live it. It has to be something you think in the shower, while having dinner, while you drive and while you shop. Coding is an art and great artists get consumed in their art.

I was recently hiring someone for a senior development position and was surprised to find out that he was not as interested in coding everyday. Only those folks who consider coding as a super awesome thing to do and something that is not just a train to get you somewhere – but is the destination – succeed in hard core development. Rest go on to become managers or worse.

And coding is not mere copying a piece of code from Stackoverflow and building a sample app.

And coding is not mere copying a piece of code from Stackoverflow and building a sample app. Those stuff are akin to building small lego structures from a picture manual. Working in a large company is like building a skyscraper where you have to make additions without bringing down the structure.

To build these large structures, you need to understand common algorithms and some of the common patterns. You need to understand which problems are tractable [at least in polynomial time] and which cannot be easily tackled without some optimization procedures.

Most importantly, you need to be building all the time. I don’t consider myself to be a great developer now, but I was coding random procedures and subroutines from the time I was 12 and coding that way for 10 years until I was hired at Microsoft HQ to build Windows. During my college I spent 6–7 hours coding everyday.

My peers at these top companies also were coding for many years with passion. That is the one trait that I believe differentiates the folks who succeed in these companies versus those who don’t.

Sure, books on coding interviews can give a leg up, but nothing can beat solid coding all the time you have available. You should love coding so much that you might be building some procedures or simple algorithms even while waiting at a restaurant. That zeal and passion for coding makes the 10x developers that companies so eagerly seek.

If you really want to be a developer plan on spending 7–8 hours coding every single day before getting hired, after you get hired. You will be building projects ranging from silly to something super cool. And you will go far beyond just tinkering with sample code and snippets available on the Internet.

If you really want to be a developer plan on spending 7–8 hours coding every single day before getting hired, after you get hired. You will be building projects ranging from silly to something super cool. And you will go far beyond just tinkering with sample code and snippets available on the Internet.

If you have not built any such complex project, you might still get hired in some company by random chance. But, you might find yourself in a job you don’t like and overshadowed by peers who have built those. If you don’t build coding projects before getting hired, you need to seriously ask yourself whether you are indeed a developer and want to make a career out of it.

If you are building code – not because someone asked you to do so, not to impress someone and not because someone paying for – but just because you can and because you find happiness in it, you can succeed as a developer.

If you are building code – not because someone asked you to do so, not to impress someone and not because someone paying for – but just because you can and because you find happiness in it, you can succeed as a developer. And same is true in any complex art – painting, acting, physics research or medicine.

<end of extraction>

Is not this the real passion that software developer should poses? That is why I believe, coding is a lifestyle. You do it not because you need to do it or you are asked, you do it because it is your happiness.

The sole purpose of re-publishing the answer provided by Balaji is to make aware the readers hence no copyright infringement was intended. 

Passive event listeners – Solving Violation error in JQuery

After introducing Passive event listeners in the DOM spec, following violation occurs when using JQuery methods to capture event triggers.

[Violation] Added non-passive event listener to a scroll-blocking ‘mousewheel’ event. Consider marking event handler as ‘passive’ to make the page more responsive. See https://www.chromestatus.com/feature/5745543795965952

Recently, I notice this issue in code where JQuery .on method has been used. Following is what needs to be done.

Code fragment with the issue:


$(document).on('change', "input[type='date']", function (e) {

Use { passive: true } to fix the issue:


$(document).on('change', "input[type='date']", { passive: true } , function (e) {

Refer to more info on JQuery issue tracker – Issue 2871.