Solutions – Nishchal Gautam – Question 3



Solutions – Nishchal Gautam – Question 3

0 0


solutions


On Github cyberhck / solutions

Solutions

Nishchal Gautam

Solution by Nishchal Gautam / @cyb3rhck

In the code given, if there are 1,00,000 rows, there are a total of 1,00,000 queries inside the loop. Instead of doing that, we can create a batch update statement, then send email, then update whole 1,00,000 rows with single query (or maybe 1000 at a time).

Also sending mail is a very slow process, even if the table has like only 1,000 rows now, it'd take quiet a time to finish execution. So what we can do is, have a separate table, which queues mail to be sent, then a cron job can do the email sending. Which will be much more faster, as we don't have to send the email instantaneously, and email will still be sent in like 5 seconds.

Code below, combines two queries, then insert into one table in a single query
<?php
$query = "INSERT INTO stock_ledger
	(article_id, bin, quantity)
	SELECT article_id, 'quality_control' AS bin, quantity
	FROM quality_control_articles
	WHERE qc_id = 720
	UNION
	SELECT article_id, 'main_bin' AS bin, -quantity
	FROM quality_control_articles WHERE qc_id = 720;";
if(mysql_query($query)){
	return true;
}else{
	return false;
}
?>
					

Question 3

Please describe what a very simple HTTP request looks like (What data is transmitted) and how a simple cookie is set and read again.

(<message-header>)
NEW LINE
[<message-body>]

Here, message header is a key:value pair

There are different types of headers.
They have value of Cache Control, Expiry,
Last-Modified, Content encoding, Method, User Agent, etc.
A simple response header to set cookie would like like the following:
Set-Cookie: user=cyberhck; access_token=asda2323108qae;

Now when browser requests a document,
it also sends request header containing cookies
and several other header information.
A simple HTTP request header's cookie would look like:
Cookie: user=cyberhck; access_token=asda2323108qae

When server gets the above cookie, it knows the request is from
cyberhck, and it can determine if the user is valid by
checking access_token.

JavaScript provides a custom sort function where we can see which one should be ordered first given two elements
data.sort(function(first, second) {
    return parseFloat(first.popularity) - parseFloat(second.popularity)
});
						

Solutions 5

A

	$list = df_query('SELECT * FROM warehouses');
	foreach ($warehouses as &$warehouse) {
		if( $warehouse['weak_number'] )
			$warehouse['number'] = $strong_number;
		//Even though it's only one statement inside if,
		//Use curly brackets, it's more readable
	}

	$html = df_render_template_simple('warehouse.list.html',$warehouses);
	if($mode == 'accounting')
						

B


//give more readable names,
//how can one understand what "a" and "f" stands for?
if($_POST['a'] == 'f'){
	header("Location: process_login.php");
}else{
	header('Location: index.php');
}

						

C

$html="<div id='container'>";
//even if there's only one statement inside if...else,
//use the curly braces, it's more readable
if((isset($_COOKIE['area']) ? $_COOKIE['area'] : 'p') == 'f')
	$html .= "<h2>Fashion</h2>";
else
	$html .= "<h2>Piercing</h2>";
$html = "<table>";
// you have not concatenated $html here,
//it's gonna rewrite, you might want to have $html .= "<table>"
foreach ($_POST as $field => $value) {
	if($_POST[$field] == 'special1')
		$_POST['field'] = 'Block';
	//instead of writing html like this, use a heredoc like:
// 		$html .= <<<MARKUP
// <tr><td>{$field}</td><td>{$value}</td></tr>
// MARKUP;
	$html .= '
	<tr>
	<td>'.
	$field
	.'</td>
	<td>'.
	$value
	.'</td>
	</tr>';
}

$html .= '</table>';
$html .= '</div>';
						

D

$mapping = array(
	'carnivore' => array(
		'cat' => 3,
		'dog' => 6
	),
	'hervibore' => array(
		'horse' => 7
	)
);

foreach ($mapping as $type => $animal) {
	foreach ($animal as $spices => $id) {
		$data=trim($raw_data);
		if ($data == ''){return 'Error: no data';}
		//don't write code like this,
		//use proper indentation in every case.,
		//also return a json data
		if(!function_exists('base64_decode')){
			return 'Error: func base64_decode n/a';
			//don't return a string, return a json data,
			// that makes more sense
		}
		$data = json_decode($data);

		$found_info[$spices]=$data[$id];
	}
}
						

E

$result = process_data($data);
if($result['error']){
	//it's difficult to open a file every time,
	//write a functioin which do this task
	$fh = fopen('error_log.txt','a');
	fwrite($fh, 'Error occured: ' . $result['error'] . "\n")
	fclose($fh);
}
						

Only for developers familiar with ExtJS: Can you develop a component that works similar to a date field with date picker but has a textarea instead of a calendar? (Either with or without the header – doesn’t matter.)

I haven't had any experience with EXTJs, but I know the concept how it's implemented though, the component is placed just below the input box and is styled to hidden, when one focuses on that input box, the corresponding component is styled to be displayed. Now when they blur or move out of input box, we hide it back again. This can be accomplished by (1. Just by CSS only, 2. With AID of JavaScript.)

What IDE do you use and why?

For web, I don't use IDE as such, I use a simple text editor called "Sublime Text". It's pretty good and is a must try if one hasn't already. I use this text editor because it's light weight (doesn't take time to do simple stuffs). Has very good support (supports Linux as well). I use Sublime Text for it's plugin support, ability to create own snippets, plugins, etc. Emmet for one, is a very good reason I've been using it so much, this saves me a lot of time. Sublime can be customized to one's needs, configuration is done via JSON files, which is pretty neat. I can't really tell why I use it, it's ineffable. I'd recommend everyone to try it out.

And for Android, I use android studio because it's recommended and it has a great support. We use gradle build to include dependencies, which I think is great.

What are your options if you want to build a file upload with progress bar and how would you eventually implement it?

For doing a file upload progress bar, I'd use HTML5 Ajax2 form data model. It basically allows a file to be upload in chunks as well, it also have method to add event listener while progress is going on, and we know how much of data is uploaded, how much data is to be uploaded in total. In that way, we get a percentage, which can be shown easily in a progressbar.

And if we also keep track of time, let's say every 300ms, the amount of data uploaded in a interval of 300ms would allow us to calculate the speed in which upload is being done.

I've had done this way in the past, and I love free softwares, so I've also opensourced it on github, you can go through the code at: github.com/cyberhck/uploadFive and you can explore a live demo at cyberhck.github.io/uploadfive/ where you can see live speed, progressbar, etc.

This single query should give you the last comment from every post

SELECT posts.content AS Post, comments.content AS MostRecentComment,comments.create_datetime
FROM comments,posts
WHERE posts.post_id=comments.post_id
AND comment_id IN(SELECT MAX(comment_id) AS comment_id FROM
		comments GROUP BY post_id);
						
Of the top of my head, I can only see the shortcuts removed in that image, it's a usability issues for a lot of people, I for instance, prefer all keyboard based operations instead of a mouse/touchpad based operation.
hello world is in a span with class "b", and it is inside a div with class "a" and id of "i". As we know in CSS, styles are cascaded, and id takes precedence over classes, so the color of hello world should be green
Question 12

What are the advantages and disadvantages of object-oriented programming? What advice would you give a junior developer about what he should avoid when programming objectoriented?

Advantages of Object Oriented Programming would include re-usability of code, managing access control, understandability, ease of use of parts of code, creating APIs are very easy in Object Oriented Programming.

Disadvantages of OOP are having higher size of program, it is more difficult than procedural program to create Object Oriented Program. Some times, it also effects speed as Object Oriented Programs are bigger in size and take up a lot of memory which slows it down.

My words to junior developer to learn OOP would be to understand the concept as a black box, when you write a Object Oriented Program, you are creating a black box for others to use, they initialize your Object, then use certain methods to get the task done, where as if one is using other's program, they are using a black box, we initialize object, then use methods available to get the task done.

One can also think of Object Oriented Programming concept as a collection of similar methods (functions) and properties (variables). I'd ask him to follow good tutorials and give them a real example on how can OOP make programming easier, and simpler, and how can he use same code again and again.

Question 13

Name an example of a Front Controller and give its advantages and disadvantages.

I don't know any example of front controller, I work on MVC architecture, as front controller is the "C" of MVC, I know a little bit about it. Front Controller basically is a architecture in which every request goes through a single file allowing that file to process every request.

The advantage of using this architecture is that a application becomes modularized, and developing in it would be very easy. We can use a file to route different requests to different components.

There are many other advantages as well, front end can be separated from backend, we can keep track of requests easily, creating APIs would be great as we can log who is requesting what at any point of time.

There are also few disadvantages of using Front Controller (Or even MVC as such) because no matter what a request is, we have to do a little processing to determine which part of application is gonna process that request. Which slows application by a little bit. But, that is very less amount of process clock and today and we can ignore that part as writing any application without a proper architecture would result in having a lot of bugs.

This happens when we reload a page with post request, it asks if we want to send the same data again to server. To avoid it, we can redirect the user after each post request to load with a get request, then it'll not pop up this dialog.

THE END

Solutions Nishchal Gautam Solution by Nishchal Gautam / @cyb3rhck