tag:blogger.com,1999:blog-50138295289449840592024-03-19T00:31:26.761-07:00Open Source For GeeksI am a software developer and I am maintaining this tech blog as my hobby. It all started when I thought of writing some posts on common Java concepts. But now it encompasses Java, Android, Linux, Puzzles, data structures, Tools and Utilities . I also write posts on technical difficulties I face during my day to day work and how could we resolve it. I write posts with a lot of passion and with the hope that it helps others.Aniket Thakurhttp://www.blogger.com/profile/07553743551249736583noreply@blogger.comBlogger515125tag:blogger.com,1999:blog-5013829528944984059.post-13917967158879890922023-12-29T23:12:00.000-08:002023-12-29T23:12:21.948-08:00Understanding Rest & Spread operator in Javascript<h4 style="text-align: left;"> Background</h4><div>In JavaScript, we tend to use rest & spread operators to keep code simple and easy to read. Both use three dots "..." but the use cases are different. In this post, we will see what these operations are and how to use them.</div><div><br /></div><div class="separator" style="clear: both; text-align: center;"><a href="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEjLbYW2cmNC34N1pGWWuqgGbRkQe0Ojh6kAlEz5HW0M-CriVku6UV3Ok-MkmEqFuhn7IAJNA12VNhMuuTai7qcw-MUTN_um8GEkuRjsoWrohzLkKG-ZAylqxoWRGk0ebamPliNXyjZ1qLMiIjknM0Eqsg41DPOajxEuYI4utiN6EFhcAnSm-b_1i22EvQXx/s300/rest_vs_spread_js.jpg" imageanchor="1" style="margin-left: 1em; margin-right: 1em;"><img border="0" data-original-height="168" data-original-width="300" height="179" src="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEjLbYW2cmNC34N1pGWWuqgGbRkQe0Ojh6kAlEz5HW0M-CriVku6UV3Ok-MkmEqFuhn7IAJNA12VNhMuuTai7qcw-MUTN_um8GEkuRjsoWrohzLkKG-ZAylqxoWRGk0ebamPliNXyjZ1qLMiIjknM0Eqsg41DPOajxEuYI4utiN6EFhcAnSm-b_1i22EvQXx/w320-h179/rest_vs_spread_js.jpg" width="320" /></a></div><br /><div>Before we proceed to looking into individual aspects just remember <b>rest is for collecting elements and spread is for spreading elements. </b></div><div><br /></div><h4 style="text-align: left;">Rest operator</h4><div>Let's try to see the rest operators 1st. The rest operator is used to collect the remaining elements in an array. The rest syntax works in both function arguments and arrays. Let's look at an example below</div><div><br /></div><div><div class="separator" style="clear: both; text-align: center;"><a href="https://blogger.googleusercontent.com/img/a/AVvXsEg7GbqoysEy4tbDdD942eTj5uf9jJv_SYs9iD3_UWVOjJ7EswZ5jsxDh2KXjrUZNac9C46DpwGPRV512VHjALCpzsrHhCrnU1njFeHVjgxtBuJmhLQ97YzhS-1l_W7KTIibRmdUjBDmpSWJ6AuTacNkLwdvX2jWfclnBXVBFepTD32B41TYa_VKZDoxFGzZ" style="margin-left: 1em; margin-right: 1em;"><img alt="" data-original-height="115" data-original-width="467" height="158" src="https://blogger.googleusercontent.com/img/a/AVvXsEg7GbqoysEy4tbDdD942eTj5uf9jJv_SYs9iD3_UWVOjJ7EswZ5jsxDh2KXjrUZNac9C46DpwGPRV512VHjALCpzsrHhCrnU1njFeHVjgxtBuJmhLQ97YzhS-1l_W7KTIibRmdUjBDmpSWJ6AuTacNkLwdvX2jWfclnBXVBFepTD32B41TYa_VKZDoxFGzZ=w640-h158" width="640" /></a></div><br /><br /></div><div>As you can see whatever number of arguments you pass to add function is going to capture 1st two in a & b respectively (in this case 1 & 2) and the remaining ones (values - [3, 4]) will be captured in an argument called rest which is an array.</div><div><br /></div><div>The rest operator is also used for destructuring arrays like below</div><div><div class="separator" style="clear: both; text-align: center;"><a href="https://blogger.googleusercontent.com/img/a/AVvXsEjIfO1A3idbvBAFKzPqezypJCmcTYYC0ryDkGp07k8g5G84uKrGufbAkrn9Vkrwa4elkIGu29sw8V_gE4WfYxUtTvvdyAwrJ3Pdm67gK7d5hZeRFSKDax3EdVfShx7OH9FLAS5_nQbhsZfeVk8TXe2d4NkNXMt-b_Wi88aMhyEetuex6WW4DVYCHvDoQc-x" style="margin-left: 1em; margin-right: 1em;"><img alt="" data-original-height="122" data-original-width="640" height="122" src="https://blogger.googleusercontent.com/img/a/AVvXsEjIfO1A3idbvBAFKzPqezypJCmcTYYC0ryDkGp07k8g5G84uKrGufbAkrn9Vkrwa4elkIGu29sw8V_gE4WfYxUtTvvdyAwrJ3Pdm67gK7d5hZeRFSKDax3EdVfShx7OH9FLAS5_nQbhsZfeVk8TXe2d4NkNXMt-b_Wi88aMhyEetuex6WW4DVYCHvDoQc-x=w640-h122" width="640" /></a></div></div><h4 style="text-align: left;">Spread operator</h4><div>The Spread operator introduced in ES6 as the name suggests is used to spread the elements.</div><div><div class="separator" style="clear: both; text-align: center;"><a href="https://blogger.googleusercontent.com/img/a/AVvXsEhl6lNj_nWvutNbQReP9hdj0lWkJY4KS3ZB5R8eJcC-TCxWD0IR3adE12zWCORXD2qWwsH-utniy9_EXb3BJuJul2x7WyRcxXHH00FX_A5qdnDq3IqWVB6R-8ia7y2OaMjuN40ngeMIpxuScSifViXvagUU0p_eMf-Z12iVpZqi61H4ro9w3DAJ_IC1Lgkp" style="margin-left: 1em; margin-right: 1em;"><img alt="" data-original-height="111" data-original-width="475" height="150" src="https://blogger.googleusercontent.com/img/a/AVvXsEhl6lNj_nWvutNbQReP9hdj0lWkJY4KS3ZB5R8eJcC-TCxWD0IR3adE12zWCORXD2qWwsH-utniy9_EXb3BJuJul2x7WyRcxXHH00FX_A5qdnDq3IqWVB6R-8ia7y2OaMjuN40ngeMIpxuScSifViXvagUU0p_eMf-Z12iVpZqi61H4ro9w3DAJ_IC1Lgkp=w640-h150" width="640" /></a></div>For eg, in the above code, you can see how "123" was split automatically into 1,2 & 3 by the spread operator.</div><div><br /></div><div>We can also use this operator to easily create copies of arrays and objects. For eg.,</div><div><br /></div><div><div class="separator" style="clear: both; text-align: center;"><a href="https://blogger.googleusercontent.com/img/a/AVvXsEiXE_hqtcwP9i3Eeq0dLMBZJG-A6gM71DOp6rUwoqLb_mNGGdv07ivns_9hB4dQIOeE4WWebjMUW70sx2XXmFP12zx3bi2374MxxMTK-gmZ42lDdb1sYcajMal7ptxfD4hRKWHBLMf8y_Ze_HR81mWn8fRHPfyfIQvbUQkn_cNQ5fULlPiY1tjvKfVfb9X4" style="margin-left: 1em; margin-right: 1em;"><img alt="" data-original-height="382" data-original-width="641" height="381" src="https://blogger.googleusercontent.com/img/a/AVvXsEiXE_hqtcwP9i3Eeq0dLMBZJG-A6gM71DOp6rUwoqLb_mNGGdv07ivns_9hB4dQIOeE4WWebjMUW70sx2XXmFP12zx3bi2374MxxMTK-gmZ42lDdb1sYcajMal7ptxfD4hRKWHBLMf8y_Ze_HR81mWn8fRHPfyfIQvbUQkn_cNQ5fULlPiY1tjvKfVfb9X4=w640-h381" width="640" /></a></div><br /><br /></div><div> <b>NOTE</b>: Spread operator helps maintain immutability requirements. This is helpful when you need data that should not mutate (Eg. Redux state).</div><div><br /></div><div>As I mentioned before rest and spread operators are used commonly in javascript and we will see more usages and examples in upcoming posts.</div><h4 style="text-align: left;">Related Links</h4><div><ul style="text-align: left;"><li><a href="https://opensourceforgeeks.blogspot.com/2023/12/closures-in-javascript.html">Closures in Javascript (OSFG)</a></li></ul></div><div><br /><br /></div><div><br /></div>Aniket Thakurhttp://www.blogger.com/profile/07553743551249736583noreply@blogger.com0tag:blogger.com,1999:blog-5013829528944984059.post-76088549436091669292023-12-29T04:08:00.000-08:002024-02-23T21:48:44.083-08:00Closures in Javascript<h4 style="text-align: left;"> Background</h4><div>In one of the earlier posts, we saw how to use Javascript (JS) closures to hide variables from the console with a counter-example. In this post, I will explain JS closures in more detail.</div><div><br /></div><h4 style="text-align: left;">Closures in Javascript</h4><div>Quoting closures from MDN web docs:</div><div><br /></div><div></div><div style="text-align: left;"><b>A closure is the combination of a function bundled together (enclosed) with references to its surrounding state (the lexical environment). In other words, a closure gives you access to an outer function's scope from an inner function. In JavaScript, closures are created every time a function is created, at function creation time.</b></div><p style="text-align: left;">It's important to note that it is not just a function but a combination of function + referenced to its lexical environment. </p><p style="text-align: left;">Let's take a simple example:</p>
<pre class="brush: java">(() => {
var name = "Aniket";
const displayName = () => {
console.log(name);
}
displayName();
})()
</pre>
<p>The (()=>{})() is a self-executing function. Inside it, you can see an anonymous function defined using the arrow operator. Inside this function, we have defined a variable called name and again an anonymous function called displayName which prints the name variable in the console. </p><p>What is interesting to note here is that even though the variable name is local to the outermost anonymous function we can still access it inside the displayName method, this is possible due to closures. When we created an anonymous function & assigned it to the displayName const variable it actually created a closure that comprised of the function itself + the reference to the lexical environment which includes the name variable defined in the outer scope.</p><p><b>NOTE</b>: Nested functions have access to variables declared in their outer scope.</p><h4 style="text-align: left;">Understanding scopes</h4><div>In the above examples, the variable name was defined in a function and had functional scope. It was accessible in that function + the methods nested inside it. It will not be accessible in the global scope. </div><div><br /></div><div>Before ES6 there were just two scopes, function scope and global scope. variables defined inside a function had function scope where whereas those defined outside had global scopes. This came with its own challenges as now if you define variables inside if else block braces then it creates a global scope because blocks with curly braces do not create scopes.</div><div><br /></div><div>Eg. see below</div><div><div class="separator" style="clear: both; text-align: center;"><a href="https://blogger.googleusercontent.com/img/a/AVvXsEhDhXdeL75Kq1UnPTaLRtyxI4hlvJEB8G2ofJ4a1vXkIfjbN9oQvI4ODsSaTjAsCltY4QD3TElxmtZUJerBb3UOPk3BU2oSoQoFQemtFY5v_Hh4atq2BgjyRTGMG9lXaIm14081MikDYsH5BBR8pyms6he0yfjpGlRs_ABhROr1oxC7OUn2WudJXxWN3nN6" style="margin-left: 1em; margin-right: 1em;"><img alt="" data-original-height="336" data-original-width="342" height="315" src="https://blogger.googleusercontent.com/img/a/AVvXsEhDhXdeL75Kq1UnPTaLRtyxI4hlvJEB8G2ofJ4a1vXkIfjbN9oQvI4ODsSaTjAsCltY4QD3TElxmtZUJerBb3UOPk3BU2oSoQoFQemtFY5v_Hh4atq2BgjyRTGMG9lXaIm14081MikDYsH5BBR8pyms6he0yfjpGlRs_ABhROr1oxC7OUn2WudJXxWN3nN6=w320-h315" width="320" /></a></div><br />
Here check variable even though was defined inside the if block has become a global scoped variable (Unlike other languages like Java where it would have created a local scoped variable). </div><div><br /></div><div>To handle this ES6 introduced two new declarations</div><div><ul style="text-align: left;"><li><b>let </b>- defines a variable local to the scope</li><li><b>const </b>- defines a constant variable again local to the scope.</li></ul><div>See below for example:</div><div><br /></div><div><div class="separator" style="clear: both; text-align: center;"><a href="https://blogger.googleusercontent.com/img/a/AVvXsEgjQvlHL2ryz414lOKTrzDBW0G0eJZnDeSqcBhRuPYL1nYLJUUXTOPcAO0nukh02Z9SmiocCIRTvW6TrlXAAH9WQzaydAZlF2djtBADQCrayOi0lvINInEq_joNvoIvepNbqd6JCNCBUQtUF2jY2PkE7oRajzoDZ1zxXsNYXlXDTodpGjSnsHyroATyUPD4" style="margin-left: 1em; margin-right: 1em;"><img alt="" data-original-height="181" data-original-width="452" height="160" src="https://blogger.googleusercontent.com/img/a/AVvXsEgjQvlHL2ryz414lOKTrzDBW0G0eJZnDeSqcBhRuPYL1nYLJUUXTOPcAO0nukh02Z9SmiocCIRTvW6TrlXAAH9WQzaydAZlF2djtBADQCrayOi0lvINInEq_joNvoIvepNbqd6JCNCBUQtUF2jY2PkE7oRajzoDZ1zxXsNYXlXDTodpGjSnsHyroATyUPD4=w400-h160" width="400" /></a></div><br /><br /></div><div><div class="separator" style="clear: both; text-align: center;"><a href="https://blogger.googleusercontent.com/img/a/AVvXsEj8YY7bfWoT3G-mfP0pofMx_KFAHJ5tczbSySI4t3tZCwe_sUbICCz3nNLqxc0OfKPBfBKQl9wi0CyqRZR7Mu78BqZn2F0J8icXSsqfBSNlztJ9Nz9o4iKZhjd9Huz5yU9kSpdCC_pnotUQBDqLTOwm9XwAzglTAIolIoNrYtCvfmdNlsDHXeeyJQrdyGK7" style="margin-left: 1em; margin-right: 1em;"><img alt="" data-original-height="178" data-original-width="440" height="162" src="https://blogger.googleusercontent.com/img/a/AVvXsEj8YY7bfWoT3G-mfP0pofMx_KFAHJ5tczbSySI4t3tZCwe_sUbICCz3nNLqxc0OfKPBfBKQl9wi0CyqRZR7Mu78BqZn2F0J8icXSsqfBSNlztJ9Nz9o4iKZhjd9Huz5yU9kSpdCC_pnotUQBDqLTOwm9XwAzglTAIolIoNrYtCvfmdNlsDHXeeyJQrdyGK7" width="400" /></a></div><br /><br /></div>
<div><b>NOTE</b>: Closure gives the function access to its outer function but the outer function can also be a nested function inside another outer function. In such cases, the innermost function will have access to all the outer nested functions via the closure chain. See eg below</div></div><div><br /></div><div><div class="separator" style="clear: both; text-align: center;"><a href="https://blogger.googleusercontent.com/img/a/AVvXsEgYQtW0L21yUFBPyrmoK4HvBfJanh2Z_v6JQlpRfrVxLyaXpbCoosOJj4ui3epPQZdY-WMOjJs0rNmgBfkq_Xcu5Np9JUbWNNKAbjWWrY96dnTJre1tT-ZRWoPvLFKeR7F-ZeOz3N5ZvbAH2UBVOy0Ydlzrp6V-l4r1IPDnxZU8wSdlbsBxuvriMSsvLWGK" style="margin-left: 1em; margin-right: 1em;"><img alt="" data-original-height="260" data-original-width="328" height="317" src="https://blogger.googleusercontent.com/img/a/AVvXsEgYQtW0L21yUFBPyrmoK4HvBfJanh2Z_v6JQlpRfrVxLyaXpbCoosOJj4ui3epPQZdY-WMOjJs0rNmgBfkq_Xcu5Np9JUbWNNKAbjWWrY96dnTJre1tT-ZRWoPvLFKeR7F-ZeOz3N5ZvbAH2UBVOy0Ydlzrp6V-l4r1IPDnxZU8wSdlbsBxuvriMSsvLWGK=w400-h317" width="400" /></a></div><br /><br /></div><h4 style="text-align: left;">Interesting examples</h4><p>Now let's see some interesting examples before we wind this up.</p><p>See the below examples & predict the output</p>
<pre class="brush: java">
const myName = ["Aniket", "Abhijit", "Awantika"];
for(var i; i<myName.length;i++)
{
setTimeout(function(){
console.log('Name: ' + myName[i] + 'at index:' + i);
},3000)
}
</pre>
<p>The output is</p><p></p><div class="separator" style="clear: both; text-align: center;"><a href="https://blogger.googleusercontent.com/img/a/AVvXsEg4bZFBxjNRY6-0A1pmiEL6dNs8jzXycOH2nKqo_oJE-7VJ0dgnjnJFnibyUY4KpzIVK7u5Q49CDW8J7IfMOF9cXe55TpgcZak4LGcI13lzxEtbFeGhlCML7Rl09y3R3weh7o9LHuCR9AsytXmuu0ahAKFMR4d42d_ZrQhd7wDriVcTK0J8TmNaAANDwRD0" style="margin-left: 1em; margin-right: 1em;"><img alt="" data-original-height="232" data-original-width="575" height="161" src="https://blogger.googleusercontent.com/img/a/AVvXsEg4bZFBxjNRY6-0A1pmiEL6dNs8jzXycOH2nKqo_oJE-7VJ0dgnjnJFnibyUY4KpzIVK7u5Q49CDW8J7IfMOF9cXe55TpgcZak4LGcI13lzxEtbFeGhlCML7Rl09y3R3weh7o9LHuCR9AsytXmuu0ahAKFMR4d42d_ZrQhd7wDriVcTK0J8TmNaAANDwRD0=w400-h161" width="400" /></a></div><br /><p></p>
It prints undefined as Name & index as 3 all the three times the loop executes. Let's try to understand why this happened: When we pass a custom function inside setTimeout it creates a closure of the function bundled with the captured environment from the out functions scope. Three closures are created by the loop but each shares the same lexical environment which has the variable "i" with changing values. This is because the "i" variable is defined as var and has a global scope. The value of "i" in the passed function is determined when it is actually executed after the timeout completes (when it comes from the event loop). Since the loop has already been completed by the time these closures from the event loop are executed "i" points to 3 and there is no such index in that array as the size is 3 and the index range from 0 to 2. Hence it prints "i" as 3 and the name as "undefined" three times - one for each closure created in the loop.<p></p><p>You can fix this by using a wrapper function to be passed inside setTimeout API argument which will create its own closure with the actual local value of "i" and pass it to the event table instead of just the original closure which is pointing to global scoped "I". Eg see below where I have given two ways one using function keyword and one using anonymous function</p><p><br /></p><p></p><div class="separator" style="clear: both; text-align: center;"><a href="https://blogger.googleusercontent.com/img/a/AVvXsEi-a94dm4-eaLtjVOPPG87SoGiMn5DIvIHYJuu7Xi64UgbC0EA9hWeJF0m8-LzspKY89AqY0QnVDYtYzh4HYxhjYP42lB1pIWEdzVj98vFUaqUQJRMYPk-q1bJZ8-5gq3jSEvs3KVfx0dXsUsu4KzOy1WynFu-mfXP9W7qSGQtqiWiObze5riNrPFYApptW" style="margin-left: 1em; margin-right: 1em;"><img alt="" data-original-height="483" data-original-width="582" height="332" src="https://blogger.googleusercontent.com/img/a/AVvXsEi-a94dm4-eaLtjVOPPG87SoGiMn5DIvIHYJuu7Xi64UgbC0EA9hWeJF0m8-LzspKY89AqY0QnVDYtYzh4HYxhjYP42lB1pIWEdzVj98vFUaqUQJRMYPk-q1bJZ8-5gq3jSEvs3KVfx0dXsUsu4KzOy1WynFu-mfXP9W7qSGQtqiWiObze5riNrPFYApptW=w400-h332" width="400" /></a></div><br />Or you could simply change var to let in the for loop which will create a block-scoped variable instead of a global scope and changes will still work fine.<p></p><p></p><div class="separator" style="clear: both; text-align: center;"><a href="https://blogger.googleusercontent.com/img/a/AVvXsEj7Ys5lWeLUdHES-uyiCADO0aQAXVJELm_aUsgHyFpGA_P_SKH9K7VfXEnJBkSjK9HRbV71iEPaBsx4gKG1Gsm31LoG786l-CSSzs-fRT8cKYcfvqUSjU270EHL5-QtOle5Vl8nAsAk9LoMmMc8j4ecNVqwB8n1nulREOH5igvitoy8wP1cyppKu5RSK-s7" style="margin-left: 1em; margin-right: 1em;"><img alt="" data-original-height="236" data-original-width="552" height="171" src="https://blogger.googleusercontent.com/img/a/AVvXsEj7Ys5lWeLUdHES-uyiCADO0aQAXVJELm_aUsgHyFpGA_P_SKH9K7VfXEnJBkSjK9HRbV71iEPaBsx4gKG1Gsm31LoG786l-CSSzs-fRT8cKYcfvqUSjU270EHL5-QtOle5Vl8nAsAk9LoMmMc8j4ecNVqwB8n1nulREOH5igvitoy8wP1cyppKu5RSK-s7" width="400" /></a></div><br /><p></p><div><br /></div><h4 style="text-align: left;">Related Links</h4><div><ul style="text-align: left;"><li><a href="https://opensourceforgeeks.blogspot.com/2016/05/hide-variable-from-console-access.html">Hide variable from console access using JS closure (OSFG)</a></li><li><a href="https://opensourceforgeeks.blogspot.com/2017/11/understanding-promises-in-javascript.html">Understanding promises in JS (OSFG)</a></li><li><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Closures">MDN web docs on closure</a></li></ul></div></myname>Aniket Thakurhttp://www.blogger.com/profile/07553743551249736583noreply@blogger.com0tag:blogger.com,1999:blog-5013829528944984059.post-42307470832320622462022-10-02T07:46:00.001-07:002022-10-02T07:46:14.409-07:00How to fix Apostrophes and double quotes not showing up in Windows<h4 style="text-align: left;"> Background</h4><p>Recently I started using Windows 11 and realized Apostrophes (Single quotes) and double quotes not showing up until I type in the next letter. This behavior is really annoying, especially for me (I am from India/Asia) if you are wondering đ . This is most probably because you are using a <b>US-international</b> keyboard. In this post, I will show you how to fix this behavior.</p><p><br /></p><h3 style="text-align: left;">Fixing "Apostrophes and double quotes not showing up in Windows"</h3><p>As I mentioned before the issue is with you using the <b>US-international</b> keyboard. So you need to fix that.</p><p>I am using "Windows 11" so the below steps are keeping that in mind, but you would have similar steps in another version of Windows.</p><p><br /></p><p></p><ol style="text-align: left;"><li>Select <b>Start </b>> <b>Settings </b>> T<b>ime & language</b> > <b>Language & region</b>.</li><li>Under Preferred languages, select the options from 1st language you are using and click on "<b>Language Options</b>".<br /><br /><div class="separator" style="clear: both; text-align: center;"><a href="https://blogger.googleusercontent.com/img/a/AVvXsEhOu1zhV1WNxAbLZZhhksb4cZwNtl6ViLHfvj-uFFCJq3y_9fshrc5z8KaCPmEE4n8zQMlBIYHwSgVu6jR4FCqK6Vy7myuYwILXquiBc4evynMhFNEzLepM1SZaUsL7sRznTPN_UEcj1UFtLgdl1gx0CsFK-QNdsGohY3yeU3amwHM7kkFlx2ceNfP7uA" style="margin-left: 1em; margin-right: 1em;"><img alt="" data-original-height="772" data-original-width="992" height="300" src="https://blogger.googleusercontent.com/img/a/AVvXsEhOu1zhV1WNxAbLZZhhksb4cZwNtl6ViLHfvj-uFFCJq3y_9fshrc5z8KaCPmEE4n8zQMlBIYHwSgVu6jR4FCqK6Vy7myuYwILXquiBc4evynMhFNEzLepM1SZaUsL7sRznTPN_UEcj1UFtLgdl1gx0CsFK-QNdsGohY3yeU3amwHM7kkFlx2ceNfP7uA" width="385" /></a></div><br /><br /><br /></li><li>Next, go under "Keyboards", here you will see the "<b>US-International</b>" keyboard installed. We need to remove this.</li><li>Let's add the Keyboard we intend to use 1st. I am adding English (India) but you can choose the keyboard you want (Let's say English (United Kingdom)).</li><li>Now select "<b>US-International</b>" keyboard from the list.<br /><div class="separator" style="clear: both; text-align: center;"><a href="https://blogger.googleusercontent.com/img/a/AVvXsEg4R1MTWY6hYFlhLCTXKEb6mdDw-ssYFgJvYNJHUcdZ1CUSULDAzfM12dacDVpqux6GmQcaB474MXPG4LiVvqB4RaF0I87B25OpuQJAdCgzrs6I4ZMf1AHihkyta1vKJ8S2AMedLO-IOWFnLcg4k-vSJfkmFcd_xjODycT0UyGFqL4eI_Lr192G4Ue3QQ" style="margin-left: 1em; margin-right: 1em;"><img alt="" data-original-height="766" data-original-width="987" height="300" src="https://blogger.googleusercontent.com/img/a/AVvXsEg4R1MTWY6hYFlhLCTXKEb6mdDw-ssYFgJvYNJHUcdZ1CUSULDAzfM12dacDVpqux6GmQcaB474MXPG4LiVvqB4RaF0I87B25OpuQJAdCgzrs6I4ZMf1AHihkyta1vKJ8S2AMedLO-IOWFnLcg4k-vSJfkmFcd_xjODycT0UyGFqL4eI_Lr192G4Ue3QQ" width="387" /></a></div><br /><br /></li><li>Changes should immediately take effect.</li></ol><h4 style="text-align: left;">Related Links</h4><div><ul style="text-align: left;"><li><a href="https://superuser.com/questions/122625/apostrophes-and-double-quotes-dont-show-up-until-i-type-the-next-letter">Apostrophes and double quotes don't show up until I type the next letter (SO)</a></li></ul></div><p></p>Aniket Thakurhttp://www.blogger.com/profile/07553743551249736583noreply@blogger.com0tag:blogger.com,1999:blog-5013829528944984059.post-78938250296762552612022-10-02T07:03:00.000-07:002022-10-02T07:03:30.049-07:00How to move TaskBar to the top or side in Windows 11<h4 style="text-align: left;"> Background</h4><div>I recently started using Windows 11 and noticed there is no way to move windows TaskBar around. It is permanently fixed toward the bottom of the screen. I personally need the TaskBar towards the left or right of the screen and here's why - Our screen (Desktop or Laptop has more horizontal space than vertical space, hence it's only logical to keep TaskBar on the left or right of the screen so that it takes only horizontal space). Though there is no good way to move the TaskBar around there is a registry edit hack that does the trick. </div><div><br /></div><div><b>NOTE</b>: If you are a normal windows user (Have not worked on programming and Windows internals before), I would recommend not to do the below but just live with TaskBar being on the bottom. Follow the below steps only if you know what you are doing and your own risk.</div><div><br /></div><h4 style="text-align: left;">How to move TaskBar to the top or side in Windows 11</h4><div><ol style="text-align: left;"><li>Open "Windows Start" and search for "<b>regedit</b>" OR</li><li>Go to "Run" (using <kbd class="keyboard-key nowrap" style="background-color: #f9f9f9; background-image: linear-gradient(rgb(238, 238, 238), rgb(249, 249, 249), rgb(238, 238, 238)); border-radius: 0.2em; border: 1px solid rgb(170, 170, 170); box-shadow: rgba(0, 0, 0, 0.1) 0.1em 0.1em 0.2em; font-family: inherit; font-size: 0.85em; padding: 0.1em 0.3em; white-space: nowrap;">â Win</kbd><span style="background-color: white; color: #202122; font-family: sans-serif; font-size: 14px;">+</span><kbd class="keyboard-key nowrap" style="background-color: #f9f9f9; background-image: linear-gradient(rgb(238, 238, 238), rgb(249, 249, 249), rgb(238, 238, 238)); border-radius: 0.2em; border: 1px solid rgb(170, 170, 170); box-shadow: rgba(0, 0, 0, 0.1) 0.1em 0.1em 0.2em; font-family: inherit; font-size: 0.85em; padding: 0.1em 0.3em; white-space: nowrap;">R</kbd>) and type "<b>regedit</b>" and press enter.<br /><br /><div class="separator" style="clear: both; text-align: center;"><a href="https://blogger.googleusercontent.com/img/a/AVvXsEgmQk-pQxiRiZmJuunjw48-TR0k6y-2U25bq2eEsQtOhoPVJQeMegptVN76tae3aH0sqLztG5HGhjUKVufAaiO55NDAASvMu3KTOiI8k-XHzAgY904bg2BZ1bFvT3Bkln8N1Kp4EFHuiWtS4mt804sG32x2a_bXVE0asCnwiAML7cLxYF7lLsG1gdxOpw" style="margin-left: 1em; margin-right: 1em;"><img alt="" data-original-height="272" data-original-width="457" height="190" src="https://blogger.googleusercontent.com/img/a/AVvXsEgmQk-pQxiRiZmJuunjw48-TR0k6y-2U25bq2eEsQtOhoPVJQeMegptVN76tae3aH0sqLztG5HGhjUKVufAaiO55NDAASvMu3KTOiI8k-XHzAgY904bg2BZ1bFvT3Bkln8N1Kp4EFHuiWtS4mt804sG32x2a_bXVE0asCnwiAML7cLxYF7lLsG1gdxOpw" width="320" /></a><br /><br /></div><br /></li><li>You will get a prompt asking if you want to let the current user make changes to "<b>Registry Editor</b>". Press Ok.</li><li>Next from the left hierarchy panel, you need to go to the following entry:<br /><pre style="background: rgba(118, 134, 150, 0.05); border-radius: 3px; border: 0px; box-shadow: rgba(118, 134, 150, 0.1) 0px 0px 0px 1px inset; box-sizing: border-box; color: rgb(51, 51, 51) !important; font-family: "Roboto Mono", monospace; font-size: 14px; font-stretch: normal; font-variant-east-asian: normal; font-variant-numeric: normal; line-height: 1.6; margin-bottom: 1.6em; margin-top: 0px; max-width: 100%; outline: 0px; overflow: auto; padding: 14.4px 21.6px; position: relative; vertical-align: baseline; white-space: pre-wrap; word-break: break-word;"><b>HKEY_CURRENT_USER\Software\Microsoft\Windows\CurrentVersion\Explorer\StuckRects3
</b></pre></li><li>Double-click the Settings binary key.<br /><div class="separator" style="clear: both; text-align: center;"><a href="https://blogger.googleusercontent.com/img/a/AVvXsEhG71dLr42PXUiUCV_c3Wuw-L-AJEkveSkqjJK6jGNJw0SjJvex_ioTWctIcQxSlYEFGp4lXb46vIEBGY33xb_fU5RW_sm8jiET2c_RHK_7-0vXZTTWKD810tGdFuw4Wo40Nq1tEY3dGqyNnBH1SNiGulWHYwzNNWbhR3tYR17ITjqbmEgt_D20TiLj6Q" style="margin-left: 1em; margin-right: 1em;"><img alt="" data-original-height="628" data-original-width="978" height="410" src="https://blogger.googleusercontent.com/img/a/AVvXsEhG71dLr42PXUiUCV_c3Wuw-L-AJEkveSkqjJK6jGNJw0SjJvex_ioTWctIcQxSlYEFGp4lXb46vIEBGY33xb_fU5RW_sm8jiET2c_RHK_7-0vXZTTWKD810tGdFuw4Wo40Nq1tEY3dGqyNnBH1SNiGulWHYwzNNWbhR3tYR17ITjqbmEgt_D20TiLj6Q=w640-h410" width="640" /></a></div><br /></li><li>Under "<b>Value data</b>" section click on the entry with the 2nd row and the 6th column (The default value would be 03). <br /><br /><div class="separator" style="clear: both; text-align: center;"><a href="https://blogger.googleusercontent.com/img/a/AVvXsEgESR1MTXsVhb3APdR3A8N43WZI5v4aHaf5uD5i-rMB6HXy8v7ZZemKLmIHVg-Wd6TFXOC9HKhOmdYedU6JjllP29mkNMRGsRNJFMmIlkKEKsOWzA3GtWef19r1qrI7qbo1VCCbU_7Iysltye6VKuP2yLLg5jxu4yqsxt2w3j2A7NWkmEJ-7neTR2e6vQ" style="margin-left: 1em; margin-right: 1em;"><img alt="" data-original-height="616" data-original-width="975" height="404" src="https://blogger.googleusercontent.com/img/a/AVvXsEgESR1MTXsVhb3APdR3A8N43WZI5v4aHaf5uD5i-rMB6HXy8v7ZZemKLmIHVg-Wd6TFXOC9HKhOmdYedU6JjllP29mkNMRGsRNJFMmIlkKEKsOWzA3GtWef19r1qrI7qbo1VCCbU_7Iysltye6VKuP2yLLg5jxu4yqsxt2w3j2A7NWkmEJ-7neTR2e6vQ" width="640" /></a></div><br /><br /><br /></li><li>Press the delete key and replace it with the 01 value to move the taskbar to the top. Press ok.<br /><div class="separator" style="clear: both; text-align: center;"><a href="https://blogger.googleusercontent.com/img/a/AVvXsEh40_zJAeIx32ylOJDrXxwB_dncwMh4bXUR7UrcaqZ6Kw5aKV0zj19621SFvKntQXn3MlONbrbR0BhcF0rzjp-N3HDDBRpKauJODUhJSiZ653yS_zgTSEmjVHif1YRQOklt6foIx43DxotJP9rDdKmcq0K8Rp5ukSKouh2PJjyvz9T_zSANrqNCuay_4A" style="margin-left: 1em; margin-right: 1em;"><img alt="" data-original-height="616" data-original-width="968" height="407" src="https://blogger.googleusercontent.com/img/a/AVvXsEh40_zJAeIx32ylOJDrXxwB_dncwMh4bXUR7UrcaqZ6Kw5aKV0zj19621SFvKntQXn3MlONbrbR0BhcF0rzjp-N3HDDBRpKauJODUhJSiZ653yS_zgTSEmjVHif1YRQOklt6foIx43DxotJP9rDdKmcq0K8Rp5ukSKouh2PJjyvz9T_zSANrqNCuay_4A" width="640" /></a></div><br /><br /></li><li>You can replace them with the following values as you desire</li><ul><li><b>00: Move the Taskbar to the left</b></li><li><b>01: Move the Taskbar to the top</b></li><li><b>02: Move the Taskbar to the right</b></li><li><b>03: Move the Taskbar to the bottom</b></li></ul><li>For changes to take effect you need to restart the "Windows Explorer" process.</li><ol><li>You can go to "Task Manager" and restart the "Windows explorer" process. OR</li><li>Do it via "Command prompt" via the following commands.</li><ol><li>Open the command prompt from the start menu or from the run menu(<kbd class="keyboard-key nowrap" style="background-color: #f9f9f9; background-image: linear-gradient(rgb(238, 238, 238), rgb(249, 249, 249), rgb(238, 238, 238)); border-radius: 0.2em; border: 1px solid rgb(170, 170, 170); box-shadow: rgba(0, 0, 0, 0.1) 0.1em 0.1em 0.2em; font-family: inherit; font-size: 0.85em; padding: 0.1em 0.3em; white-space: nowrap;">â Win</kbd><span style="background-color: white; color: #202122; font-family: sans-serif; font-size: 14px;">+</span><kbd class="keyboard-key nowrap" style="background-color: #f9f9f9; background-image: linear-gradient(rgb(238, 238, 238), rgb(249, 249, 249), rgb(238, 238, 238)); border-radius: 0.2em; border: 1px solid rgb(170, 170, 170); box-shadow: rgba(0, 0, 0, 0.1) 0.1em 0.1em 0.2em; font-family: inherit; font-size: 0.85em; padding: 0.1em 0.3em; white-space: nowrap;">R</kbd>) and "<b>cmd</b>" command.</li><li>"<b>taskkill /f /im explorer.exe"</b></li><li>"<b>start explorer.exe</b>"<br /><div class="separator" style="clear: both; text-align: center;"><a href="https://blogger.googleusercontent.com/img/a/AVvXsEhKE3dKjYI_ls2fh723fwtW_Hut4gWoY0cDcmaISQNDsWh04LmOXUBhImeLImHtCHeS4Pcr75FNNbi3hDSt29HJ82Ayarx0TZx7lVP9jb0zak6L0JwKztE28YnLIr-6pZZx6R2VHk3iLkSNWWWwS7HLx0_7uztSWZa05a_NwPkfZQm4aR2QTYoqOq6-xg" style="margin-left: 1em; margin-right: 1em;"><img alt="" data-original-height="327" data-original-width="1098" height="190" src="https://blogger.googleusercontent.com/img/a/AVvXsEhKE3dKjYI_ls2fh723fwtW_Hut4gWoY0cDcmaISQNDsWh04LmOXUBhImeLImHtCHeS4Pcr75FNNbi3hDSt29HJ82Ayarx0TZx7lVP9jb0zak6L0JwKztE28YnLIr-6pZZx6R2VHk3iLkSNWWWwS7HLx0_7uztSWZa05a_NwPkfZQm4aR2QTYoqOq6-xg=w640-h190" width="640" /></a></div></li></ol></ol></ol></div><div><br /></div><div>You will then see Taskbar move to the top of the screen.</div><div><br /></div><div><div class="separator" style="clear: both; text-align: center;"><a href="https://blogger.googleusercontent.com/img/a/AVvXsEh0Z3oqn7RuRi1WR7fjfMNj_ibje4qifklNYVYU5owBw3UIkB96ainNHTbXNemXncLeeYOwRYlpFfOAEfhWv3p4vRbeh2Z6tmRGg710lHqCqQt4CcaLppvej1D9FMBEATRtWqcvxICdBfHElkwZq0S1PlNPpI1Jf1FwC8vAV6Qqt0_0DIvQBQd-vtacJw" style="margin-left: 1em; margin-right: 1em;"><img alt="" data-original-height="1080" data-original-width="1920" height="360" src="https://blogger.googleusercontent.com/img/a/AVvXsEh0Z3oqn7RuRi1WR7fjfMNj_ibje4qifklNYVYU5owBw3UIkB96ainNHTbXNemXncLeeYOwRYlpFfOAEfhWv3p4vRbeh2Z6tmRGg710lHqCqQt4CcaLppvej1D9FMBEATRtWqcvxICdBfHElkwZq0S1PlNPpI1Jf1FwC8vAV6Qqt0_0DIvQBQd-vtacJw" width="640" /></a></div><br /><br /></div><div><b>NOTE</b>: With the above steps, you can move the TaskBar to the right or left as well, but it's useless (It does not work as expected). Hopefully, Windows 11 team fixes this sooner but we have to live with it for now. I personally am not happy with the above as I really want my TaskBar on the right due to the reasons mentioned in the "Background section" at the top.</div><div><br /></div><div><br /></div><div><br /></div>Aniket Thakurhttp://www.blogger.com/profile/07553743551249736583noreply@blogger.com0tag:blogger.com,1999:blog-5013829528944984059.post-699700091421362802021-04-29T08:47:00.001-07:002021-04-29T08:47:31.463-07:00How to fix issue of not able to click anything on Windows 10<h2 style="text-align: left;"> Background</h2><div>Recently I came across an issue in Windows 10 where I was not able to click on icons. This was a relatively weird issue. What was happening is - I could click either on icons on the taskbar or icons on the desktop but not both. Also, cancel, minimize buttons won't work. This happened when I switched my mouse from USB to wireless. Anyways there are few ways we can fix this which I have listed below.</div><div><br /></div><div><ol style="text-align: left;"><li><b>Restart PC</b></li><li><b>Restart File Explorer</b></li><li><b>Use sfc (system file scanner)</b></li></ol></div><div><br /></div><h3 style="text-align: left;">Restart PC</h3><div>Well, why not? This fixed the problem. There is not a lot of problems that restarting cant fix. But this is associated with system reboot time which I hate. I tried this for few times but quickly got tired of it. Restart every time I switch my mouse? Bad idea.</div><div><br /></div><div><br /></div><h3 style="text-align: left;">Restart File Explorer</h3><div>If the issue was with explorer we could quickly try to kill File explorer and restart it. Go to Task Manager by</div><div><ul style="text-align: left;"><li>Ctrl + Alt + Delete</li><li>Ctrl + Shift + Escape</li></ul><div>Find Windows Explorer and kill it</div></div><div><br /></div><div><div class="separator" style="clear: both; text-align: center;"><a href="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEiTtBwk89kMe9g5TAUB_g2rguW7qXtPxvhG1mlRqON9tNGzQE99HAMCwVkFCAZu0Xnkf77KNgwi7aEET8jh3fOCyfSVwegrlO9EjLuc8jp6DbGy8AI22PwKfzZlpgY7hO_X6d2tdQW1g67F//" style="margin-left: 1em; margin-right: 1em;"><img alt="" data-original-height="729" data-original-width="822" height="354" src="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEiTtBwk89kMe9g5TAUB_g2rguW7qXtPxvhG1mlRqON9tNGzQE99HAMCwVkFCAZu0Xnkf77KNgwi7aEET8jh3fOCyfSVwegrlO9EjLuc8jp6DbGy8AI22PwKfzZlpgY7hO_X6d2tdQW1g67F/w400-h354/image.png" width="400" /></a></div><br /><br /></div><div>You can select the process and click delete. Or right-click and end process. To start it back in the same task manager go to File -> Run New Task (You can Also to Alt+F to open the file menu and then click and then click 'n' for new task)</div><div><br /></div><div>Once you open a new task window - enter explorer in it and press enter.</div><div>Your windows explorer will start again.</div><div><br /></div><div><br /></div><h3 style="text-align: left;">Use Systems file checker (SFC)</h3><div>This is what I use nowadays to fix this issue. My guess is some files get corrupted when I switch mouse or maybe the driver is buggy .. who knows! But running the following command fixes all.</div><div><br /></div><div>Make sure you run the below command as administrator from the command prompt.</div><div><ul style="text-align: left;"><li>sfc /scanall</li></ul></div><div><br /></div><div><div class="separator" style="clear: both; text-align: center;"><a href="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEjA2aRhxmExzrtnpN0PJtxLvHf075EdFMAYIjOB1D1G8uP8aVHTyXuEf2i7szdlm2ZDhC8Hc5VsYfXpEJLdUin90yWo3Vh2aikrXueXDGTqlzACWPDWunw_bWbzU1VA3zlOw6t7aiA8Sk_H//" style="margin-left: 1em; margin-right: 1em;"><img alt="" data-original-height="639" data-original-width="1103" height="370" src="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEjA2aRhxmExzrtnpN0PJtxLvHf075EdFMAYIjOB1D1G8uP8aVHTyXuEf2i7szdlm2ZDhC8Hc5VsYfXpEJLdUin90yWo3Vh2aikrXueXDGTqlzACWPDWunw_bWbzU1VA3zlOw6t7aiA8Sk_H/w640-h370/image.png" width="640" /></a></div><br />And the best part - No reboot required. This does take a couple of mins. But you can try browsing or something else at that time :)</div><div><br /></div><div><br /></div><div><br /></div>Aniket Thakurhttp://www.blogger.com/profile/07553743551249736583noreply@blogger.com0tag:blogger.com,1999:blog-5013829528944984059.post-88918267405489283002020-05-24T10:33:00.000-07:002020-05-24T10:33:08.199-07:00Decorators in Python<div dir="ltr" style="text-align: left;" trbidi="on">
<h4 style="text-align: left;">
Background</h4>
<div>
In the last post we saw what are <a href="https://opensourceforgeeks.blogspot.com/2020/05/understanding-python-closure.html">closures in Python</a>. In this post we will see what are decorators in python. Closures are heavily used in Decorators. Let's see how.</div>
<div>
<br /></div>
<h4 style="text-align: left;">
Decorators in Python</h4>
<div>
As we know already everything in Python is an Object. A decorator is an object that is used to modify a function or a class. Function decorator takes a reference to the decorated function and returns a new function. It will internally call the actual decorated/referenced function.<br />
<br />
You can also have a class as a decorator instead of a function. When we decorate a method with a class, that function becomes instance method of that class.<br />
<br />
In either case the original code is not changed. </div>
<div>
<br /></div>
<div>
Let us say we have a function that makes a remote API call and we want to monitor the start and end time for that API. You have a method as follows:
<br />
<br />
<pre class="brush: java">def make_api_call(*params):
# Simulate API call
time.sleep(3)
print("Done")
</pre>
</div>
<div>
<br /></div>
<div>
<br /></div>
<div>
I have just added a sleep of 3 seconds to simulate the actual API call. So now if we want to monitor the start and end time of this API, we can modify this function to print time before and after the API call, but it is not correct to modify existing functions. This is where decorator comes into the picture.<br />
<br />
<pre class="brush: java">from datetime import datetime
import time
def monitor_performance(func):
def wrapper_func(*params):
print("Making API call with params {} at {}".format(params, datetime.now()))
func(params)
print("Finishing API call with params {} at {}".format(params, datetime.now()))
return wrapper_func
@monitor_performance
def make_api_call(*params):
# Simulate API call
time.sleep(3)
print("Done")
make_api_call("param1", "param2")
</pre>
<br />
<br />
<br />
When you execute this code it prints the following output.<br />
<b>Making API call with params ('param1', 'param2') at 2020-05-24 22:31:19.480543</b><br />
<b>Done</b><br />
<b>Finishing API call with params ('param1', 'param2') at 2020-05-24 22:31:22.484090</b><br />
<br />
<div class="separator" style="clear: both; text-align: center;">
<a href="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEgwd9U9MaGDzU6ya0A3ChiBE1YGp2YVSOMDK0IOA6hGGflwml8hCLdJub9WevM-nYWyUCFyDLf8Su0G0uUszxrigYUA5NN_oFGRQ00CoNp7zLOrBr9nw5XqvKD5X3B7JnUh8OkqLPPF4mch/s1600/decorator.png" imageanchor="1" style="margin-left: 1em; margin-right: 1em;"><img border="0" data-original-height="428" data-original-width="1096" height="248" src="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEgwd9U9MaGDzU6ya0A3ChiBE1YGp2YVSOMDK0IOA6hGGflwml8hCLdJub9WevM-nYWyUCFyDLf8Su0G0uUszxrigYUA5NN_oFGRQ00CoNp7zLOrBr9nw5XqvKD5X3B7JnUh8OkqLPPF4mch/s640/decorator.png" width="640" /></a></div>
<br />
<br />
You can notice how we decorated our actual method make_api_call with a custom decorator monitor_performance. Also, you must have noticed our decorator function used a closure - another internal method called wrapper_func to actually monitor start and end time.<br />
<br />
As I mentioned before the decorator can be used to modify the actual method and internally calls the actual method. In this case, before we call the actual method we print start and end time.<br />
<br />
You would have also noticed that the parameters passed to make_api_call are automatically passed to our wrapper function as we are returning this wrapper function from the decorator. Also, notice how we have declared decorator for our function using '@' notation.<br />
<br />
<br />
<h4 style="text-align: left;">
Using class instead of function for a decorator</h4>
<div>
<br /></div>
<div>
The same above code can be done with a class as a decorator. As we already know everything in python is an object and it is callable if it defines the __call__() method.</div>
<div>
<br /></div>
<pre class="brush: java">from datetime import datetime
import time
class monitor_performace:
def __init__(self, actual_func):
self.actual_func = actual_func
def __call__(self, *params):
print("Making API call with params {} at {}".format(params, datetime.now()))
self.actual_func(params)
print("Finishing API call with params {} at {}".format(params, datetime.now()))
@monitor_performace
def make_api_call(*params):
# Simulate API call
time.sleep(3)
print("Done")
make_api_call("param1", "param2")
</pre>
<div>
<br /></div>
<div>
<br /></div>
<div>
It prints similar output as before:<br />
<b>Making API call with params ('param1', 'param2') at 2020-05-24 22:39:22.895176</b><br />
<b>Done</b><br />
<b>Finishing API call with params ('param1', 'param2') at 2020-05-24 22:39:25.896923</b></div>
<div>
<br />
<br />
<div class="separator" style="clear: both; text-align: center;">
<a href="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEhMjGkB1mMVOxotXLTba8_MeLgPKzQcmRWTaTDNt2rvGMkoW-9oECphzMyBMpGO-nCef-45kQtDB6pWaguqFWCDvIYILgcvRsBPdysvitiae52EehYS0LPCYnJ85gvLdKPNck6OilhpN-R-/s1600/decorator-1.png" imageanchor="1" style="margin-left: 1em; margin-right: 1em;"><img border="0" data-original-height="424" data-original-width="1099" height="246" src="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEhMjGkB1mMVOxotXLTba8_MeLgPKzQcmRWTaTDNt2rvGMkoW-9oECphzMyBMpGO-nCef-45kQtDB6pWaguqFWCDvIYILgcvRsBPdysvitiae52EehYS0LPCYnJ85gvLdKPNck6OilhpN-R-/s640/decorator-1.png" width="640" /></a></div>
<br />
<br />
<br />
<b>Notes:</b><br />
<br />
<ul style="text-align: left;">
<li>You can also decorate a class with another class</li>
<li>You can chain decorated as well. Each decorated function/class will be called serially.</li>
</ul>
<br />
<br />
<br />
<h4 style="text-align: left;">
Related Links</h4>
<br />
<ul style="text-align: left;">
<li><a href="https://opensourceforgeeks.blogspot.com/2020/05/understanding-python-closure.html">Understanding python closure(OSFG)</a></li>
</ul>
<br />
<br /></div>
</div>
<div>
<br /></div>
<div>
<br /></div>
<div>
<br /></div>
<div>
<br /></div>
</div>
Aniket Thakurhttp://www.blogger.com/profile/07553743551249736583noreply@blogger.com0tag:blogger.com,1999:blog-5013829528944984059.post-25679502427903571412020-05-16T12:32:00.005-07:002020-05-16T12:32:59.606-07:00Understanding python closure<div dir="ltr" style="text-align: left;" trbidi="on">
<h4 style="text-align: left;">
Background</h4>
<div>
In the last couple of posts, we saw how we can pass multiple arguments in python functions and what are generators in python. Next, I want to explain what decorators are in python. Decorator is a very powerful feature of python but in order to explain it, we need to understand closure in Python. You must have heard of <a href="https://opensourceforgeeks.blogspot.com/2016/05/hide-variable-from-console-access.html">Javascript closures</a>, these are kind of similar. We will see this in detail now.</div>
<div>
<br /></div>
<h4 style="text-align: left;">
Understanding python closure</h4>
<div>
Python closures are related to nested functions. Consider the following example:</div>
<br />
<pre class="brush: java">def print_func(text):
text_to_print = text
def printer():
print(text_to_print)
return printer
print_function_reference = print_func("Hello World!")
print(print_function_reference)
print_function_reference()
</pre>
<div>
<br /></div>
<div>
<br /></div>
<div>
What happens when you execute the above piece of code? It prints:<br />
<b><function print_func.<locals>.printer at 0x7f21b16d1950></b><br />
<b>Hello World!</b></div>
<div>
<br />
So what's happening here?<br />
We have defined a function called <b>print_func</b> which takes in a string argument which we like to print. Then this method returns a reference new method called <b>printer</b>() and when you invoke this method(reference) you see your value is printed.<br />
<br />
But wait a second? I am good with the part where I get a reference of printer method as seen in output but when I invoke it how does it get the value of <b>text_to_print? </b>It does not seem to be in printer methods scope.<br />
>> This is exactly what we call closure.<br />
<br />
A couple of other pointers before we go to the definition of closure:<br />
<br />
<ul style="text-align: left;">
<li>printer() function is called a nested function</li>
<li>A nested function has read-only access of variables defined in the outer scope. 'text_to_print' in this case.</li>
<li>Such variables are called "<b>non-local"</b> variables.</li>
<li>Everything in python is an object with set of attributes. Yes, even a function. They all have some common attributes like <b>"__doc__"</b>.</li>
</ul>
</div>
<div>
So, Closure is a function object that is used to access variables from enclosing scope, even though they are not present in the memory(out of scope). Eg. 'text_to_print' in this case.<br />
<br />
They are used to invoke functions not in scope. Eg. printer() in above case. Scope for printer() function is inside print_func() function yet we can invoke it from outside.</div>
<div>
<br />
NOTE: You can try deleting print_func() and then invoke print_function_reference(). It will still work, even though it's closing function is deleted.<br />
<br />
<div class="separator" style="clear: both; text-align: center;">
<a href="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEgscEIz3GLEume1r4JIiIlsLW7lIZXE2WSXtqtdHSP-OqRZRWJluLj_F-wG37Eqs-ryZI0djVL_grt72sEl5EFlr8Ls5fTn6zd56KEUqrIPYvnfJ0rv-qRwhngjGWeqm5aqZUUsKgNMctur/s1600/closure_python.png" imageanchor="1" style="margin-left: 1em; margin-right: 1em;"><img border="0" data-original-height="570" data-original-width="834" height="436" src="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEgscEIz3GLEume1r4JIiIlsLW7lIZXE2WSXtqtdHSP-OqRZRWJluLj_F-wG37Eqs-ryZI0djVL_grt72sEl5EFlr8Ls5fTn6zd56KEUqrIPYvnfJ0rv-qRwhngjGWeqm5aqZUUsKgNMctur/s640/closure_python.png" width="640" /></a></div>
<br /></div>
<h4 style="text-align: left;">
When and Why to use Closures?</h4>
<div>
As you can see closure help with data hiding. You don't need to define global variables. That's exactly the primary use case of closures.<br />
<br />
They are used in callbacks and decorators. We will have a detailed post on decorators (stay tuned!).<br />
<br />
Typically when you have a few methods you can go with closure. However, if you have multiple methods you are better off with a class.</div>
<div>
<br /></div>
<div>
You can also see closure contents as follows:<br />
<br />
<div class="separator" style="clear: both; text-align: center;">
<a href="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEip2lXXGWs1JRG0T69JtkMmsPYR6c4xjka-IfEUDZKiJwwQMo2_RAWOuhy7upTH8pTvaMEkapdtVfvzfTo3VJJGbbYjztxo-2V1Rj3891NsBOFuX367ydVypZws1JqMcbipWI2mTSEJNnU9/s1600/closure-content.png" imageanchor="1" style="margin-left: 1em; margin-right: 1em;"><img border="0" data-original-height="123" data-original-width="849" height="92" src="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEip2lXXGWs1JRG0T69JtkMmsPYR6c4xjka-IfEUDZKiJwwQMo2_RAWOuhy7upTH8pTvaMEkapdtVfvzfTo3VJJGbbYjztxo-2V1Rj3891NsBOFuX367ydVypZws1JqMcbipWI2mTSEJNnU9/s640/closure-content.png" width="640" /></a></div>
<br /></div>
<div>
<br />
<br />
<h4 style="text-align: left;">
Related Links</h4>
</div>
<div>
<ul style="text-align: left;">
<li><a href="https://opensourceforgeeks.blogspot.com/2020/05/how-to-pass-variable-arguments-using.html">How to pass variable arguments using *args and **kwargs in Python?(OSFG)</a></li>
<li><a href="https://opensourceforgeeks.blogspot.com/2020/05/difference-between-yield-and-return-in.html">Difference between yield and return in python(OSFG)</a></li>
<li><a href="https://opensourceforgeeks.blogspot.com/2016/05/hide-variable-from-console-access.html">Hide variable from console access - Javascript Closures and self executing functions</a></li>
</ul>
</div>
</div>
Aniket Thakurhttp://www.blogger.com/profile/07553743551249736583noreply@blogger.com0tag:blogger.com,1999:blog-5013829528944984059.post-19358217654140180422020-05-16T11:21:00.004-07:002020-05-16T11:21:47.294-07:00How to add code Syntax highlighting to your blogger blog?<div dir="ltr" style="text-align: left;" trbidi="on">
<h4 style="text-align: left;">
Background</h4>
If you own a technical blog or a website you generally need to add code to illustrate your examples. In such cases highlighting the code becomes essential. You would have seen the code syntax highlighting in this blog itself.<br />
<br />
<div class="separator" style="clear: both; text-align: center;">
<a href="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEjMhcRIvW_OeL3ntcyjuzgLwfHdnx-yh1W4EAy2sTYi5-8nqo586s7SElB2kd2WkIg91eMY8WHBq-ieb6qDhROtN2iSAOtbZQwHFRXYkt74DjMmK7W-wLKPawGc9m_PrlWhrNSi9H9nJxhX/s1600/syntax-hughlightinh.png" imageanchor="1" style="margin-left: 1em; margin-right: 1em;"><img border="0" data-original-height="669" data-original-width="1071" height="398" src="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEjMhcRIvW_OeL3ntcyjuzgLwfHdnx-yh1W4EAy2sTYi5-8nqo586s7SElB2kd2WkIg91eMY8WHBq-ieb6qDhROtN2iSAOtbZQwHFRXYkt74DjMmK7W-wLKPawGc9m_PrlWhrNSi9H9nJxhX/s640/syntax-hughlightinh.png" width="640" /></a></div>
<br />
<br />
<br />
In this post, I will show you how you can achieve this.<br />
<br />
<br />
<h4 style="text-align: left;">
How to add code Syntax highlighting to your blogger blog?</h4>
For code syntax highlighting we will use <a href="https://github.com/syntaxhighlighter/syntaxhighlighter">SyntaxHighlighter</a>. I will specifically tell you how to add this to your blogger blog.<br />
<br />
<br />
<ul style="text-align: left;">
<li>Open your blogger blog dashboard</li>
<li>Go to Theme</li>
<li>Click on 3 dots beside "My theme" and click on "Edit HTML"</li>
</ul>
<br />
<br />
<div class="separator" style="clear: both; text-align: center;">
<a href="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEg4i6bLhTMidn00f41wmgP9_yKgaoklT3lzC7prj8OCA-ryCOwbFlXjy4uNU2CoW5MHJqUSnK4DvB3Y2aSwX9FJ7KOTOz0WxrFaIsFJF1ENXTz_cxA9REQGzNeR-lZKV_BK2R7qZ-UeBTRn/s1600/Selection_002.png" imageanchor="1" style="margin-left: 1em; margin-right: 1em;"><img border="0" data-original-height="715" data-original-width="1227" height="372" src="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEg4i6bLhTMidn00f41wmgP9_yKgaoklT3lzC7prj8OCA-ryCOwbFlXjy4uNU2CoW5MHJqUSnK4DvB3Y2aSwX9FJ7KOTOz0WxrFaIsFJF1ENXTz_cxA9REQGzNeR-lZKV_BK2R7qZ-UeBTRn/s640/Selection_002.png" width="640" /></a></div>
<br />
<br />
<div class="separator" style="clear: both; text-align: center;">
<a href="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEhx1hqRssyeTuo3IocGqtILQC7mmz-T6PoNjDQadAgYgMMVoTEXtbHVJ5OM4QSMBKjpqZCKsVFclv_kA1tri-4XwQayfkKptiGmYEp4CW9S-mX6rfHfdmc5Xv21VWz6h0w0C1bZtsZXu23Q/s1600/Selection_003.png" imageanchor="1" style="margin-left: 1em; margin-right: 1em;"><img border="0" data-original-height="469" data-original-width="1159" height="258" src="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEhx1hqRssyeTuo3IocGqtILQC7mmz-T6PoNjDQadAgYgMMVoTEXtbHVJ5OM4QSMBKjpqZCKsVFclv_kA1tri-4XwQayfkKptiGmYEp4CW9S-mX6rfHfdmc5Xv21VWz6h0w0C1bZtsZXu23Q/s640/Selection_003.png" width="640" /></a></div>
<br />
<br />
<br />
<br />
<ul>
<li>In the panel which opens and shows some HTML code search and go to the line with </head> tag. This is where your head tag ends. We need to add some include CSS and js files here along with some custom javascript.</li>
<li>Inside the head tag (Just before </head> add following code)
<br /><br /><pre class="brush: java"><!-- Syntax Highlighter START -->
<link href="http://alexgorbatchev.com/pub/sh/current/styles/shCore.css" rel="stylesheet" type="text/css"></link>
<link href="http://alexgorbatchev.com/pub/sh/current/styles/shThemeDefault.css" rel="stylesheet" type="text/css"></link>
<script src="http://alexgorbatchev.com/pub/sh/current/scripts/shCore.js" type="text/javascript">
<script src='http://alexgorbatchev.com/pub/sh/current/scripts/shBrushAS3.js' type='text/javascript'/>
<script src='http://alexgorbatchev.com/pub/sh/current/scripts/shBrushBash.js' type='text/javascript'/>
<script src='http://alexgorbatchev.com/pub/sh/current/scripts/shBrushColdFusion.js' type='text/javascript'/>
<script src='http://alexgorbatchev.com/pub/sh/current/scripts/shBrushCSharp.js' type='text/javascript'/>
<script src='http://alexgorbatchev.com/pub/sh/current/scripts/shBrushCpp.js' type='text/javascript'/>
<script src='http://alexgorbatchev.com/pub/sh/current/scripts/shBrushCss.js' type='text/javascript'/>
<script src='http://alexgorbatchev.com/pub/sh/current/scripts/shBrushDelphi.js' type='text/javascript'/>
<script src='http://alexgorbatchev.com/pub/sh/current/scripts/shBrushDiff.js' type='text/javascript'/>
<script src='http://alexgorbatchev.com/pub/sh/current/scripts/shBrushErlang.js' type='text/javascript'/>
<script src='http://alexgorbatchev.com/pub/sh/current/scripts/shBrushGroovy.js' type='text/javascript'/>
<script src='http://alexgorbatchev.com/pub/sh/current/scripts/shBrushJScript.js' type='text/javascript'/>
<script src='http://alexgorbatchev.com/pub/sh/current/scripts/shBrushJava.js' type='text/javascript'/>
<script src='http://alexgorbatchev.com/pub/sh/current/scripts/shBrushJavaFX.js' type='text/javascript'/>
<script src='http://alexgorbatchev.com/pub/sh/current/scripts/shBrushPerl.js' type='text/javascript'/>
<script src='http://alexgorbatchev.com/pub/sh/current/scripts/shBrushPhp.js' type='text/javascript'/>
<script src='http://alexgorbatchev.com/pub/sh/current/scripts/shBrushPlain.js' type='text/javascript'/>
<script src='http://alexgorbatchev.com/pub/sh/current/scripts/shBrushPowerShell.js' type='text/javascript'/>
<script src='http://alexgorbatchev.com/pub/sh/current/scripts/shBrushPython.js' type='text/javascript'/>
<script src='http://alexgorbatchev.com/pub/sh/current/scripts/shBrushRuby.js' type='text/javascript'/>
<script src='http://alexgorbatchev.com/pub/sh/current/scripts/shBrushScala.js' type='text/javascript'/>
<script src='http://alexgorbatchev.com/pub/sh/current/scripts/shBrushSql.js' type='text/javascript'/>
<script src='http://alexgorbatchev.com/pub/sh/current/scripts/shBrushVb.js' type='text/javascript'/>
<script src='http://alexgorbatchev.com/pub/sh/current/scripts/shBrushXml.js' type='text/javascript'/>
<script language='javascript' type='text/javascript'>
SyntaxHighlighter.config.bloggerMode = true;
SyntaxHighlighter.all();
</script>
</pre>
<br />
</li>
<li>Once done save the file and reload blog.</li>
</ul>
<div class="separator" style="clear: both; text-align: center;">
<a href="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEha_YSjZz78HcqoVfksBYkXMfM6c6xr1L2q5WqgqwWwXsJJ0qUVhxbhsLsmcS1H9OqD1sPLkrYoVHHvCntqEwK8O5UiSmVf8GR1QzHVF0seWVY37hUmDGTTembH-apIm2L0JFQdYl7EEt1M/s1600/Selection_004.png" imageanchor="1" style="margin-left: 1em; margin-right: 1em;"><img border="0" data-original-height="256" data-original-width="1600" height="102" src="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEha_YSjZz78HcqoVfksBYkXMfM6c6xr1L2q5WqgqwWwXsJJ0qUVhxbhsLsmcS1H9OqD1sPLkrYoVHHvCntqEwK8O5UiSmVf8GR1QzHVF0seWVY37hUmDGTTembH-apIm2L0JFQdYl7EEt1M/s640/Selection_004.png" width="640" /></a></div>
<div>
<br /></div>
<br />
<ul style="text-align: left;">
<li>Now if you want any highlighting you can use the corresponding class in <pre> tag. Eg for Java you can do
<br /><pre class="brush: java"><pre class="brush:java">This will be highlighted</pre></pre>
</li>
<li>Instead of Java you can have other languages as well. Choices are: <b>cpp, c, c++, c#, c-sharp, csharp, css, delphi, pascal, java, js, jscript, javascript, php, py, python, rb, ruby, rails, ror, sql, vb, vb.net, xml, html, xhtml, xslt</b>. You can see the latest list of <a href="https://code.google.com/archive/p/syntaxhighlighter/wikis/Languages.wiki">supported languages</a>.</li>
<li>You can only add js files for brushes you need (See optimization below)</li>
</ul>
<h4 style="text-align: left;">
Optimizations</h4>
This is the good part! We would not call ourselves programmers if we did not have an optimization part :)<br />
<br />
<br />
<ul style="text-align: left;">
<li>You can see above there are a bunch of js files added in the head tag. You might not need all and each page load with load these external JS code which can slow loading if your blog. So Add only those JS files which you need. In fact, if you see the screenshot above I have used just the Java brush JS. I just use the same for all types of codes. <br /><br />
<div class="separator" style="clear: both; text-align: center;">
<a href="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEhuBFRKgrOcFKpydG-YIRN6oQz9eyjBe7l22eUs6BAeLHDNXqAbnJ98S_c31l53P8be0RkZLx-F2hWkHbx07sUKbIqdc2YHSVrH2WLaQ1xm1Z806uw_cYXx3qeMxtb7LurmCTvTn4Dm-lsw/s1600/syntax-highlight-code.png" imageanchor="1" style="margin-left: 1em; margin-right: 1em;"><img border="0" data-original-height="164" data-original-width="1058" height="98" src="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEhuBFRKgrOcFKpydG-YIRN6oQz9eyjBe7l22eUs6BAeLHDNXqAbnJ98S_c31l53P8be0RkZLx-F2hWkHbx07sUKbIqdc2YHSVrH2WLaQ1xm1Z806uw_cYXx3qeMxtb7LurmCTvTn4Dm-lsw/s640/syntax-highlight-code.png" width="640" /></a></div>
<br />
</li>
<li>If you do not want the code highlighting to work for your homepage (Just for the the posts you write), you can add all above code inside the following tags: <br /><br />
<pre class="brush: java"><b:if cond='data:blog.pageType == "item"'>
</b:if>
</pre>
</li>
<li>Lastly, you would have also noticed the link base path for JS and CSS files are different in my code that what I originally provided. That's because I have used the CDN path(<a href="https://cdnjs.com/libraries/SyntaxHighlighter">https://cdnjs.com/libraries/SyntaxHighlighter</a>). This is done primarily for 2 things:</li>
<ul>
<li>First, it allows highlighting to work even on https. By default with the above code loading your blog site with https protocol will not show highlighting. That's because your include scripts are HTTP and not supported for https.</li>
<li>Secondly, if the HTTP links are down you are screwed. CDN caches the scripts and cs files. So you can always rely on it (rely is is a strong word but it's better than those HTTP links :) )</li>
</ul>
</ul>
<br />
<h4 style="text-align: left;">
Configuration<br /></h4>
<br />
<ul style="text-align: left;">
<li>Another thing you might have noticed is the change of theme file I have used. The original set of code I proposed uses a default theme <b>shThemeDefault.css</b> but I have changed this to use <b>shThemeEmacs.css. </b>You can use whichever theme you like - Just include the corresponding theme CSS file (and remove the default one). Some of the available themes are: <b>shThemeRDark, shThemeMidnight, shThemeMDUltra, shThemeFadeToGrey, shThemeEmacs, shThemeEclipse, shThemeDjango, shThemeDefault, shCoreRDark, shCoreMidnight, shCoreMDUltra, shCoreFadeToGrey, shCoreEmacs, shCoreEclipse, shCoreDjango, shCoreDefault</b></li>
</ul>
<br />
<br />
<br />
<ul style="text-align: left;">
<li>I already mentioned you should only include and use the JS files corresponding to language brushed you intent to use. This will reduce your page load time. You can also use the "<b>b:if" </b>tag I mentioned above so that these scripts load for your blog posts.</li>
</ul>
<br />
You can already see this blog using all of these customizations. Feel free to comment if you need any help. Thanks.<br />
<br />
<h4 style="text-align: left;">
Related Links</h4>
<div>
<ul style="text-align: left;">
<li><a href="https://github.com/syntaxhighlighter/syntaxhighlighter">SyntaxHighlighter(Github)</a></li>
<li><a href="https://code.google.com/archive/p/syntaxhighlighter/wikis/Languages.wiki">Supported languages</a></li>
</ul>
</div>
<br />
<br /></div>
Aniket Thakurhttp://www.blogger.com/profile/07553743551249736583noreply@blogger.com0tag:blogger.com,1999:blog-5013829528944984059.post-80196027172913349872020-05-10T08:18:00.002-07:002020-05-10T08:18:57.851-07:00Difference between yield and return in python<div dir="ltr" style="text-align: left;" trbidi="on">
<h4 style="text-align: left;">
Background</h4>
<div>
If you have been using Python you would have come across return and yield statements. Both are used to return something from a function. Though both of them are used to return something from the function both serve different purposes. In this post, I will try to explain what those are.</div>
<div>
<br />
I use Jupyter notebook for running python code snippets. To see how you can install it refer to my earlier post (link in the Related Sections at the end of this post).</div>
<h4 style="text-align: left;">
Understanding return in Python</h4>
<div>
Let's try to understand returns first as that's the simplest. The return keyword is used is a similar fashion in multiple programming languages. It is used to return a value to its caller.</div>
<div>
<br /></div>
<div>
A function can have multiple return statements but only the 1st one encountered during its execution flow will be executed and the corresponding value will be returned to the called. No code after the return statement will be executed (dead code) - the method with return statement exists. The return statement is generally the last statement in a function but it could be before as well if we want to skip subsequent code based on a certain condition. </div>
<div>
<br /></div>
<div>
Consider the following example:<br />
<br /></div>
<pre class="brush: java">def is_even(num):
if num is None:
return False
elif num%2 == 0:
return True
else:
return False
print(is_even(2))
print(is_even(3))
print(is_even(None))
</pre>
<div>
<br /></div>
<div>
The output is:<br />
<b>True</b><br />
<b>False</b><br />
<b>False</b></div>
<div>
<br />
<br />
As you can see the function is_even has multiple return statements and exactly one will get executed for a single execution call based on the conditions. You could also rewrite it as :<br />
<br />
<pre class="brush: java">def is_even(num):
is_even=True
if num is None or num%2 != 0:
is_even = False
return is_even
print(is_even(2))
print(is_even(3))
print(is_even(None))
</pre>
<br />
<br />
This is a slightly better version than the previous one. we just have one return statement and less code.<br />
<br />
<br />
<h4 style="text-align: left;">
Understanding yield in Python</h4>
<br />
Yield statement also returns the value to the caller but it retains the state. When you call the function again it resumes where it left off (last yield statement). This enabled code to generate a series of data when needed without generating all at once.<br />
<br />
Such structures that generate a series of data are called generators in python and yield keywords are used to create generators. Whenever generators need to produce a value they do it using the yield keyword. Consider the following example:<br />
<pre class="brush: java">def get_even():
i=0
while True:
i = i + 2
yield i
test = get_even()
print(next(test))
print(next(test))
print(next(test))
</pre>
<br />
<br />
This outputs:<br />
<b>2</b><br />
<b>4</b><br />
<b>6</b><br />
<br />
As you can see this is a forever going generator. It will keep on generating the sequence. If you do something like below, it will go in an infinite loop:<br />
<br />
<pre class="brush: java">def get_even():
i=0
while True:
i = i + 2
yield i
test = get_even()
for evennum in test:
print(evennum)
</pre>
<br />
<br />
This outputs an infinite series of even numbers starting from 2. You will have to manually kill the process as it goes into an infinite loop.<br />
<br />
If there are limited field statements in the function, the generator will run that many times. If you try to run a generator after that it will raise an Exception.<br />
<br />
<pre class="brush: java">def get_even():
i=0
i = i + 2
yield i
i = i + 2
yield i
test = get_even()
for evennum in test:
print(evennum)
next(test)
</pre>
<br />
<br />
Output:<br />
<b>2</b><br />
<b>4</b><br />
<b>---------------------------------------------------------------------------</b><br />
<b>StopIteration Traceback (most recent call last)</b><br />
<b><ipython-input-40-ef2477e0fee5> in <module></b><br />
<b> 10 for evennum in test:</b><br />
<b> 11 print(evennum)</b><br />
<b>---> 12 next(test)</b><br />
<b><br /></b>
<b>StopIteration: </b><br />
<br />
You can have return statements in a generator as well which simply signifies the end of that generator. No yield statement after the return statement will be respected. Consider the following example:<br />
<pre class="brush: java">def get_even():
i=0
i = i + 2
yield i
return
i = i + 2
yield i
test = get_even()
for evennum in test:
print(evennum)
next(test)
</pre>
<br />
<br />
This will print:<br />
<br />
<b>2</b><br />
<b>---------------------------------------------------------------------------</b><br />
<b>StopIteration Traceback (most recent call last)</b><br />
<b><ipython-input-41-554cedfc9db7> in <module></b><br />
<b> 11 for evennum in test:</b><br />
<b> 12 print(evennum)</b><br />
<b>---> 13 next(test)</b><br />
<b><br /></b>
<b>StopIteration: </b><br />
<br />
<br />
As you can see it encountered 1st yield and returned back 2. In the next call, it saw a return statement and terminated the generator. So, calling it again is going to raise an Exception as we saw above. Having return and yield statement was not allowed in python2 but it's allowed in python3 and it simply means the end of the generator.<br />
<br />
<div class="separator" style="clear: both; text-align: center;">
<a href="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEjVrkQ6iy_fyVtn2KRxXfAmqqzolgkJYpfKitmGYl66o1EWNMcGMZNP56Sgp7Qia_YsyUpZZz44KFMcOZT1_1NvPqWPWOMUqk1NpP0du_1PvnC5sfk8Io8ESF4qfqFu1YJn9of2W1eLYv-R/s1600/yield.png" imageanchor="1" style="margin-left: 1em; margin-right: 1em;"><img border="0" data-original-height="333" data-original-width="700" height="304" src="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEjVrkQ6iy_fyVtn2KRxXfAmqqzolgkJYpfKitmGYl66o1EWNMcGMZNP56Sgp7Qia_YsyUpZZz44KFMcOZT1_1NvPqWPWOMUqk1NpP0du_1PvnC5sfk8Io8ESF4qfqFu1YJn9of2W1eLYv-R/s640/yield.png" width="640" /></a></div>
<br />
<h4 style="text-align: left;">
Summarizing the difference</h4>
<div>
<ul style="text-align: left;">
<li>Return statements terminate the execution of the method and return the value to the caller whereas yield returns the value to the caller but retains the current state so that the same method can be called again. </li>
<li>The yield keyword is used in Python generators. A generator is a special function that returns a generator object to the caller instead of the actual value. </li>
<li>Generators save memory as the new value is generated only when the generator is called. If the same thing you had to do with the return, you would need to compute the series, store all in an array and return the array once.</li>
<li>As generators with the yield keyword resume the execution all local variables are retained whereas in case of return they are destroyed.</li>
</ul>
</div>
<br />
<br />
<h4 style="text-align: left;">
Related Links</h4>
<div>
<ul style="text-align: left;">
<li><a href="http://opensourceforgeeks.blogspot.com/2020/05/how-to-install-ipython-jupyter-notebook.html">How to Install IPython Jupyter Notebook on Ubuntu(OSFG)</a></li>
<li><a href="http://opensourceforgeeks.blogspot.com/2020/05/how-to-pass-variable-arguments-using.html">How to pass variable arguments using *args and **kwargs in Python?(OSFG)</a></li>
</ul>
</div>
<br /></div>
<div>
<br /></div>
</div>
Aniket Thakurhttp://www.blogger.com/profile/07553743551249736583noreply@blogger.com0tag:blogger.com,1999:blog-5013829528944984059.post-32854514556074887212020-05-03T06:40:00.001-07:002020-05-03T06:54:27.761-07:00How to pass variable arguments using *args and **kwargs in Python?<div dir="ltr" style="text-align: left;" trbidi="on">
<h4 style="text-align: left;">
Background</h4>
<div>
If you are working with python you must have come across following notations:</div>
<div>
<ul style="text-align: left;">
<li>*args</li>
<li>**kwargs</li>
</ul>
<div>
args and kwargs are just argument names. It can be replaced by any other variable name, but the important part is the syntax and how it is used. If you have come across this you would also know they are used to pass the variable number of arguments. In this post, I will try to explain how they work with some examples.</div>
</div>
<div>
<br /></div>
<div>
<b>Note</b>: If you have not installed Jupyter notebook for python, please refer to my earlier blog post: <a href="http://opensourceforgeeks.blogspot.com/2020/05/how-to-install-ipython-jupyter-notebook.html">How to Install IPython Jupyter Notebook on Ubuntu</a></div>
<div>
<br /></div>
<h4 style="text-align: left;">
How to pass variable arguments using *args and **kwargs in Python?</h4>
<div>
<br /></div>
<div>
Let's take cases of *args and **kwargs one at a time and then we will see some combined examples.<br />
<br />
<h4 style="text-align: left;">
Understanding *args</h4>
</div>
<div>
<ul style="text-align: left;">
<li><b>*args is used to take a variable number of non-keyworded arguments that are not your formal arguments. </b></li>
<li><b>arguments passed in *args become iterable. Think of this as a list.</b></li>
</ul>
<div>
We will understand "non-keyworded" meaning better when we go to **kwargs but for now, let's try to focus on *args.</div>
</div>
<div>
<br /></div>
<div>
Consider the following example:</div>
<div>
<br /></div>
<div>
<br /></div>
<pre class="brush:java">def foo(param1, *param2):
print("In foo:")
print(param1)
print(param2)
</pre>
<div>
<br /></div>
<div>
<br /></div>
<div>
And now if you pass:</div>
<div>
foo(1,2,3,4)</div>
<div>
<br /></div>
<div>
You will get the output:</div>
<div>
<b>In foo:
1
(2, 3, 4)</b>
</div>
<div>
<br /></div>
<div>
As you can see argument 1 got mapped to param1 (your formal argument) and the rest for mapped to *param2 (*param2 is your *args. As I mentioned before variable name does not matter). </div>
<div>
<br /></div>
<div>
You can pass any number of params after 1 and they will be part of param2.</div>
<div>
<br /></div>
<div>
You can even iterate over param2 to print all variables.</div>
<div>
<br /></div>
<pre class="brush:java">def foo(param1, *param2):
print("In foo:")
print(param1)
for no in param2:
print(no)
</pre>
<div>
<br /></div>
<div>
<b>Output:</b></div>
<div>
<div>
In foo:</div>
<div>
1</div>
<div>
2</div>
<div>
3</div>
<div>
4</div>
</div>
<div>
<br />
<h4>
Understanding *kwargs</h4>
<ul style="text-align: left;">
<li><b>*kwargs is used to take a variable number of keyworded arguments that are not your formal arguments. When I say keyword it means that you pass arguments by providing a name to that variable</b></li>
<li>Think of this as a dictionary of variable name and value you passed as arguments to the function.</li>
</ul>
Consider the following example:<br />
<br />
<pre class="brush:java">def bar(param1, **param2):
print("In bar:")
print(param1)
print(param2)
</pre>
<br />
And if you pass bar(1,a=2,b=3,c=4) it will <b>output</b><br />
<b>In bar:</b><br />
<b>1</b><br />
<b>{'a': 2, 'b': 3, 'c': 4}</b><br />
<br />
1 which is your formal parameter maps to param1 and rest named parameters go as dict in param2.<br />
Obviously, you cannot pass bar(1, 2, 3, a=2,b=3,c=4)<br />
as it does not know what to do with 2,3,4<br />
<br />
<br />
Hopefully, now you understand what keyworded arguments are. They are basically named parameters passed in the function call.<br />
<br />
You can also iterate it as a dictionary<br />
<br />
<pre class="brush:java">def bar(param1, **param2):
print("In bar:")
print(param1)
for key, value in param2.items():
print("{}:{}".format(key,value))
</pre>
<br />
<br />
<br />
<b>Output:</b><br />
In bar:<br />
1<br />
a:2<br />
b:3<br />
c:4<br />
<br />
Your functions would actually have both *args and **kwargs. So let's try to see a combined example<br />
<br />
<pre class="brush:java">def foobar(param0, *param1, **param2):
print("In foobar:")
print(param0)
print(param1)
print(param2)
</pre>
<br />
<br />
And now if you call this as foobar(1,2,3,4,a=1)<br />
you will get the following output:<br />
In foobar:<br />
1<br />
(2, 3, 4)<br />
{'a': 1}<br />
<br />
Again 1 is your formal parameter and maps to param0<br />
2,3,4 are your non-keyword params that get mapped to param1<br />
and a=1 is your keyword param that gets mapped to param2<br />
<br />
<br />
<br />
<ul style="text-align: left;">
<li>Note the order is important. *args should always come before **kwargs. </li>
<li>Also, there cannot be positional arguments after **kwargs</li>
<li>Also, you cannot do something like foobar(1,2,3,4,a=1,5) as it will not know how to map 5.</li>
</ul>
<br />
<br />
<div class="separator" style="clear: both; text-align: center;">
<a href="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEjJi3Kaw4rvaIU9skAt5Fq6rkJLfGfKRpuKAixlunfTShhZljqFeymladPkbngCVSWbFo8rqUzlPyUpt9rNIZ3HwaYhhSTEUx6wPkVHVcYQ0f4fT7LcZsBkyIOsld42sXWJfFLrcL5xDx4o/s1600/argsnkwargs.png" imageanchor="1" style="margin-left: 1em; margin-right: 1em;"><img border="0" data-original-height="643" data-original-width="1086" height="378" src="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEjJi3Kaw4rvaIU9skAt5Fq6rkJLfGfKRpuKAixlunfTShhZljqFeymladPkbngCVSWbFo8rqUzlPyUpt9rNIZ3HwaYhhSTEUx6wPkVHVcYQ0f4fT7LcZsBkyIOsld42sXWJfFLrcL5xDx4o/s640/argsnkwargs.png" width="640" /></a></div>
<br />
<br />
Hopefully, this clarifies differences between *args and **kwargs. You can play around more in the Jupyter notebook or python terminal if you have installed it (See the link below if you haven't)<br />
<br />
<br />
<br /></div>
<h4 style="text-align: left;">
Related Links</h4>
<div>
<ul style="text-align: left;">
<li><a href="http://opensourceforgeeks.blogspot.com/2020/05/how-to-install-ipython-jupyter-notebook.html">How to Install IPython Jupyter Notebook on Ubuntu(OSFG)</a></li>
</ul>
</div>
</div>
Aniket Thakurhttp://www.blogger.com/profile/07553743551249736583noreply@blogger.com0tag:blogger.com,1999:blog-5013829528944984059.post-23479044921791016912020-05-02T02:07:00.000-07:002020-05-02T02:07:05.738-07:00How to Install IPython Jupyter Notebook on Ubuntu<div dir="ltr" style="text-align: left;" trbidi="on">
<h4 style="text-align: left;">
Background</h4>
<div>
Jupyter Notebook is an open-source and interactive web app that allows you to create and share documents that contain live code, equations, visualizations, and narrative text. We will use this to run python code but it can be used with other languages as well.</div>
<div>
<br /></div>
<h4 style="text-align: left;">
Prerequisites</h4>
<div>
Firstly make sure you have the following applications installed before installing Jupyter notebook:</div>
<div>
<ul style="text-align: left;">
<li><b>python3</b></li>
<li><b>python3-pip</b></li>
</ul>
<div>
You can install these from default Ubuntu repositories by running the following commands:</div>
</div>
<div>
<ul style="text-align: left;">
<li><b>sudo apt-get install python3</b></li>
<li><b>sudo apt-get install python3-pip</b></li>
</ul>
</div>
<div>
You can check that the versions are correct with -V option as shown in the screenshot below:</div>
<div>
<br /></div>
<div class="separator" style="clear: both; text-align: center;">
<a href="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEisZYWVyi3GZuxVeAie2eYvnZY-P7wHlR7d-XJMh__kNTkhAj_R_nL_lzmGDOBLYE2Wn-bthMAqtQEpYhy-a9AVcLAygz-pVfzp3eKfR0zAUwGTlz6PKJiMhLNtHP8L04I4HF87KP8i-q45/s1600/python-pip-version.png" imageanchor="1" style="margin-left: 1em; margin-right: 1em;"><img border="0" data-original-height="320" data-original-width="724" height="282" src="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEisZYWVyi3GZuxVeAie2eYvnZY-P7wHlR7d-XJMh__kNTkhAj_R_nL_lzmGDOBLYE2Wn-bthMAqtQEpYhy-a9AVcLAygz-pVfzp3eKfR0zAUwGTlz6PKJiMhLNtHP8L04I4HF87KP8i-q45/s640/python-pip-version.png" width="640" /></a></div>
<div>
<br /></div>
<div>
<br /></div>
<div>
<h4>
How to Install IPython Jupyter Notebook on Ubuntu</h4>
</div>
<div>
Now that dependencies are in place, let's install Jupyter notebook.</div>
<div>
<br /></div>
<div>
Install python and jupyter</div>
<div>
<ul style="text-align: left;">
<li><b>pip3 install ipython</b></li>
<li><b>pip3 install jupyter</b></li>
</ul>
</div>
<div>
IPython (Interactive Python) is a command shell for interactive computing in multiple programming languages, originally developed for the Python programming language, that offers introspection, rich media, shell syntax, tab completion, and history (<a href="https://en.wikipedia.org/wiki/IPython">Wiki</a>).</div>
<div>
<br /></div>
<div>
<br /></div>
<div class="separator" style="clear: both; text-align: center;">
<a href="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEgoANzqA10QAzXV2P9VCnv2TVWSJxZ82pIDcYtFFzlEdtCe_DBCERIohyUCIjFAkX0LTp-230vIF02EElkrho9kZKiGlFrjwtII5QZeIGsJ6zpGTrjqM7KSlqumBk72IWdjAFvJPsozsZEw/s1600/python-pip-version.png" imageanchor="1" style="margin-left: 1em; margin-right: 1em;"><img border="0" data-original-height="320" data-original-width="724" height="282" src="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEgoANzqA10QAzXV2P9VCnv2TVWSJxZ82pIDcYtFFzlEdtCe_DBCERIohyUCIjFAkX0LTp-230vIF02EElkrho9kZKiGlFrjwtII5QZeIGsJ6zpGTrjqM7KSlqumBk72IWdjAFvJPsozsZEw/s640/python-pip-version.png" width="640" /></a></div>
<div>
<br /></div>
<div>
<br /></div>
<div>
You can then start the jupyter notebook with the following command:</div>
<div>
<ul style="text-align: left;">
<li><b>jupyter notebook</b></li>
</ul>
<div class="separator" style="clear: both; text-align: center;">
<a href="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEimUFGdun76tdmgI7rXOvUN5P_rV8ZPAatkSEgGl5JaUZdJmoY5W-3ECjvi30yDhqIMvFUgjEn2OXp8stn8H262ZcZze1x7k4a9uqXG_aQaN3JspLJXBG3LZSHwacz9hjPtkoECrMafshRC/s1600/jupyter-notebook.png" imageanchor="1" style="margin-left: 1em; margin-right: 1em;"><img border="0" data-original-height="628" data-original-width="914" height="438" src="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEimUFGdun76tdmgI7rXOvUN5P_rV8ZPAatkSEgGl5JaUZdJmoY5W-3ECjvi30yDhqIMvFUgjEn2OXp8stn8H262ZcZze1x7k4a9uqXG_aQaN3JspLJXBG3LZSHwacz9hjPtkoECrMafshRC/s640/jupyter-notebook.png" width="640" /></a></div>
<div>
<br /></div>
</div>
<div>
<br /></div>
<div>
It should automatically open a browser window for you, if not you can fo to the URL from the command output, in my case:</div>
<div>
<br /></div>
<div>
<ul style="text-align: left;">
<li>http://127.0.0.1:8888/?token=f279cc86b6219e3312d623377a247ed4a686e140fac30153</li>
</ul>
</div>
<div>
Then you can create a new notebook with python3 kernel and write your code there.</div>
<div>
<br /></div>
<div>
<br /></div>
<div class="separator" style="clear: both; text-align: center;">
<a href="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEjcdH9Wr-Ctf6f6o1QzsZ-NVPFh1sI-BYFcn-8RvP40JgTf536GWkWhLLWb6k4wePMXSsmKTUe5bNu75-iv_ZLD6cF6Ps9CC98QS8WK6FHLHQtxiSZwE7ypC7E80bcjfpTFwOveIJwztMsB/s1600/new-notebook.png" imageanchor="1" style="margin-left: 1em; margin-right: 1em;"><img border="0" data-original-height="905" data-original-width="1600" height="360" src="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEjcdH9Wr-Ctf6f6o1QzsZ-NVPFh1sI-BYFcn-8RvP40JgTf536GWkWhLLWb6k4wePMXSsmKTUe5bNu75-iv_ZLD6cF6Ps9CC98QS8WK6FHLHQtxiSZwE7ypC7E80bcjfpTFwOveIJwztMsB/s640/new-notebook.png" width="640" /></a></div>
<br />
<div class="separator" style="clear: both; text-align: center;">
<a href="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEgPTF3ms_VMHXczS9rKeT8zvLN5VnfqDMZJmqGVXBlYdKwES0TuyH8n8_T90S3K2x29WURfXyveP71evfVhHZ1u2wvi8ZqoERfZey2OKpVOwhWzwhA7f8isXOtEWQqjUq6kilmK2oSd5gSm/s1600/python-notebook-cell.png" imageanchor="1" style="margin-left: 1em; margin-right: 1em;"><img border="0" data-original-height="422" data-original-width="1576" height="170" src="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEgPTF3ms_VMHXczS9rKeT8zvLN5VnfqDMZJmqGVXBlYdKwES0TuyH8n8_T90S3K2x29WURfXyveP71evfVhHZ1u2wvi8ZqoERfZey2OKpVOwhWzwhA7f8isXOtEWQqjUq6kilmK2oSd5gSm/s640/python-notebook-cell.png" width="640" /></a></div>
<div>
<br /></div>
<div>
<br /></div>
<div>
Let me know in the comments if you face any issues.</div>
<div>
We will do some more fun stuff and learn more about python. So stay tuned!</div>
<h4 style="text-align: left;">
Related Links</h4>
<div>
<ul style="text-align: left;">
<li><a href="https://opensourceforgeeks.blogspot.com/2015/10/how-python-works.html">How Python works?(OSFG)</a></li>
</ul>
</div>
</div>
Aniket Thakurhttp://www.blogger.com/profile/07553743551249736583noreply@blogger.com0tag:blogger.com,1999:blog-5013829528944984059.post-84941356848985380152020-05-01T01:56:00.002-07:002020-05-01T01:56:45.910-07:00How to fix Ubuntu update error âwaiting for unattended-upgr to exitâ<div dir="ltr" style="text-align: left;" trbidi="on">
<h4 style="text-align: left;">
Background</h4>
<div>
So I logged into my Ubuntu machine after a long time and I decided to update my installed software to the latest versions. But I see following screen and the update is stuck: <b>âwaiting for unattended-upgr to exitâ</b></div>
<div>
<br /></div>
<div class="separator" style="clear: both; text-align: center;">
<a href="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEjEpVubeM1NzW5kAJNhlarOEysdOFz8KAOYVA_g_I9Dj39TfKiLPeOunp1bP3cEzQUd8yxJ8eeubRgKFN64qBpg8eJkVFnmW5RDIilm9CQLo0SxZvBLwANjqm8nVntET9S-HVu33AhtdTdr/s1600/update-waiting-error.png" imageanchor="1" style="margin-left: 1em; margin-right: 1em;"><img border="0" data-original-height="325" data-original-width="874" height="236" src="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEjEpVubeM1NzW5kAJNhlarOEysdOFz8KAOYVA_g_I9Dj39TfKiLPeOunp1bP3cEzQUd8yxJ8eeubRgKFN64qBpg8eJkVFnmW5RDIilm9CQLo0SxZvBLwANjqm8nVntET9S-HVu33AhtdTdr/s640/update-waiting-error.png" width="640" /></a></div>
<div>
<br /></div>
<div>
<br /></div>
<div>
In this post, I will show you how to fix this issue.</div>
<div>
<br /></div>
<div>
<br /></div>
<div>
<h4 style="text-align: left;">
Fixing âwaiting for unattended-upgr to exitâ issue</h4>
</div>
<div>
<br /></div>
<div>
To begin, make sure all packages are in a clean state and correctly installed For this you can run:</div>
<div>
<ul style="text-align: left;">
<li><b>sudo dpkg --configure -a</b></li>
</ul>
<div>
However, this fails for me with the following error</div>
</div>
<div>
<br /></div>
<div class="separator" style="clear: both; text-align: center;">
<a href="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEjxd1kqh3KnlpG_1Sb7pCVIJEImy0CgOfwzn-UDWcNTKtF98PaOV6GJVKHdlISzdDeGfQ_6v1OngVUM4z6u1ERy5PpkS74NxKO44yVAMR6KyZl-NTeInN8wWOjDfuOMpLieFQgg5HDilYdq/s1600/dpkg+configure.png" imageanchor="1" style="margin-left: 1em; margin-right: 1em;"><img border="0" data-original-height="232" data-original-width="674" height="219" src="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEjxd1kqh3KnlpG_1Sb7pCVIJEImy0CgOfwzn-UDWcNTKtF98PaOV6GJVKHdlISzdDeGfQ_6v1OngVUM4z6u1ERy5PpkS74NxKO44yVAMR6KyZl-NTeInN8wWOjDfuOMpLieFQgg5HDilYdq/s640/dpkg+configure.png" width="640" /></a></div>
<div>
<br /></div>
<div>
<br /></div>
<div>
In fact, "<b>sudo apt-get upgrade"</b> also fails for me:</div>
<div>
<br /></div>
<pre class="brush: java">athakur:~$ sudo apt-get upgrade
E: Could not get lock /var/lib/dpkg/lock-frontend - open (11: Resource temporarily unavailable)
E: Unable to acquire the dpkg frontend lock (/var/lib/dpkg/lock-frontend), is another process using it?
</pre>
<div>
<br /></div>
<div>
<br /></div>
<div>
This could be due to multiple causes. Most probably some other internal update is running and using the lock. You can check this with the following commands:<br />
<br />
<br />
<ul style="text-align: left;">
<li><b>ps -eaf | grep -i apt</b></li>
<li><b>lsof /var/lib/dpkg/lock-frontend </b></li>
</ul>
<br />
<b>Note:</b> If you see a process like<b> "apt.systemd.daily"</b> using the lock, <b>please wait for a few mins</b>. This is auto-scheduler that updates your system. If you do not want this behavior you can go to "Software and Updates" and disable auto-updates:<br />
<br />
<br />
<div class="separator" style="clear: both; text-align: center;">
<a href="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEhxjXnt3xyRuUxbzxHMB2xK3F62-izy6-4pUdkALGci9Jos9_E3Q5UOwp5_i5W0CjWDzVhmTJnrQtjbQd7FV3k_60kUDwOeU4wYAV4YUMN1ftLtgjeeh-eRTOdgByS_WdZBbfvwCr0Aoywf/s1600/auto-updates.png" imageanchor="1" style="margin-left: 1em; margin-right: 1em;"><img border="0" data-original-height="490" data-original-width="733" height="426" src="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEhxjXnt3xyRuUxbzxHMB2xK3F62-izy6-4pUdkALGci9Jos9_E3Q5UOwp5_i5W0CjWDzVhmTJnrQtjbQd7FV3k_60kUDwOeU4wYAV4YUMN1ftLtgjeeh-eRTOdgByS_WdZBbfvwCr0Aoywf/s640/auto-updates.png" width="640" /></a></div>
<br />
<br />
Anyways, if you do not wish to wait you can always kill the process. Above commands - ps and lsof should give you PIDs corresponding to the process using the locks. You can kill them by running<br />
<br />
<br />
<ul style="text-align: left;">
<li><b>sudo kill -9 PID</b></li>
</ul>
<div>
Replace PID with actual PID (Process ID) you see in the output of the above commands. Once done you can resume the software updates. You can also do</div>
<div>
<ul style="text-align: left;">
<li><b>sudo apt-get upgrade</b></li>
</ul>
<div>
to upgrade your software.</div>
</div>
<div>
<br /></div>
<div>
<br /></div>
<br />
If above does not work as well you can always<b> delete the lock file (Not recommended)</b><br />
<br />
<br />
<ul style="text-align: left;">
<li><b>sudo rm -rf /var/lib/dpkg/lock-frontend</b></li>
</ul>
<br />
<br />
and resume any update you might have. Please note we should not do this under ideal conditions. Lock files are meant to be present for special purposes. That being said, sometimes Softwares do go into an inconsistent state, and lock files have to be removed manually.<br />
<br />
Once you kill the process or remove the lock file manually run following command to let dpkg fix itself:<br />
<br />
<br />
<ul style="text-align: left;">
<li><b>sudo dpkg --configure -a</b></li>
</ul>
<div>
This is the same command we ran as the very 1ts step.</div>
<br />
<br /></div>
<div>
<br /></div>
<div>
<h4 style="text-align: left;">
Related Links</h4>
</div>
<div>
<ul style="text-align: left;">
<li><a href="https://unix.stackexchange.com/a/583738/41312">Ubuntu update error â waiting for unattended-upgr to exit â(SO)</a></li>
</ul>
</div>
<div>
<br /></div>
</div>
Aniket Thakurhttp://www.blogger.com/profile/07553743551249736583noreply@blogger.com0tag:blogger.com,1999:blog-5013829528944984059.post-89765710971579809302019-07-27T09:18:00.001-07:002019-07-27T09:18:56.798-07:00How to install IntelliJ Idea plugin from local disk<div dir="ltr" style="text-align: left;" trbidi="on">
<h4 style="text-align: left;">
Background</h4>
<div>
In the <a href="http://opensourceforgeeks.blogspot.com/2019/07/creating-intellij-plugin.html">last post</a>, we saw a basic tutorial on how to create a custom plugin for IntelliJ IDE's. In this post, I will show you how you can install a plugin you have on your local disk.</div>
<div>
<br /></div>
<h4 style="text-align: left;">
How to install IntelliJ Idea plugin from local disk</h4>
<div>
To install plugin from local disk, go to<b> setting in IDE(Ctrl+Alt+S) -> Plugins. </b>Next click on the <b>gear icon </b>and select <b>"Install plugin from disk".</b></div>
<div>
<br /></div>
<div class="separator" style="clear: both; text-align: center;">
<a href="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEgVmXL71-imdJ0tkDYGDlgMnDFfSrjhb_FCm0XMj253PcM3j00I7HwdGHVdePSjvXtu6VeRAYDksfGlt2tIipJCA3uRPItWKhG1UC8fwvGMZtNyH9cfyc3lM8mDxTJXl8K3XN429Pp18HQY/s1600/install_from_disk.PNG" imageanchor="1" style="margin-left: 1em; margin-right: 1em;"><img border="0" data-original-height="256" data-original-width="997" height="164" src="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEgVmXL71-imdJ0tkDYGDlgMnDFfSrjhb_FCm0XMj253PcM3j00I7HwdGHVdePSjvXtu6VeRAYDksfGlt2tIipJCA3uRPItWKhG1UC8fwvGMZtNyH9cfyc3lM8mDxTJXl8K3XN429Pp18HQY/s640/install_from_disk.PNG" width="640" /></a></div>
<div>
<br /></div>
<div>
<br /></div>
<div>
<br /></div>
<div>
Select the zip file of your plugin you have stored locally and select Ok. The plugin should get installed. You may have to restart the IDE for change to take effect.</div>
<div>
<br /></div>
<div class="separator" style="clear: both; text-align: center;">
<a href="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEgE06v_7HtTFqq01RBwDLlwxaxiCz64F3gpIjXx3ZLm-e6cYKl8Ub5oxYGe-nATFOsN-fJPqRQyz2cyaq0s4yEQkjswYmKqAGGvElNNeq0U5zsf80rnBCugR7LW6Eswy7oBu_nhsbplLezV/s1600/restart.PNG" imageanchor="1" style="margin-left: 1em; margin-right: 1em;"><img border="0" data-original-height="254" data-original-width="1007" height="160" src="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEgE06v_7HtTFqq01RBwDLlwxaxiCz64F3gpIjXx3ZLm-e6cYKl8Ub5oxYGe-nATFOsN-fJPqRQyz2cyaq0s4yEQkjswYmKqAGGvElNNeq0U5zsf80rnBCugR7LW6Eswy7oBu_nhsbplLezV/s640/restart.PNG" width="640" /></a></div>
<div>
<br /></div>
<div>
<br /></div>
<div>
Now you can see the plugin in the installed tab of your plugins section of settings. </div>
<div>
<br /></div>
<div>
<br /></div>
<div class="separator" style="clear: both; text-align: center;">
<a href="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEj9pa7LsB0oW6UVls1vDQ2v8VBtZhyphenhyphenALZRx_YTwVHlGCQJM2XsfQNzGxSmRxcJIDrHeRlzwHzxyYnUrsLM1ewnlqE5CWlM9pblPMAf5do6OzPpNi9693oQ5wZxLvQbz3oivd0SZBpR-4csV/s1600/installed1.PNG" imageanchor="1" style="margin-left: 1em; margin-right: 1em;"><img border="0" data-original-height="252" data-original-width="994" height="162" src="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEj9pa7LsB0oW6UVls1vDQ2v8VBtZhyphenhyphenALZRx_YTwVHlGCQJM2XsfQNzGxSmRxcJIDrHeRlzwHzxyYnUrsLM1ewnlqE5CWlM9pblPMAf5do6OzPpNi9693oQ5wZxLvQbz3oivd0SZBpR-4csV/s640/installed1.PNG" width="640" /></a></div>
<div>
<br /></div>
<div>
<br /></div>
<h4 style="text-align: left;">
Directories used by the IDE to store plugins</h4>
<div>
If you are wondering where are plugins instaled then the path is <b>config\plugins </b>under your IDEA directory. For me it is:</div>
<div>
<br /></div>
<div>
<ul style="text-align: left;">
<li><b>C:\Users\anike\.IdeaIC2019.1\config\plugins</b></li>
</ul>
</div>
<div>
It should put your plugin jar in above dir.</div>
<div>
<br /></div>
<div class="separator" style="clear: both; text-align: center;">
<a href="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEggctX-EGGewr_Bwq2cJJnv2torpuLMgZEBAT5g48QmD-y4j7ZJWGDMy4-9207Bb4F-oJapX-bmnGDMEzTSOE4_kOhZQWS96OLGYxbT2tvp6cCBRCne-6_4K_XUGO4BJVoEjP4oBCuIGAhj/s1600/installed_path.PNG" imageanchor="1" style="margin-left: 1em; margin-right: 1em;"><img border="0" data-original-height="312" data-original-width="923" height="216" src="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEggctX-EGGewr_Bwq2cJJnv2torpuLMgZEBAT5g48QmD-y4j7ZJWGDMy4-9207Bb4F-oJapX-bmnGDMEzTSOE4_kOhZQWS96OLGYxbT2tvp6cCBRCne-6_4K_XUGO4BJVoEjP4oBCuIGAhj/s640/installed_path.PNG" width="640" /></a></div>
<div>
<br /></div>
<div>
<br /></div>
<div>
<br /></div>
<div>
To see more details on this path refer - <a href="https://intellij-support.jetbrains.com/hc/en-us/articles/206544519-Directories-used-by-the-IDE-to-store-settings-caches-plugins-and-logs">Directories used by the IDE to store settings, caches, plugins and logs </a></div>
<div>
<br /></div>
<div>
<br /></div>
<div>
<br /></div>
<h4 style="text-align: left;">
Related Links</h4>
<div>
<ul style="text-align: left;">
<li><a href="http://opensourceforgeeks.blogspot.com/2019/07/creating-intellij-plugin.html">Creating an IntelliJ plugin(OSFG)</a></li>
<li><a href="https://intellij-support.jetbrains.com/hc/en-us/articles/206544519-Directories-used-by-the-IDE-to-store-settings-caches-plugins-and-logs">Directories used by the IDE to store settings, caches, plugins and logs </a></li>
</ul>
</div>
<div>
<br /></div>
</div>
Aniket Thakurhttp://www.blogger.com/profile/07553743551249736583noreply@blogger.com0tag:blogger.com,1999:blog-5013829528944984059.post-8343245142760125182019-07-27T09:01:00.002-07:002019-07-27T09:20:30.923-07:00Creating an Intellij plugin<div dir="ltr" style="text-align: left;" trbidi="on">
<h4 style="text-align: left;">
Background</h4>
<div>
Intellij IDEA is one of the famous IDEs(Integrated development environment) used for Java development. Intellij has a variant of IDE's that they provide like -</div>
<div>
<ol style="text-align: left;">
<li><b>Pycharm </b>- For Python</li>
<li><b>Webstorm </b>- For web development</li>
<li><b>IDEA </b>- For Java</li>
</ol>
<div>
etc. In this post, I will show how you can write your own plugin for any of these IDEs. To develop a plugin you need Intellij IDEA IDE. You can use this to create a plugin for any other variant of IDE. In fact, the framework for IDE remains the same, so you can create a plugin that can potentially work in all IDEs. </div>
</div>
<div>
<br /></div>
<div>
To start with download IntelliJ IDEA. I am using version 2019.1.3(Community edition).</div>
<div>
<br /></div>
<div class="separator" style="clear: both; text-align: center;">
<a href="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEiRwDdphrOkTxwQJ0ENpJo0sqVrG35VQ3ZkFFMHmz4CNrrUhiImZ7H5Ir1hT9QKY4YR06dDoFSf8ghzlr7waylIEGlqZau3Uz1XXD08oqcvNwZkLublJzcMzHfCfdgN6Gln238dOF_mXRud/s1600/idea_version.PNG" imageanchor="1" style="margin-left: 1em; margin-right: 1em;"><img border="0" data-original-height="399" data-original-width="605" height="263" src="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEiRwDdphrOkTxwQJ0ENpJo0sqVrG35VQ3ZkFFMHmz4CNrrUhiImZ7H5Ir1hT9QKY4YR06dDoFSf8ghzlr7waylIEGlqZau3Uz1XXD08oqcvNwZkLublJzcMzHfCfdgN6Gln238dOF_mXRud/s400/idea_version.PNG" width="400" /></a></div>
<div>
<br /></div>
<div>
<br /></div>
<h4 style="text-align: left;">
Idea</h4>
<div>
In this plugin, we are going to add a simple action functionality that takes in the selected text and searches on Stack overflow site. This action will be visible when you right-click on the editor panel of your IDE. Let's see how to do that,</div>
<div>
<br /></div>
<h4 style="text-align: left;">
Creating an IntelliJ plugin</h4>
<div>
<br /></div>
<div>
Open your IDEA and create a new project. <b>File-> New -> Project -> Intellij platform plugin</b></div>
<div>
<br /></div>
<div class="separator" style="clear: both; text-align: center;">
<a href="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEhWoy2rhWomh6qzYoDztezYniYdGDptXRmEbDx18Eko4DnpJcgo0gXvbOEBbt9LL3PXG7DWwWr5BecF2vfZRAYYFXSDg3LVyaj205XmnBsH_Q2VZ_kTpPaKHrriRvcJHXlLfJO-vAeoLz7K/s1600/new_proj.PNG" imageanchor="1" style="margin-left: 1em; margin-right: 1em;"><img border="0" data-original-height="774" data-original-width="926" height="534" src="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEhWoy2rhWomh6qzYoDztezYniYdGDptXRmEbDx18Eko4DnpJcgo0gXvbOEBbt9LL3PXG7DWwWr5BecF2vfZRAYYFXSDg3LVyaj205XmnBsH_Q2VZ_kTpPaKHrriRvcJHXlLfJO-vAeoLz7K/s640/new_proj.PNG" width="640" /></a></div>
<div>
<br /></div>
<div>
<br /></div>
<div>
Once done, click on next, enter your project name and submit. This should create a new project for you. One of the important files is <b>Project\resources\META-INF\plugin.xml. </b>This gives information about your plugin. Think of it as the manifest file of Android project (If you have worked on Android apps before). Got me location is <b>C:\Users\anike\IdeaProjects\StackOverflowSearch\resources\META-INF\plugin.xml </b></div>
<div>
and my project name is <b>StackOverflowSearch.</b></div>
<div>
<b><br /></b></div>
<div>
<b>NOTE</b>: You can choose Groovy as well to develop your plugin. I have selected default, which uses Java.</div>
<div>
<br /></div>
<div>
In the source folder create a class called StackoverflowSearch. This is going to be our action class. Make this class extend <b>com.intellij.openapi.actionSystem.AnAction. </b>AnAction is an abstract class provide by Intellij SDK framework. Once you extend it, you will have to implement the abstract methods in it</div>
<div>
<br /></div>
<div>
<div>
<pre class="brush: java"> @Override
public void actionPerformed(@NotNull AnActionEvent anActionEvent) {
}
</pre>
</div>
</div>
<div>
<br /></div>
<div>
Then you can add the following code to complete your simple action -</div>
<div>
<br /></div>
<div>
<pre class="brush: java">import com.intellij.ide.BrowserUtil;
import com.intellij.openapi.actionSystem.AnAction;
import com.intellij.openapi.actionSystem.AnActionEvent;
import com.intellij.openapi.actionSystem.CommonDataKeys;
import com.intellij.openapi.editor.CaretModel;
import com.intellij.openapi.editor.Editor;
import com.intellij.psi.PsiFile;
import org.jetbrains.annotations.NotNull;
public class StackoverflowSearch extends AnAction {
@Override
public void actionPerformed(@NotNull AnActionEvent anActionEvent) {
PsiFile file = anActionEvent.getData(CommonDataKeys.PSI_FILE);
Editor editor = anActionEvent.getRequiredData(CommonDataKeys.EDITOR);
CaretModel caretModel = editor.getCaretModel();
String selectedText = caretModel.getCurrentCaret().getSelectedText();
BrowserUtil.open("https://stackoverflow.com/search?q=" + selectedText);
}
}
</pre>
</div>
<div>
<br /></div>
<div>
<br /></div>
<div>
This essentially gets the selected text from your editor and open a browser URL with that query parameter. If you do not understand much with this code, don't worry just go to the <a href="https://www.jetbrains.org/intellij/sdk/docs/welcome.html">official documentation</a> and see what each class means. For eg. PSIFile - it s file representation in Intellij framework world. You can see more details <a href="https://www.jetbrains.org/intellij/sdk/docs/basics/architectural_overview/psi.html">here</a>. </div>
<div>
<br /></div>
<div>
<br /></div>
<div>
<br /></div>
<div>
Once done, you will have to list this action in the <b>plugin.xml </b>file we saw above. In this file, you should see the <<b>actions</b>> tag. Add below content inside it.</div>
<div>
<br /></div>
<div>
<br /></div>
<div>
<pre class="brush: java"> <action
id="Action.Stackoverflow.Search"
class="StackoverflowSearch"
text="Search Text on Stack Overflow"
description="Search Text on Stack Overflow">
<add-to-group group-id="EditorPopupMenu" anchor="last"/>
</action>
</pre>
</div>
<div>
<br /></div>
<div>
Once done you are all set to go. The only important thing to note above is the <b>add-to-group group-id </b>field. <b>EditorPopupMenu </b>means this action will be shown in Editor when you right-click. You could have other possible values to show it in Console or top menubar.<br />
<br />
My complete <b>plugin.xml</b> looks like below -</div>
<br />
<pre class="brush: java"><idea-plugin>
<id>com.your.company.unique.plugin.id</id>
<name>Stackoverflow Search Plugin</name>
<version>1.0</version>
<vendor email="opensourceforgeeks@gmail.com" url="http://opensourceforgeeks.blogspot.com/">OSFG</vendor>
<description><![CDATA[
Simple plugin to open selexted text in Stack overflow site
]]></description>
<change-notes><![CDATA[
Simple plugin to open selexted text in Stack overflow site
]]>
</change-notes>
<!-- please see http://www.jetbrains.org/intellij/sdk/docs/basics/getting_started/build_number_ranges.html for description -->
<idea-version since-build="173.0"/>
<!-- please see http://www.jetbrains.org/intellij/sdk/docs/basics/getting_started/plugin_compatibility.html
on how to target different products -->
<!-- uncomment to enable plugin in all products
<depends>com.intellij.modules.lang</depends>
-->
<extensions defaultExtensionNs="com.intellij">
<!-- Add your extensions here -->
</extensions>
<actions>
<!-- Add your actions here -->
<action
id="Action.Stackoverflow.Search"
class="StackoverflowSearch"
text="Search Text on Stack Overflow"
description="Search Text on Stack Overflow">
<add-to-group group-id="EditorPopupMenu" anchor="last"/>
</action>
</actions>
</idea-plugin>
</pre>
<br />
<div>
<br /></div>
<div>
<br /></div>
<div>
Now you can simply run your project,</div>
<div>
<br /></div>
<div class="separator" style="clear: both; text-align: center;">
<a href="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEiryz9d4IrOiKQXDo05ninYT2HSzLz-oB9St-tA6QvsRKkM0tJLEhAn3jqcXEZ_XE6oVJRDVbJHEjXThOG4L22oZDe52G6S0k1vZmFDKALinwIdXq_xGV9dURnaZOY401xm0wrbntvryPJV/s1600/Run.PNG" imageanchor="1" style="margin-left: 1em; margin-right: 1em;"><img border="0" data-original-height="179" data-original-width="368" height="155" src="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEiryz9d4IrOiKQXDo05ninYT2HSzLz-oB9St-tA6QvsRKkM0tJLEhAn3jqcXEZ_XE6oVJRDVbJHEjXThOG4L22oZDe52G6S0k1vZmFDKALinwIdXq_xGV9dURnaZOY401xm0wrbntvryPJV/s320/Run.PNG" width="320" /></a></div>
<div>
<br /></div>
<div>
<br /></div>
<div>
Run configuration should automatically be created when you click on run. It should be similar to the following -</div>
<div>
<br /></div>
<div class="separator" style="clear: both; text-align: center;">
<a href="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEjQj0erYckhDtw9c7DBlkCYYkLkneWJCTQEOLMN_PaotwWWApt62lckkB3z7JPeeT83Pu2hxS-WBJvc_K2kWFa1nEp0mE2jkRd1g0sPICUQrPZ7dDQ6kWu4opdAY2J2amK_cHqnaPUBTq3j/s1600/run_options.PNG" imageanchor="1" style="margin-left: 1em; margin-right: 1em;"><img border="0" data-original-height="686" data-original-width="1078" height="406" src="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEjQj0erYckhDtw9c7DBlkCYYkLkneWJCTQEOLMN_PaotwWWApt62lckkB3z7JPeeT83Pu2hxS-WBJvc_K2kWFa1nEp0mE2jkRd1g0sPICUQrPZ7dDQ6kWu4opdAY2J2amK_cHqnaPUBTq3j/s640/run_options.PNG" width="640" /></a></div>
<div>
<br /></div>
<div>
<b>NOTE</b>: Notice that the JRE is Intellij Idea SDK.</div>
<div>
<br /></div>
<div>
This should start a new IDE instance with your plugin activate. You can verify your plugin in installed by going to<b> settings(Ctrl_Alt+S) -> Plugins -> Installed</b></div>
<div>
<br /></div>
<div class="separator" style="clear: both; text-align: center;">
<a href="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEha-eV1cxYPU1HDucTl5QWvCGsITmQLiTHPOOLHlX_CMyzzHdEGf_JgCSFOTIFz4j3-pWKyMxUj_hyu5kG54KBYSAv01V6cAca9pS_x3b_-8WTvzKpdFX9mjwgCIn4DsLdU8e9gWwuAzWUn/s1600/installed.PNG" imageanchor="1" style="margin-left: 1em; margin-right: 1em;"><img border="0" data-original-height="251" data-original-width="1010" height="158" src="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEha-eV1cxYPU1HDucTl5QWvCGsITmQLiTHPOOLHlX_CMyzzHdEGf_JgCSFOTIFz4j3-pWKyMxUj_hyu5kG54KBYSAv01V6cAca9pS_x3b_-8WTvzKpdFX9mjwgCIn4DsLdU8e9gWwuAzWUn/s640/installed.PNG" width="640" /></a></div>
<div>
<br /></div>
<div>
Now you can select a text, right-click and see the "Search Text on Stackoverflow" action. Click that and it should open the Stack overflow site with your selected text as a search parameter,</div>
<div>
<br /></div>
<div class="separator" style="clear: both; text-align: center;">
<a href="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEgsYeGkkkd7hm8sYBRYf5ISTv_EDj2lR8d5Zg8V8jjnslHNNExmRWmfPYaADxNsPTj3ncFHPg8RNVoERecySLyGLNE5-km8ftGj6euO15lqv2BNzHsQHt3fqz0_DhFEg99vPDnEXhXUVaO3/s1600/action.PNG" imageanchor="1" style="margin-left: 1em; margin-right: 1em;"><img border="0" data-original-height="761" data-original-width="812" height="598" src="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEgsYeGkkkd7hm8sYBRYf5ISTv_EDj2lR8d5Zg8V8jjnslHNNExmRWmfPYaADxNsPTj3ncFHPg8RNVoERecySLyGLNE5-km8ftGj6euO15lqv2BNzHsQHt3fqz0_DhFEg99vPDnEXhXUVaO3/s640/action.PNG" width="640" /></a></div>
<div>
<br /></div>
<div>
<br /></div>
<h4 style="text-align: left;">
Distributing the plugin</h4>
<div>
To distribute the plugin, simply right click your plugin project and select - "<b>Prepare plugin module for deployment</b>". This should export a zip file which can be distributed. You should see a message like below when you have selected the above option.</div>
<div>
<br /></div>
<div>
<br /></div>
<div class="separator" style="clear: both; text-align: center;">
<a href="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEhY2079hJhnOvZCAE_oPTwCZCLqaGZGMyVmyEdDFcDKK43duat2jusZ9zTGkorb35Ba3NpkbMgjCVPTFCtRG9ywBtCIgHuv4eMPF8uuWoIg6fcu5AcmjXWEu6sUwsfEqnu4odrcFcbWTEOD/s1600/deployed.PNG" imageanchor="1" style="margin-left: 1em; margin-right: 1em;"><img border="0" data-original-height="239" data-original-width="448" height="212" src="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEhY2079hJhnOvZCAE_oPTwCZCLqaGZGMyVmyEdDFcDKK43duat2jusZ9zTGkorb35Ba3NpkbMgjCVPTFCtRG9ywBtCIgHuv4eMPF8uuWoIg6fcu5AcmjXWEu6sUwsfEqnu4odrcFcbWTEOD/s400/deployed.PNG" width="400" /></a></div>
<div>
<br /></div>
<div>
To know how to install plugin from local disk refer - <a href="http://opensourceforgeeks.blogspot.com/2019/07/how-to-install-intellij-idea-plugin.html">How to install IntelliJ Idea plugin from local disk</a><br />
<br />
You can also put it into a plugin repository for others to use instead of distributing zip file. For more details on the plugin, repo see <a href="http://www.jetbrains.org/intellij/sdk/docs/plugin_repository/index.html">here</a>. I will be adding more details on how to create an Intellij plugin. So stay tuned.<br />
<br />
<br /></div>
<div>
</div>
<h4 style="text-align: left;">
Related Links</h4>
<div>
<ul style="text-align: left;">
<li><a href="https://www.jetbrains.org/intellij/sdk/docs/welcome.html">Intellij Platform SDK</a></li>
<li><a href="http://opensourceforgeeks.blogspot.com/2019/07/how-to-install-intellij-idea-plugin.html">How to install IntelliJ Idea plugin from local disk(OSFG)</a></li>
</ul>
</div>
</div>
Aniket Thakurhttp://www.blogger.com/profile/07553743551249736583noreply@blogger.com0tag:blogger.com,1999:blog-5013829528944984059.post-10988744024769841862019-05-26T05:34:00.002-07:002019-05-26T05:34:25.191-07:00How to remove computer name from prompt in Ubuntu terminal<div dir="ltr" style="text-align: left;" trbidi="on">
<h4 style="text-align: left;">
Background</h4>
<div>
If you are using Ubuntu terminal you must have noticed that terminal prompt looks like below -</div>
<div>
<br /></div>
<div class="separator" style="clear: both; text-align: center;">
<a href="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEiOutvR-CHZXibf8meGBrOk9rHg77cqTPu7X6BUYPrIcV_GOwuSP1uiO6_Lx86sOUM0AqfZzgamWs2FoCm_kIKSsbI-vAjbX3Ep4uTAmGCvbX0OzGE6LAJPoksdWBGAlpWw7v1DGj1e4eIe/s1600/terminal.png" imageanchor="1" style="margin-left: 1em; margin-right: 1em;"><img border="0" data-original-height="584" data-original-width="814" height="458" src="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEiOutvR-CHZXibf8meGBrOk9rHg77cqTPu7X6BUYPrIcV_GOwuSP1uiO6_Lx86sOUM0AqfZzgamWs2FoCm_kIKSsbI-vAjbX3Ep4uTAmGCvbX0OzGE6LAJPoksdWBGAlpWw7v1DGj1e4eIe/s640/terminal.png" width="640" /></a></div>
<div>
<br /></div>
<div>
Notice that prompt looks like -</div>
<div>
<br /></div>
<div>
<b>athakur@athakur-Inspiron-7572:~/Documents/code$</b></div>
<div>
<b><br /></b></div>
<div>
The problem is this is fairly large and with more folders inside the root directory, there is much less space to type actual commands. In this post, I will show how to fix this.</div>
<div>
<br /></div>
<h4 style="text-align: left;">
How to remove computer name from prompt in Ubuntu terminal</h4>
<div>
<br /></div>
<div>
To fix this you need to edit <b>~/.bashrc</b> file. In this file there is a variable called PS1 that governs how your command prompt looks like. If you open <b>~/.bashrc </b>you should see something like below -<br />
<br />
<pre class="brush: java">if [ "$color_prompt" = yes ]; then
PS1='${debian_chroot:+($debian_chroot)}\[\033[01;32m\]\u@\h\[\033[00m\]:\[\033[01;34m\]\w\[\033[00m\]\$ '
else
PS1='${debian_chroot:+($debian_chroot)}\u@\h:\w\$ '
fi
unset color_prompt force_color_prompt
# If this is an xterm set the title to user@host:dir
case "$TERM" in
xterm*|rxvt*)
PS1="\[\e]0;${debian_chroot:+($debian_chroot)}\u@\h: \w\a\]$PS1"
;;
*)
;;
esac
</pre>
<br />
<br />
<br />
Let me explain a little bit about PS1 variable and above itself.</div>
<div>
<br /></div>
<div>
<ul style="text-align: left;">
<li><b>debian_chroot</b>: This is applicable if you are running chroot operation (Your root directory is different than the default one). If you do not know chroot then do not worry, this is just and empty variable and can be ignored for now. </li>
<li><b>XTERM</b>: This is for a terminal emulator. If you are using XTERM PS1 under this would take effect.</li>
<li><b>color_prompt</b>: This would be the default case for most. Your terminal would support color prompt. So PS1 under <b>"$color_prompt" = yes </b>is something you need to edit. </li>
</ul>
<div>
If you have not heard above, don't worry about it just change the PS1 variable under the color_propmt if statement.</div>
<div>
<br /></div>
<ul style="text-align: left;">
<li><b>\u:</b> expands to the current username</li>
<li><b>\h:</b> expands to the current hostname</li>
<li><b>\w:</b> expands to the current working directory</li>
<li><b>\$: </b>expands to # for root and $ for all other users</li>
</ul>
</div>
<div>
<br /></div>
<div>
Now that you know what each means and once you have figured out which PS1 to change you can simply remove "@\h" from it.<br />
<br />
<br />
<br />
So change<br />
<br />
<pre class="brush: java">if [ "$color_prompt" = yes ]; then
PS1='${debian_chroot:+($debian_chroot)}\[\033[01;32m\]\u@\h\[\033[00m\]:\[\033[01;34m\]\w\[\033[00m\]\$ '
</pre>
<br />
<br />
to<br />
<br />
<pre class="brush: java">if [ "$color_prompt" = yes ]; then
PS1='${debian_chroot:+($debian_chroot)}\[\033[01;32m\]\u\[\033[00m\]:\[\033[01;34m\]\w\[\033[00m\]\$ '
</pre>
<br />
<br />
<br />
Once done save it, and run -<br />
<br />
<ul style="text-align: left;">
<li><b>source ~/.bashrc</b></li>
</ul>
<div>
or simply open a new terminal and you should see the change.</div>
<div>
<br /></div>
<div class="separator" style="clear: both; text-align: center;">
<a href="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEjKNIT_6rZNtAbiTkwwqIdiGZqRmb1CjyLo8MKVAzwIhn2mGCNmyRcThVmdb_VfG_nYR_cU6ePePjUPmfhZEcXFX5WW9wmFozIMegLCwzKIFTRhyphenhyphenCxbEWSuf1xtf81uRUlph7J2G-2Yf_gN/s1600/terminal-after.png" imageanchor="1" style="margin-left: 1em; margin-right: 1em;"><img border="0" data-original-height="584" data-original-width="814" height="458" src="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEjKNIT_6rZNtAbiTkwwqIdiGZqRmb1CjyLo8MKVAzwIhn2mGCNmyRcThVmdb_VfG_nYR_cU6ePePjUPmfhZEcXFX5WW9wmFozIMegLCwzKIFTRhyphenhyphenCxbEWSuf1xtf81uRUlph7J2G-2Yf_gN/s640/terminal-after.png" width="640" /></a></div>
<div>
<br /></div>
<div>
<h4 style="text-align: left;">
Related Links</h4>
</div>
</div>
<div>
<ul style="text-align: left;">
<li><a href="http://opensourceforgeeks.blogspot.com/2019/05/customizing-traytaskbar-date-display-in.html">Customizing tray/taskbar date display in Ubuntu to show the actual date (OSFG)</a></li>
<li><a href="http://opensourceforgeeks.blogspot.com/2019/05/how-to-fix-hitting-arrow-keys-adds.html">How to fix hitting arrow keys adds characters in vi editor issue in Ubuntu (OSFG)</a></li>
</ul>
</div>
<div>
<br /></div>
</div>
Aniket Thakurhttp://www.blogger.com/profile/07553743551249736583noreply@blogger.com0tag:blogger.com,1999:blog-5013829528944984059.post-46877910172291006122019-05-26T00:07:00.002-07:002019-05-26T00:07:56.554-07:00Customizing tray/taskbar date display in Ubuntu to show the actual date<div dir="ltr" style="text-align: left;" trbidi="on">
<h4 style="text-align: left;">
Background</h4>
<div>
In my <b>Ubuntu 18.04.2 LTS</b>, I see that the date/time displayed on the desktop on the taskbar above is like - "Sun 12.00 PM".</div>
<div>
<br /></div>
<div class="separator" style="clear: both; text-align: center;">
</div>
<div class="separator" style="clear: both; text-align: center;">
<a href="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEjh5Q5sZ8A000I_dCUa049sgqKdXGIDeSJ44S2-lBNAQ3UuSoGNSScJ0recGs85vOGxT7UeIWe7n1auBcXHzTMF0sjVStPiEFwoh9gWRoihpgB368a-aCk_1ysfRNmW86DNkogoOF-UqqCU/s1600/time_before.png" imageanchor="1" style="margin-left: 1em; margin-right: 1em;"><img border="0" data-original-height="198" data-original-width="1600" height="78" src="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEjh5Q5sZ8A000I_dCUa049sgqKdXGIDeSJ44S2-lBNAQ3UuSoGNSScJ0recGs85vOGxT7UeIWe7n1auBcXHzTMF0sjVStPiEFwoh9gWRoihpgB368a-aCk_1ysfRNmW86DNkogoOF-UqqCU/s640/time_before.png" width="640" /></a></div>
<div>
</div>
<div>
<br /></div>
<div>
You have to actually click on it to see the current date. In this post, I will show you how to add a date to the format that you see on the top. It would have been much easier if Ubuntu gave us this customization in settings itself, but unfortunately, that is not the case, at least not yet.</div>
<div>
<br /></div>
<h4 style="text-align: left;">
Customizing tray/taskbar date display in Ubuntu to show the actual date</h4>
<div>
There are two ways you can do this. I will show the most user-friendly method first. But if you are more comfortable with Linux command line terminal and executing commands go to 2. advance section below.</div>
<div>
<br /></div>
<div>
<br /></div>
<div>
<br /></div>
<h4 style="text-align: left;">
1. User-Friendly - GUI Way</h4>
<div>
If you do not prefer using the command line, then you can install a GUI based tool. The tool name is <b>"gnome-tweak-tool". </b>You can search for "GNOME tweaks" in the Ubuntu software center. Install it.</div>
<div>
<br /></div>
<div class="separator" style="clear: both; text-align: center;">
<a href="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEiCMfE3ILwPP4rIeU3xHiTVQF1cKbFsfmYI6gY9aQWGX4-8nXUe_qFg4G4fXTVq0Sk0NUIHnWAQyBlbsXzEyGeqCHnB_-poL0Mduk8FxnyBdZLIi7XekwsB5fy8wUrEcfSvundkKPiSeoc5/s1600/gtweak1.png" imageanchor="1" style="margin-left: 1em; margin-right: 1em;"><img border="0" data-original-height="843" data-original-width="1200" height="448" src="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEiCMfE3ILwPP4rIeU3xHiTVQF1cKbFsfmYI6gY9aQWGX4-8nXUe_qFg4G4fXTVq0Sk0NUIHnWAQyBlbsXzEyGeqCHnB_-poL0Mduk8FxnyBdZLIi7XekwsB5fy8wUrEcfSvundkKPiSeoc5/s640/gtweak1.png" width="640" /></a></div>
<br />
<div class="separator" style="clear: both; text-align: center;">
<a href="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEjUjPVSxC7-EWw8_IWNleB5BzgfthWBMcSNmlCOG1PZap42DfAu_wis8onbnR6UmsVrQAfTbhg7FZBZ0es7NjSxaIVnrUPECJRtO1tMZB_marcJTZ0MfHpifXn_PoKNAHBfFJsGcU8M7pHu/s1600/gtweak2.png" imageanchor="1" style="margin-left: 1em; margin-right: 1em;"><img border="0" data-original-height="843" data-original-width="1200" height="448" src="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEjUjPVSxC7-EWw8_IWNleB5BzgfthWBMcSNmlCOG1PZap42DfAu_wis8onbnR6UmsVrQAfTbhg7FZBZ0es7NjSxaIVnrUPECJRtO1tMZB_marcJTZ0MfHpifXn_PoKNAHBfFJsGcU8M7pHu/s640/gtweak2.png" width="640" /></a></div>
<div>
<br /></div>
<div>
<br /></div>
<div>
Launch it and you should see the following screen. Go to Top Bar for date settings.</div>
<div>
<br /></div>
<div>
<br /></div>
<div class="separator" style="clear: both; text-align: center;">
<a href="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEja_bfaiyErPiUT3SFNnKZSKc_RSiDbcUdTQLL-dix2lFAKCdXvxNpb3YSljUpbUj73CkE8NVj2qqAfxtR9-HNHE_qYpAQnYy_KE4ox1nR1mZ18t6wADeKyT4-8QJ1eO14FJZomc57bMYRA/s1600/tweak-set-def.png" imageanchor="1" style="margin-left: 1em; margin-right: 1em;"><img border="0" data-original-height="626" data-original-width="876" height="456" src="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEja_bfaiyErPiUT3SFNnKZSKc_RSiDbcUdTQLL-dix2lFAKCdXvxNpb3YSljUpbUj73CkE8NVj2qqAfxtR9-HNHE_qYpAQnYy_KE4ox1nR1mZ18t6wADeKyT4-8QJ1eO14FJZomc57bMYRA/s640/tweak-set-def.png" width="640" /></a></div>
<div>
<br /></div>
<div>
<br /></div>
<div>
<br /></div>
<div>
You can change the configuration as needed. You can see there are a bunch of other options here as well - like show battery percentage. All yours to play with :)</div>
<div>
<br /></div>
<div>
<br /></div>
<div>
<b>NOTE</b>: If you do not prefer the Ubuntu software center but apt-get to install software, you can use the following command to install and launch the above application.</div>
<div>
<br /></div>
<div>
<div>
<b>sudo apt install gnome-tweak-tool</b></div>
<div>
<b>gnome-tweaks # now launch it</b></div>
</div>
<div>
<b><br /></b></div>
<div class="separator" style="clear: both; text-align: center;">
<a href="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEiLTUlj_txQUSiy3joTgo8JkbGWbL8nDyYEq6_fFi-GipqiLbAFvtpra8LMWlFYsg6sJHp8dSHEIqyP5FMY8NOliQv2TmjED8awX1r7E_wckMvWUrPHhe28sduMP625gvSnHkJorp_nvQi9/s1600/gtweak-cli-install.png" imageanchor="1" style="margin-left: 1em; margin-right: 1em;"><img border="0" data-original-height="540" data-original-width="814" height="424" src="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEiLTUlj_txQUSiy3joTgo8JkbGWbL8nDyYEq6_fFi-GipqiLbAFvtpra8LMWlFYsg6sJHp8dSHEIqyP5FMY8NOliQv2TmjED8awX1r7E_wckMvWUrPHhe28sduMP625gvSnHkJorp_nvQi9/s640/gtweak-cli-install.png" width="640" /></a></div>
<div>
<b><br /></b></div>
<div>
<br /></div>
<div>
<br /></div>
<div>
<br /></div>
<h4 style="text-align: left;">
2. Advanced - CLI Way</h4>
<div>
There are two commands that you need to know here -</div>
<div>
<ol style="text-align: left;">
<li><b>gsettings set org.gnome.desktop.interface clock-show-date true</b></li>
<ul>
<li>makes the date appear</li>
</ul>
<li><b>gsettings set org.gnome.desktop.interface clock-show-seconds true</b></li>
<ul>
<li>switches the seconds display on</li>
</ul>
</ol>
<div>
You can similarly replace "<b>set</b>" by "<b>get</b>" to see the current values. By default, both values are set to false which is why you don't see a date or seconds.</div>
</div>
<div>
<br /></div>
<div class="separator" style="clear: both; text-align: center;">
<a href="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEhwvRqggbbgLRu6K3fZkYRwZLzmjdaMlagmwJBN7NPsXy8h4NUE3VYiWD4u92CbQGZLSf8SlYIOTArrdaH67MEB69mKIg3m5fWD8WsS2eKatztXPSc6BYeGpIALjaWYro3-RQDdoOuExK4Z/s1600/time_Set_before.png" imageanchor="1" style="margin-left: 1em; margin-right: 1em;"><img border="0" data-original-height="540" data-original-width="814" height="424" src="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEhwvRqggbbgLRu6K3fZkYRwZLzmjdaMlagmwJBN7NPsXy8h4NUE3VYiWD4u92CbQGZLSf8SlYIOTArrdaH67MEB69mKIg3m5fWD8WsS2eKatztXPSc6BYeGpIALjaWYro3-RQDdoOuExK4Z/s640/time_Set_before.png" width="640" /></a></div>
<div>
<br /></div>
<div>
<br /></div>
<div>
Now let's go ahead and set these values to true and see the change of date/time format in the taskbar above.</div>
<div>
<br /></div>
<div class="separator" style="clear: both; text-align: center;">
<a href="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEje3aresUaa39MtGMEkBjURkRKFnz-D9JG12tjbVoHi0QeKV57ks0pPKB8PGwWvWLaGKKi4ShL_R4IsodVIXzkr5ZxI7eO8VDjD1scME2qS_Z_cmas1NUs2m-Jlz43xMzK2t_7y1F26X3Pj/s1600/Set_time_after.png" imageanchor="1" style="margin-left: 1em; margin-right: 1em;"><img border="0" data-original-height="540" data-original-width="814" height="424" src="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEje3aresUaa39MtGMEkBjURkRKFnz-D9JG12tjbVoHi0QeKV57ks0pPKB8PGwWvWLaGKKi4ShL_R4IsodVIXzkr5ZxI7eO8VDjD1scME2qS_Z_cmas1NUs2m-Jlz43xMzK2t_7y1F26X3Pj/s640/Set_time_after.png" width="640" /></a></div>
<div>
<br /></div>
<div>
<br /></div>
<div>
And the result is -</div>
<div>
<br /></div>
<div class="separator" style="clear: both; text-align: center;">
<a href="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEjEnHJW798NTHTgcpg5-c-clL1fLICiEmybnJYp7-fWJ6QdFxA2lOeAXQF79dJktemIjuvgNkwPjcL5ke3uv-nwWCXuPHPsi0qt0Zn_TGqRWhYlF75QM9SRbkYcQb2flgbUH3j2hqXSqAII/s1600/timr_after.png" imageanchor="1" style="margin-left: 1em; margin-right: 1em;"><img border="0" data-original-height="202" data-original-width="1600" height="80" src="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEjEnHJW798NTHTgcpg5-c-clL1fLICiEmybnJYp7-fWJ6QdFxA2lOeAXQF79dJktemIjuvgNkwPjcL5ke3uv-nwWCXuPHPsi0qt0Zn_TGqRWhYlF75QM9SRbkYcQb2flgbUH3j2hqXSqAII/s640/timr_after.png" width="640" /></a></div>
<div>
<br /></div>
<div>
<br /></div>
<div>
<br /></div>
<div>
I personally don't like seconds showing up. Just date works for me, so I have set accordingly. You can have settings that best suit you. You can do a similar thing with battery percentage as well with following command -</div>
<div>
<br /></div>
<div>
<ul style="text-align: left;">
<li><b>gsettings set org.gnome.desktop.interface show-battery-percentage true</b></li>
</ul>
</div>
<div>
<br /></div>
<div>
<br /></div>
<h4 style="text-align: left;">
Related Links</h4>
<div>
<ul>
<li><a href="http://opensourceforgeeks.blogspot.com/2019/05/how-to-fix-hitting-arrow-keys-adds.html">How to fix hitting arrow keys adds characters in vi editor issue in Ubuntu(OSFG)</a></li>
</ul>
</div>
<div>
<br /></div>
</div>
Aniket Thakurhttp://www.blogger.com/profile/07553743551249736583noreply@blogger.com0tag:blogger.com,1999:blog-5013829528944984059.post-35830795102797504112019-05-25T05:23:00.001-07:002019-05-26T04:51:23.159-07:00How to fix hitting arrow keys adds characters in vi editor issue in Ubuntu<div dir="ltr" style="text-align: left;" trbidi="on">
<h4 style="text-align: left;">
Background</h4>
<div>
I just purchased a new Laptop and the obvious next thing to do was add Ubuntu to it. There are some common problems that everyone faces when a new Ubuntu OS is installed and one such problem is - hitting arrow keys adds characters in vi the editor. In this post, I will show you how to fix this issue.</div>
<div>
<br /></div>
<div>
<br /></div>
<div class="separator" style="clear: both; text-align: center;">
<a href="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEh86ul1A3J8XvzQ0b3gOi6NgGCJMxvmXhoMgWxaEEtsJKRWwZ6AMRodJ8UmV8X2xGiiL7q6YvJdcQvc0OtkxbcnFBT-qB8UdntrsUoyhkv88m1xY2ta2-sxDYBYymwP-Di1Am2VCE91AEQX/s1600/vi_issues.gif" style="margin-left: 1em; margin-right: 1em;"><img border="0" data-original-height="608" data-original-width="890" height="435" src="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEh86ul1A3J8XvzQ0b3gOi6NgGCJMxvmXhoMgWxaEEtsJKRWwZ6AMRodJ8UmV8X2xGiiL7q6YvJdcQvc0OtkxbcnFBT-qB8UdntrsUoyhkv88m1xY2ta2-sxDYBYymwP-Di1Am2VCE91AEQX/s640/vi_issues.gif" width="640" /></a></div>
<div>
<br /></div>
<div>
<br /></div>
<h4 style="text-align: left;">
Fixing hitting arrow keys adds characters in vi editor issue</h4>
<div>
To fix this issue, edit a file called <b>vim.rc </b>in your root folder. If it's not present create one. You can use the following command.</div>
<div>
<br /></div>
<div>
<ul style="text-align: left;">
<li><b>vi ~/.vimrc</b></li>
</ul>
</div>
<div>
Now add the following content to it -</div>
<div>
<br /></div>
<div>
<ul>
<li><b>set nocompatible</b></li>
</ul>
</div>
<div>
If backspace is not working add following content -<br />
<br />
<ul style="text-align: left;">
<li><b>set backspace=2</b></li>
</ul>
</div>
<div>
<br />
And that's it. Save the file and you should be good to go. </div>
<div>
<br /></div>
<div class="separator" style="clear: both; text-align: center;">
<a href="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEgUs2EUfXY593sWL09JAoXYYlb41qhBSj5jWbWmKvkv5hYhBUday8R-_vs_5uuRc_lCZzWwyayf0KgOE89mG91VEkIi31xHziuTEqBNlpL60G-0PWMkL4aKSEmz8OyXHRWZiPU3WvYluCuv/s1600/vimrc.png" style="margin-left: 1em; margin-right: 1em;"><img border="0" data-original-height="606" data-original-width="894" height="432" src="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEgUs2EUfXY593sWL09JAoXYYlb41qhBSj5jWbWmKvkv5hYhBUday8R-_vs_5uuRc_lCZzWwyayf0KgOE89mG91VEkIi31xHziuTEqBNlpL60G-0PWMkL4aKSEmz8OyXHRWZiPU3WvYluCuv/s640/vimrc.png" width="640" /></a></div>
<div>
<br /></div>
<div>
<br /></div>
<div>
Another cleaner way is just to install vim -</div>
<div>
<ul style="text-align: left;">
<li><b>sudo apt-get install vim</b></li>
</ul>
</div>
<div>
Now that the problem is resolved, let's try to understand the issue here. vi as an editor has normal and insert mode. When you open a file using vi you are in normal mode. Here you can go to any line, use any arrow keys and the behavior is as expected. Now when you type "i", you essentially go into insert mode. In this mode, vi does not expect you to go left, right, top, bottom using arrow keys. You can always do that by pressing "ESC" and going back to normal mode. Insert mode is just to add text to your file and that's the behavior of vi.</div>
<div>
<br /></div>
<div>
Hope this helps :)</div>
<div>
<br /></div>
<div>
<br /></div>
<div>
<br /></div>
<div>
<br /></div>
</div>
Aniket Thakurhttp://www.blogger.com/profile/07553743551249736583noreply@blogger.com0tag:blogger.com,1999:blog-5013829528944984059.post-77656461628843844322019-04-13T23:50:00.001-07:002019-04-13T23:50:13.903-07:00How to install Oracle Java 11 in Ubuntu<div dir="ltr" style="text-align: left;" trbidi="on">
<h4 style="text-align: left;">
Background</h4>
<div style="text-align: left;">
In one of my previous posts I had covered how you can install Java 8 in your Ubuntu machine. In this post I will show how you can install Java 11 which is the latest SE version released (April 2019). </div>
<div style="text-align: left;">
<br /></div>
<div style="text-align: left;">
Oracle Java 11 is first LTS (Long term support) of Oracle Java release. </div>
<div style="text-align: left;">
<br /></div>
<div style="text-align: left;">
NOTE: Oracle uses a commercial license now. You can download and use Oracle java for development and testing without any cost but to use it in production you need to pay a fee. </div>
<div style="text-align: left;">
<br /></div>
<div style="text-align: left;">
If you do not want to pay you can always use Open JDK 11. From Java 11 forward, therefore, Oracle JDK builds and OpenJDK builds will be essentially identical. You can read more about this -</div>
<ul style="text-align: left;">
<li><a href="https://blogs.oracle.com/java-platform-group/oracle-jdk-releases-for-java-11-and-later">Oracle JDK Releases for Java 11 and Later</a></li>
</ul>
<br />
<h4 style="text-align: left;">
How to install Oracle Java 11 in Ubuntu</h4>
<div style="text-align: left;">
You can get Oracle Java 11 installer using linuxuprising PPA. To add this PPA execute following commands -</div>
<div style="text-align: left;">
<br /></div>
<ul style="text-align: left;">
<li><b>sudo add-apt-repository ppa:linuxuprising/java</b></li>
<li><b>sudo apt-get update</b></li>
</ul>
<br />
<div class="separator" style="clear: both; text-align: center;">
<a href="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEgY9J86i3Q_4m1ELLdYk7kljwKbLvzcD0Kx1yFA7EBiZUI4FAUlLrrhAqj3HfZKZ01jcr9VDa8SPtoBAb0AMb0rU9atS8p-0sg8jID8XFTrPu4S8iQBoYc8yUD1wHeiDGZTQ6JxIOfGVxPK/s1600/add-ppa.png" imageanchor="1" style="margin-left: 1em; margin-right: 1em;"><img border="0" data-original-height="696" data-original-width="722" height="616" src="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEgY9J86i3Q_4m1ELLdYk7kljwKbLvzcD0Kx1yFA7EBiZUI4FAUlLrrhAqj3HfZKZ01jcr9VDa8SPtoBAb0AMb0rU9atS8p-0sg8jID8XFTrPu4S8iQBoYc8yUD1wHeiDGZTQ6JxIOfGVxPK/s640/add-ppa.png" width="640" /></a></div>
<br />
<br />
To install the installer execute the following command -<br />
<br />
<ul style="text-align: left;">
<li><b>sudo apt-get install oracle-java11-installer</b></li>
</ul>
You would need to accept the terms and conditions and continue with the installer. Once installed you can check the version of Java installed with following command -<br />
<br />
<ul style="text-align: left;">
<li><b>java -version </b></li>
</ul>
<br />
To make Java 11 default you can install following package / execute following command -<br />
<br />
<ul style="text-align: left;">
<li><b>sudo apt-get install oracle-java11-set-default </b></li>
</ul>
If you do not want this as default simply remove above pacakge -<br />
<ul style="text-align: left;">
<li><b>sudo apt-get remove oracle-java11-set-default</b></li>
</ul>
<br />
<br />
<h4 style="text-align: left;">
Related Links</h4>
<ul style="text-align: left;">
<li><a href="https://opensourceforgeeks.blogspot.com/2016/05/installing-oracle-java-8-in-ubuntu-or.html">Installing Oracle Java 8 In Ubuntu Or Linux Mint Via PPA Repository [JDK8](OSFG) </a></li>
<li><a href="https://www.linuxuprising.com/2018/10/how-to-install-oracle-java-11-in-ubuntu.html"> How To Install Oracle Java 11 In Ubuntu, Linux Mint Or Debian (From PPA Repository)</a></li>
</ul>
</div>
Aniket Thakurhttp://www.blogger.com/profile/07553743551249736583noreply@blogger.com0tag:blogger.com,1999:blog-5013829528944984059.post-55329312241577653762019-03-28T06:16:00.002-07:002019-03-28T12:12:09.239-07:00Writing unit tests for AWS Lambda in Node.js<div dir="ltr" style="text-align: left;" trbidi="on">
<h4 style="text-align: left;">
Background</h4>
<div>
In the last post, we saw -</div>
<div>
<ul style="text-align: left;">
<li><a href="http://opensourceforgeeks.blogspot.com/2019/02/how-to-write-mocha-and-chai-unit-tests.html">How to write Mocha and Chai unit tests for your Node.js app?</a></li>
</ul>
<div>
In this post, we will see an extension of the same. We will see how we can extend this to write test cases for AWS Lambda functions. We are still going to use Chai and Mocha, but also some additional dependencies. Following is the list of final dependencies we need -</div>
</div>
<div>
<br /></div>
<div>
<br /></div>
<div>
<div>
<pre class="brush: java"> "devDependencies": {
"chai": "^4.2.0",
"lambda-tester": "^3.5.0",
"mocha": "^6.0.2",
"mock-require": "^3.0.3"
}
</pre>
</div>
</div>
<div>
<br /></div>
<div>
<br /></div>
<div>
Also, note these are dev dependencies. These are required only for development/testing. Here -</div>
<div>
<ul style="text-align: left;">
<li><b>lambda-tester </b>is used for simulating lambda behavior. You can use this to send mock events and handle the result or errors.</li>
<li><b>mock-require</b> is used to mock any other dependencies your lambda might be depending on. For eg. any service or network call.</li>
</ul>
<div>
<br /></div>
</div>
<h4>
Writing unit tests for AWS Lambda in Node.js</h4>
<div>
Let's say following is our lambda code -</div>
<div>
<br /></div>
<div>
<br /></div>
<div>
<div>
<pre class="brush: java">exports.handler = (event, context, callback) => {
var searchId = event.pathParameters.searchId;
if(searchId) {
var result = {
status : "success",
code: 200,
data: "Got searchId in the request"
}
callback(null,result)
}
else {
var result = {
status : "failure",
code: 400,
data: "Missing searchId in the request"
}
callback(result, null);
}
};
</pre>
</div>
</div>
<div>
<br /></div>
<div>
<br /></div>
<div>
<br /></div>
<div>
It's just a simple code that looks for searchId as the path parameter and if not found returns error. Now mocha tests for this lambda would look like -</div>
<div>
<br /></div>
<pre class="brush: java">const assert = require('chai').assert;
const expect = require('chai').expect;
const lambdaTester = require('lambda-tester');
const mockRequire = require('mock-require');
const index = require("../index");
describe("Lambda Tests", function(){
describe("Successful Invocation", function(){
it("Successful Invocation with results", function(done) {
const mockData = {
pathParameters : {
searchId : 10
}
};
lambdaTester(index.handler).event(mockData)
.expectResult((result) => {
expect(result.status).to.exist;
expect(result.code).to.exist;
expect(result.data).to.exist;
assert.equal(result.status, "success");
assert.equal(result.code, 200);
assert.equal(result.data, "Got searchId in the request");
}).verify(done);
});
});
describe("Failed Invocation", function(){
it("Unsuccessful invocation", function(done) {
const mockData = {
pathParameters : {
newSearchId : 5
}
};
lambdaTester(index.handler).event(mockData)
.expectError((result) => {
expect(result.status).to.exist;
expect(result.code).to.exist;
expect(result.data).to.exist;
assert.equal(result.status, "failure");
assert.equal(result.code, 400);
assert.equal(result.data, "Missing searchId in the request");
}).verify(done);
});
});
})
</pre>
<div>
<br /></div>
<div>
<br /></div>
<div>
You need to follow the same conventions we saw in the last post. Create package.json, add dev dependencies mentioned above. Run <b>npm install. </b>Create a folder call test and add your test file in it (Content mentioned above). Once done you can run <b>mocha</b> at the root level.</div>
<div>
<br /></div>
<div class="separator" style="clear: both; text-align: center;">
<a href="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEg3ddS00S-Wk9VyI5ejJ9hJI8uBde6XmiGOUt0jw9lAo64AmZffPbkWknl4lPfihMK4fwTadBoLV0rJfnbHQRGgSSFGfXLlIg-8y5WNFPZpcrArqSTFv8CW7HFL1yN-Ooov5uAeTRb0xl6T/s1600/mocha.png" imageanchor="1" style="margin-left: 1em; margin-right: 1em;"><img border="0" data-original-height="630" data-original-width="1092" height="368" src="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEg3ddS00S-Wk9VyI5ejJ9hJI8uBde6XmiGOUt0jw9lAo64AmZffPbkWknl4lPfihMK4fwTadBoLV0rJfnbHQRGgSSFGfXLlIg-8y5WNFPZpcrArqSTFv8CW7HFL1yN-Ooov5uAeTRb0xl6T/s640/mocha.png" width="640" /></a></div>
<div>
<br /></div>
<div>
<br />
<br />
<br />
If you see above I also mentioned we need "mock-require". This would be used if you actually need to mack a service. Let's say your lambda uses a custom logger -<br />
<br />
<b>const logger = require('customLogger').logger;</b><br />
<div>
<br /></div>
<div>
then you can mock this by -</div>
<div>
<br /></div>
<div>
<br /></div>
<div>
<pre class="brush: java">const mockedLogger = {
logger : {
log: function(message) {
console.log("message: " + message);
}
}
}
mockRequire('custom-logger', mockedLogger);
</pre>
</div>
<br />
This could be a network service or a database query. You can mock it as per your requirement.<br />
<br />
<h4 style="text-align: left;">
Related Links</h4>
<div style="text-align: left;">
</div>
<ul style="text-align: left;">
<li><a href="http://opensourceforgeeks.blogspot.com/2019/02/how-to-write-mocha-and-chai-unit-tests.html" style="font-weight: normal;">How to write Mocha and Chai unit tests for your Node.js app?(OSFG)</a></li>
</ul>
</div>
<div>
</div>
<div>
<br /></div>
</div>
Aniket Thakurhttp://www.blogger.com/profile/07553743551249736583noreply@blogger.com0tag:blogger.com,1999:blog-5013829528944984059.post-76429583214825478842019-02-24T00:23:00.001-08:002019-02-24T00:23:42.753-08:00How to write Mocha and Chai unit tests for your Node.js app?<div dir="ltr" style="text-align: left;" trbidi="on">
<h4 style="text-align: left;">
Background</h4>
<div>
Testing is an important part of the development lifecycle. Testing can be of many types - unit testing, integration testing, manual testing, QA automation testing. In this tutorial, I am going to show how you can write unit tests for your Node.js application using Mocha and Chai frameworks. </div>
<div>
<br /></div>
<div>
Mocha is a javascript test framework and Chai is an assertion library. </div>
<div>
<br /></div>
<div>
<a href="https://mochajs.org/">Mocha</a> is a feature-rich JavaScript test framework running on Node.js and in the browser, making asynchronous testing simple and fun. Mocha tests run serially, allowing for flexible and accurate reporting while mapping uncaught exceptions to the correct test cases.</div>
<div>
<br /></div>
<div>
<a href="https://www.chaijs.com/">Chai</a> is a BDD / TDD assertion library for node and the browser that can be delightfully paired with any javascript testing framework.</div>
<div>
<br /></div>
<div>
<br /></div>
<h4 style="text-align: left;">
Sample Node.js App</h4>
<div>
Let's start by writing a simple Node.js app that does addition and subtraction and then we will see how we can write tests for it using Mocha and Chai.</div>
<div>
<br /></div>
<div>
Create a directory called mochatest and navigate to that directory using the following commands -</div>
<div>
<ul style="text-align: left;">
<li><b>mkdir mochatest</b></li>
<li><b>cd mochatest</b></li>
</ul>
</div>
<div>
Now initialize it as npm module using -</div>
<div>
<ul style="text-align: left;">
<li><b>npm init -y</b></li>
</ul>
<div class="separator" style="clear: both; text-align: center;">
<a href="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEjIRs9wR7DRvvvU3DU0g40v9OefArdJylTbgaN2sW2F3hmsXTc5jgrfPyygOgDqUcZxJdlMoue6nPPFqOxuMctH7Fkrm3tdI9-nJC1sFWDMLAqLCQ8uqbO_T69311oZh7s6Toy7fbmi9h6X/s1600/npm-init.png" imageanchor="1" style="margin-left: 1em; margin-right: 1em;"><img border="0" data-original-height="630" data-original-width="1092" height="368" src="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEjIRs9wR7DRvvvU3DU0g40v9OefArdJylTbgaN2sW2F3hmsXTc5jgrfPyygOgDqUcZxJdlMoue6nPPFqOxuMctH7Fkrm3tdI9-nJC1sFWDMLAqLCQ8uqbO_T69311oZh7s6Toy7fbmi9h6X/s640/npm-init.png" width="640" /></a></div>
<div>
<br /></div>
</div>
<div>
<br /></div>
<div>
<br /></div>
<div>
You can see the package.json content initialized with default values. Now let's install our dependencies - mocha, and chai. Execute following command -</div>
<div>
<br /></div>
<div>
<ul style="text-align: left;">
<li><b>npm install mocha chai --save-dev</b></li>
</ul>
</div>
<div>
Notice we are saving it as dev dependency and not actual dependency since we need this for testing only.</div>
<div>
<br /></div>
<div class="separator" style="clear: both; text-align: center;">
<a href="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEiwqnyGuYVh6rmSpAEuGl2Q_DdUzdT0bAL1Yzhqu-WHq9LfBRRWTLU_Kn6_ZgwgcgMuA0yIcJGtZ10HI72acQ1QM8d2mNdKtFSNgarcE7Ai7T9YO_gH_FqfZZEYuwwNb0PSOQ_IvOsXjOVi/s1600/npminstall.png" imageanchor="1" style="margin-left: 1em; margin-right: 1em;"><img border="0" data-original-height="630" data-original-width="1092" height="368" src="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEiwqnyGuYVh6rmSpAEuGl2Q_DdUzdT0bAL1Yzhqu-WHq9LfBRRWTLU_Kn6_ZgwgcgMuA0yIcJGtZ10HI72acQ1QM8d2mNdKtFSNgarcE7Ai7T9YO_gH_FqfZZEYuwwNb0PSOQ_IvOsXjOVi/s640/npminstall.png" width="640" /></a></div>
<div>
<br /></div>
<div>
<br /></div>
<div>
<br /></div>
<div>
This should create a node_module directory in your current <b>mochatest </b>directory and install your dependencies there. You can also see dependencies added in package.json.</div>
<div>
<br /></div>
<div class="separator" style="clear: both; text-align: center;">
<a href="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEiOltxFn0WpKyRcWvkTMdMvr076xnqa0qFzReh5L1DFkwFEzsJfJxM0rxY2FQdOKrlI8RJBE1IBpv3xoza4pli4T4A3k0UF8fBhIF7SJD6VeZz-KVecu4xuVtGwW7j8SlPJvbgint2Fu7Yz/s1600/npminstpack.png" imageanchor="1" style="margin-left: 1em; margin-right: 1em;"><img border="0" data-original-height="630" data-original-width="1092" height="368" src="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEiOltxFn0WpKyRcWvkTMdMvr076xnqa0qFzReh5L1DFkwFEzsJfJxM0rxY2FQdOKrlI8RJBE1IBpv3xoza4pli4T4A3k0UF8fBhIF7SJD6VeZz-KVecu4xuVtGwW7j8SlPJvbgint2Fu7Yz/s640/npminstpack.png" width="640" /></a></div>
<div>
<br /></div>
<div>
<br /></div>
<div>
Now let's create our main app. You can see in the package.json above the main file is called index.js. At this point, I would request you to open your application in your favorite IDE. I will be using visual studio code for this. </div>
<div>
<br /></div>
<div>
Now create a file called index.js in <b>mochatest </b>folder. and add the following content to it</div>
<div>
<br /></div>
<div>
<br /></div>
<div>
<pre class="brush: java">var addition = function(a,b) {
return a + b;
}
var subtraction = function(a,b) {
return a - b;
}
module.exports = {
add: addition,
subtract: subtraction
}
</pre>
</div>
<div>
<br /></div>
<div>
This essentially exports 2 functions -</div>
<div>
<ul style="text-align: left;">
<li>add </li>
<li>subtract</li>
</ul>
<div>
that does exactly what the name says - adds and subtracts two numbers. Now let's see how we can write mocha tests for these.<br />
<br />
<br /></div>
</div>
<div>
<h4 style="text-align: left;">
How to write Mocha and Chai unit tests for your Node.js app?</h4>
</div>
<div>
In the <b>mochatest </b>folder create a folder called <b>test</b>. We will have test files in this folder. It is recommended to have same file structure as your actual app. Since we just have a single file called index.js in our app, create a file called <b>indexTest.js </b>in your test folder and add following content to it.</div>
<div>
<br /></div>
<div>
<br /></div>
<pre class="brush: java">const assert = require('chai').assert;
const index = require("../index");
describe("Index Tests", function(){
describe("Addition", function(){
it("Addition functionality test", function() {
let result = index.add(4,5);
assert.equal(result,9);
});
it("Addition return type test", function() {
let result = index.add(4,5);
assert.typeOf(result,'number');
});
});
describe("Subtraction", function(){
it("Subtraction functionality test", function() {
let result = index.subtract(5,4);
assert.equal(result,1);
});
it("Subtraction return type test", function() {
let result = index.subtract(5,4);
assert.typeOf(result,'number');
});
});
});
</pre>
<div>
<br /></div>
<div>
Let me explain this before we go and test this out. Like I mentioned before chai is an assertion library, so we get a reference to it. Then you get a reference to the actual app file - index.js. Remember it exports two functions -<br />
<br />
<ul style="text-align: left;">
<li>add</li>
<li>subtract</li>
</ul>
<div>
Then we have "<b class="">describe"</b> keyword. Each <b class="">describe</b> is a logical grouping of tests and you can cascade them further. For example in the above case, we start a grouping on the basis if file meaning these group has tests for file index.js. Inside it, we have cascaded describe for each method - add and subtract. Each "<b class="">describe</b>" takes 2 arguments - 1st one is the string that defines what the grouping is for and the 2nd one is the function that has the logic of what that group does. It could have other subgroups as you see above.</div>
<div>
<br /></div>
<div>
Inside describe you can define actual tests inside "<b>it" </b>method. This method also takes 2 arguments - 1st one says what the test does and the 2nd one is a function that gets executed to test it. Inside it we use the assert reference we got from chai module. In this case, we have used</div>
<div>
<ul style="text-align: left;">
<li>equal</li>
<li>typeof</li>
</ul>
<div>
You can see others in <a href="https://www.chaijs.com/guide/styles/">https://www.chaijs.com/guide/styles/</a></div>
</div>
</div>
<div>
<br /></div>
<div>
<br /></div>
<div>
<br /></div>
<div>
<b>NOTE</b>: By default, mocha looks for the glob <b>"./test/*.js</b><b>"</b>, so you may want to put your test methods in <b>test</b>/ folder.</div>
<div>
<br /></div>
<div>
Now let's run it. Use the following command -<br />
<br />
<br />
<ul style="text-align: left;">
<li>mocha</li>
</ul>
<div class="separator" style="clear: both; text-align: center;">
<a href="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEiHko8H1RyfBhjsX8ze2_VQzcBr61r7bQjXwfceMo3WDac5GgaB-JL68vmFl2iWtzYHYrd2KHRqx3-m1MNXyommbN_vjt96xZI_pwPSUr3gUzujtXF8UvwOIZQ8tsGQf9ubC5pC5hkKmxCv/s1600/result.png" imageanchor="1" style="margin-left: 1em; margin-right: 1em;"><img border="0" data-original-height="630" data-original-width="1092" height="368" src="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEiHko8H1RyfBhjsX8ze2_VQzcBr61r7bQjXwfceMo3WDac5GgaB-JL68vmFl2iWtzYHYrd2KHRqx3-m1MNXyommbN_vjt96xZI_pwPSUr3gUzujtXF8UvwOIZQ8tsGQf9ubC5pC5hkKmxCv/s640/result.png" width="640" /></a></div>
<div>
<br /></div>
<br />
<br />
<br /></div>
<div>
And you can see the results. You can change the logic in index.js to see that tests fail. For example, lets change add method to return a-b instead of a+b and rerun this test. You will see the following output -<br />
<br />
<div class="separator" style="clear: both; text-align: center;">
<a href="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEgAm6J33Zn4SnRzRnLAuSbBB2E5-xGh7sJpy9_lLigle58r5LtQlkXC19FiOupYoG67kcvaNDpYxg3A0c1gxvNg7giWcATFUpgcWtsz0B_nQ0re8SBp1tgwtiVxRkxaC9rojdUl6jwUrwMs/s1600/failres.png" imageanchor="1" style="margin-left: 1em; margin-right: 1em;"><img border="0" data-original-height="702" data-original-width="1092" height="410" src="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEgAm6J33Zn4SnRzRnLAuSbBB2E5-xGh7sJpy9_lLigle58r5LtQlkXC19FiOupYoG67kcvaNDpYxg3A0c1gxvNg7giWcATFUpgcWtsz0B_nQ0re8SBp1tgwtiVxRkxaC9rojdUl6jwUrwMs/s640/failres.png" width="640" /></a></div>
<br />
Finally, let's plug this in the npm system. package.json already has <b>test script </b>as follows -<br />
<br />
<pre class="brush: java"> "scripts": {
"test": "echo \"Error: no test specified\" && exit 1"
},
</pre>
<br />
<br />
change this to<br />
<br />
<br />
<pre class="brush: java"> "scripts": {
"test": "mocha"
},
</pre>
<br />
<br />
and you can simply run following command to execute tests -<br />
<br />
<ul style="text-align: left;">
<li><b>npm run test</b></li>
</ul>
<br />
<div class="separator" style="clear: both; text-align: center;">
<a href="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEjK8Xc6GNbtQfLPCcqrbYXo3qeEAYkAtHluOV7EB8bF80lB2y8p-mT9ugUcvCptkac7El21btNTfPTiPcasW2AN1W0V_-P0WlPeOoYPsBoGct5oV3B0HhhketL-nVy-bTkOvFHYMYR7IrbO/s1600/resnpm.png" imageanchor="1" style="margin-left: 1em; margin-right: 1em;"><img border="0" data-original-height="534" data-original-width="1032" height="330" src="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEjK8Xc6GNbtQfLPCcqrbYXo3qeEAYkAtHluOV7EB8bF80lB2y8p-mT9ugUcvCptkac7El21btNTfPTiPcasW2AN1W0V_-P0WlPeOoYPsBoGct5oV3B0HhhketL-nVy-bTkOvFHYMYR7IrbO/s640/resnpm.png" width="640" /></a></div>
<br />
<br /></div>
<div>
Let me know if you have any questions. Thanks.</div>
<div>
<br /></div>
<div>
<br /></div>
<h4 style="text-align: left;">
Related Links</h4>
<div>
<ul style="text-align: left;">
<li><a href="https://mochajs.org/">https://mochajs.org/</a></li>
<li><a href="https://www.chaijs.com/">https://www.chaijs.com/</a></li>
</ul>
</div>
<div>
<br /></div>
<div>
<br /></div>
</div>
Aniket Thakurhttp://www.blogger.com/profile/07553743551249736583noreply@blogger.com0tag:blogger.com,1999:blog-5013829528944984059.post-76844200543585138892019-01-27T22:51:00.001-08:002019-01-29T01:35:17.065-08:00Sorting Techniques<div dir="ltr" style="text-align: left;" trbidi="on">
<h4 style="text-align: left;">
Background</h4>
<div>
This post summarises various sorting techniques.</div>
<div>
<br /></div>
<div class="separator" style="clear: both; text-align: center;">
<a href="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEh9H8Yx34SrMmgUdr2pz9CqhMDM5ZgyZQ1UvUJ182hYjAXzsO7GoQCqdjowg0v0pR8Dct4ZUXTIB3wTgckBrVa_36Y3lKm168lze96_LJ5i1DhWh2EqFJ9V5u45GedTgewZc3ojMfS2mR4V/s1600/sorting.png" imageanchor="1" style="margin-left: 1em; margin-right: 1em;"><img border="0" data-original-height="810" data-original-width="1102" height="470" src="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEh9H8Yx34SrMmgUdr2pz9CqhMDM5ZgyZQ1UvUJ182hYjAXzsO7GoQCqdjowg0v0pR8Dct4ZUXTIB3wTgckBrVa_36Y3lKm168lze96_LJ5i1DhWh2EqFJ9V5u45GedTgewZc3ojMfS2mR4V/s640/sorting.png" width="640" /></a></div>
<div>
<br /></div>
<h4 style="text-align: left;">
Sorting Techniques</h4>
<div>
I have written posts over time to show the implementation of some of the sorting techniques. Following are links to the same -</div>
<div>
<ul style="text-align: left;">
<li><a href="http://opensourceforgeeks.blogspot.com/2014/02/bubble-sort-in-java.html">Bubble Sort</a></li>
<li><a href="http://opensourceforgeeks.blogspot.com/2014/02/insertion-sort-in-java.html">Insertion Sort</a></li>
<li><a href="http://opensourceforgeeks.blogspot.com/2014/02/code-import-java.html">Merge Sort</a></li>
<li><a href="http://opensourceforgeeks.blogspot.com/2014/02/code-import-java_21.html">Quick Sort</a></li>
<li><a href="http://opensourceforgeeks.blogspot.com/2014/02/counting-sort-in-java.html">Counting Sort</a></li>
<li><a href="http://opensourceforgeeks.blogspot.com/2014/03/heapsort-in-java.html">HeapSort</a></li>
</ul>
</div>
<div>
<br /></div>
<h4 style="text-align: left;">
Related Links</h4>
<div>
<ul style="text-align: left;">
<li><a href="http://bigocheatsheet.com/">http://bigocheatsheet.com/</a></li>
<li><a href="http://opensourceforgeeks.blogspot.com/2014/02/sort-stack-using-recursion-in-java.html">Sort a stack using recursion in Java(OSFG)</a></li>
</ul>
</div>
</div>
Aniket Thakurhttp://www.blogger.com/profile/07553743551249736583noreply@blogger.com0tag:blogger.com,1999:blog-5013829528944984059.post-69725383201722286402019-01-27T04:28:00.000-08:002019-01-27T04:28:52.479-08:00What is transient keyword in Java?<div dir="ltr" style="text-align: left;" trbidi="on">
<h4 style="text-align: left;">
Background</h4>
<div>
In one of my earlier post, I had covered what serialization in Java is and how transient keyword can be used in that context. You can take a look at that post -</div>
<div>
<ul style="text-align: left;">
<li><a href="http://opensourceforgeeks.blogspot.com/2014/01/serialization-in-java.html">Serialization in Java</a></li>
</ul>
<div>
We saw that in serialization context, instance variables marked as transient will not be serialized and on deserialization, they get the default values. In this post, we will see some more details about transient keyword with an example.</div>
</div>
<div>
<br /></div>
<h4 style="text-align: left;">
Transient use cases</h4>
<div>
<ul style="text-align: left;">
<li>The transient keyword should be used when you do not want to serialize your instance variables. Eg.</li>
<ul>
<li>An instance of Logger class. There is no state associated with a logger instance, so we do not need to serialize it.</li>
<li>Similarly, any secure data like passwords, which you may not want to serialize.</li>
</ul>
<li>You cannot use any classes in the JDK that does not implement Serializable as references in your class that is Serializable. It needs to be marked transient. Else it will throw <b>âjava.io.NotSerializableExceptionâ</b> exception.</li>
</ul>
<div>
<br /></div>
</div>
<div>
<h4>
The transient and final keyword</h4>
</div>
<div>
Transient treats final keyword a bit differently. So let's take an example to understand this,</div>
<div>
<br /></div>
<div>
<pre class="brush: java">//final field 1
public final transient String myName = "Aniket";
//final field 2
public final transient Logger myLogger = LoggerFactory.getLogger(MyClass.class.getName());
</pre>
<div>
<br /></div>
<div>
If you consider above fields in a class, by our above logic they should not be serialized since they are marked as transient. However, if any final variable is evaluated as a "constant expression" like in case of <b>myName </b>above, it will be serialized. So in above case <b>myName </b>is serialized and <b class="gr-progress">myLogger </b>is not.</div>
<div>
<br /></div>
<div>
On the side note, recall <b>serialVersionUID </b>which is static and final. It is the only static variable that gets serialized. static instances do not form the state of the object, so by very definition of serialization, it is not serialized.</div>
<div>
<br /></div>
<div>
<h4 style="text-align: left;">
Use of transient keyword in HashMap.</h4>
</div>
<div>
If you see HashMap implementation you can see the array that backs it is marked as transient.</div>
<div>
<br /></div>
<div>
<br /></div>
<pre class="brush: java"> /**
* The table, resized as necessary. Length MUST Always be a power of two.
*/
transient Entry[] table;
</pre>
<div>
<br /></div>
<div>
<br /></div>
<div>
If this array is not serialized, how does it get deserialized back to restore instance state? Class does implement serializable -</div>
<div>
<br /></div>
<pre class="brush: java">public class HashMap<K,V> extends AbstractMap<K,V>
implements Map<K,V>, Cloneable, Serializable {
private static final long serialVersionUID = 362498820763181265L;
</pre>
<div>
<br /></div>
<div>
<br /></div>
<div>
Reason for this is that two instances of same class do not generate the same hashcode (unless of course, you override the hashcode method to do so). The native implementation uses the objects memory location which will be different for the object before serialization and after deserialization. So it is not guaranteed that the objects will be in the same bucket and in the same location as that of hashmap that was serialized. This is why the array itself is not serialized by marking it as transient. So how is the instance state restored? </div>
<div>
<br /></div>
<div>
For this in HashMap implementation, they override writeObject and readObject method. In the writeObject method, all entries from the entry array are read in a sequence and serialized. Similarly, in readObject for deserialization, it is read in the same order and then stored in its own internal entry table array. So the buckets and position are dynamically calculated during deserialization with the same data.</div>
<div>
<br /></div>
<div>
PS: This is a good interview question :)</div>
<div>
<br /></div>
<div>
<br /></div>
<div>
<br /></div>
<h4 style="text-align: left;">
Related Links</h4>
<div>
<ul style="text-align: left;">
<li><a href="http://opensourceforgeeks.blogspot.com/2014/01/serialization-in-java.html">Serialization in Java(OSFG)</a></li>
</ul>
</div>
</div>
</div>
Aniket Thakurhttp://www.blogger.com/profile/07553743551249736583noreply@blogger.com0tag:blogger.com,1999:blog-5013829528944984059.post-63166984442955746222019-01-19T00:40:00.002-08:002019-01-19T00:40:54.368-08:00How to print odd and even numbers in order with two threads<div dir="ltr" style="text-align: left;" trbidi="on">
<h4 style="text-align: left;">
Background</h4>
<div>
Let us say you have two threads - one thread prints even numbers and other one prints odd numbers. You need to design this in such a way that all the numbers are printed in the natural order i.e 1,2,3,4 etc. </div>
<div>
<br /></div>
<div>
This is more of a synchronization questions rather than a data structure question. You need to understand how threads, synchronization works in order to be able to solve this question. </div>
<div>
<br /></div>
<h4 style="text-align: left;">
How to print odd and even numbers in order with two threads</h4>
<div>
We can do this two ways -</div>
<div>
<ol style="text-align: left;">
<li>Using <b>Sempahores</b></li>
<li>Using <b>wait and notify</b></li>
</ol>
<div>
<br /></div>
</div>
<div>
Let us see how we can do this using semaphores -</div>
<div>
<br /></div>
<pre class="brush: java">public static void withSemaphores() throws InterruptedException, ExecutionException {
Semaphore oddLock = new Semaphore(1);
Semaphore evenLock = new Semaphore(0);
Runnable printOdd = () -> {
for (int i = 1; i < 10; i = i + 2) {
try {
oddLock.acquire();
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
;
System.out.println(i);
evenLock.release();
}
};
Runnable printEven = () -> {
for (int i = 2; i < 10; i = i + 2) {
try {
evenLock.acquire();
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
System.out.println(i);
oddLock.release();
}
};
new Thread(printOdd).start();
new Thread(printEven).start();
}
</pre>
<div>
<br /></div>
<div>
<br /></div>
<div>
Before we see how this is actually working you need to understand how semaphores work. They essentially are like permits. You can initialize the semaphore with the initial permits. Let us say semaphore has 2 permits, to begin with. In this case, 2 threads can acquire these permits. The 3rd thread which comes has to wait till one of the 2 permits become available again. Threads that have acquired the permits can release them once they are done. Permits are acquired by <b class="">acquire</b><b>()</b> method and released by<b> release()</b> method. To read more about Semaphores you can refer a post I had written earlier -</div>
<div>
<ul style="text-align: left;">
<li><a href="http://opensourceforgeeks.blogspot.com/2017/06/counting-semaphore-countdownlatch.html">Counting Semaphore, CountDownLatch, CyclicBarrier - synchronization methods for concurrency</a></li>
</ul>
</div>
<div>
<br /></div>
<div>
Also, note I have used Java 8 lambda syntax in the code above. You can read more about lambds -</div>
<div>
<ul style="text-align: left;">
<li><a href="http://opensourceforgeeks.blogspot.com/2016/02/using-lambda-expressions-from-java-8.html">Using Lambda Expressions from Java 8</a></li>
</ul>
</div>
<div>
Now with this understanding let's see how the above logic works.</div>
<div>
<br /></div>
<div>
<br /></div>
<div>
<b class="">printOdd</b> runnable is responsible for printing odd numbers whereas <b>printEven</b> prints even number. For loop is designed in such a way and it increments by 2 to continue printing respective numbers. We need to start with 1 which is odd, so old thread starts first. Notice we have 2 semaphores - one for odd and one for even. Odd semaphore has 1 permit whereas even semaphore has 0, to begin with. The odd thread can get the permit from an odd semaphore and print the odd value which is 1. Meanwhile, the even thread will get blocked since no permits are available for even semaphore. Only when an odd thread releases even semaphore permit, even thread will go ahead and print 2. That's how each thread locks each other till numbers are printed in sequence.</div>
<div>
<br /></div>
<div>
You can do the same with the wait and notify. You can see both of the above methods on my GitHub repository on data structures - <a href="https://github.com/aniket91/DataStructures/blob/master/src/com/osfg/questions/PrintOddEven.java">https://github.com/aniket91/DataStructures/blob/master/src/com/osfg/questions/PrintOddEven.java</a> </div>
<div>
<br /></div>
<div>
<br /></div>
<h4 style="text-align: left;">
Related Links</h4>
<div>
<ul>
<li><a href="http://opensourceforgeeks.blogspot.com/2017/06/counting-semaphore-countdownlatch.html">Counting Semaphore, CountDownLatch, CyclicBarrier - synchronization methods for concurrency(OSFG)</a></li>
<li><a href="http://opensourceforgeeks.blogspot.com/2016/02/using-lambda-expressions-from-java-8.html">Using Lambda Expressions from Java 8(OSFG)</a></li>
<li><a href="https://github.com/aniket91/DataStructures">https://github.com/aniket91/DataStructures</a></li>
</ul>
</div>
</div>
Aniket Thakurhttp://www.blogger.com/profile/07553743551249736583noreply@blogger.com0tag:blogger.com,1999:blog-5013829528944984059.post-89266753276933448822019-01-17T05:26:00.000-08:002019-01-17T05:34:06.446-08:00How to use Callable interface with Threads in Java?<div dir="ltr" style="text-align: left;" trbidi="on">
<h4 style="text-align: left;">
Background</h4>
<div>
In one of the previous posts on <a href="https://opensourceforgeeks.blogspot.com/2017/01/creating-threads-with-executorservice.html">Creating Threads with Executor service</a>, we saw an interface called Callable. Executor has a method called submit that took Callable object and returned a future object which had the results. Unlike the Runnable interface, we can use Callable interface to return the result or throw checked Exceptions. In this post, we will see how to use Callable interface with plain Thread construct.</div>
<div>
<br /></div>
<h4 style="text-align: left;">
How to use Callable interface with Threads in Java?</h4>
<div>
We know that Thread takes Runnable interface only. No surprises there. So we cannot directly use objects implementing the Callable interface. Also to get the result we need Future object as we saw in Executors. Remember any design pattern that suits this use case? yes, it is <a href="https://opensourceforgeeks.blogspot.com/2015/02/adapter-and-facade-design-patterns-in.html">Adapter Pattern</a>. Java provides a class called FutureTask which implements Runnable and Future, combining both functionalities conveniently. Let's see an example of how we can do this -</div>
<div>
<br />
package com.osfg;<br />
<br />
import java.util.concurrent.Callable;<br />
import java.util.concurrent.ExecutionException;<br />
import java.util.concurrent.FutureTask;<br />
<br />
<br />
<pre class="brush: java">public class Test {
public static void main(String args[]) throws InterruptedException, ExecutionException {
Callable<String> callable = () -> {
Thread.sleep(5000);
return "Hello!";
};
FutureTask<String> futureTask = new FutureTask<>(callable);
Thread t = new Thread(futureTask);
t.start();
while (!futureTask.isDone()) {
System.out.println("Task not done yet!");
Thread.sleep(1000);
}
System.out.println(futureTask.get());
}
}
</pre>
<br />
<div>
<br /></div>
<br />
<br />
You can see here that our Callable waits for 5 seconds and returns the results. And in the main thread, we do a check every 1 second to see if the result is available in the FutureTask. So if you run above code you will get -</div>
<div>
<br /></div>
<div>
<div>
<b>Task not done yet!</b></div>
<div>
<b>Task not done yet!</b></div>
<div>
<b>Task not done yet!</b></div>
<div>
<b>Task not done yet!</b></div>
<div>
<b>Task not done yet!</b></div>
<div>
<b>Hello!</b></div>
</div>
<div>
<br /></div>
<div>
FutureTask has following methods -<br />
<br />
<ul style="text-align: left;">
<li><b>public boolean cancel(boolean mayInterrupt):</b> Used to stop the task. It stops the task if it has not started. If it has started, it interrupts the task only if mayInterrupt is true.</li>
<li><b>public Object get() throws InterruptedException, ExecutionException</b>: Used to get the result of the task. If the task is complete, it returns the result immediately, otherwise, it waits until the task is complete and then returns the result.</li>
<li><b>public boolean isDone():</b> Returns true if the task is complete and false otherwise</li>
</ul>
</div>
<div>
<br /></div>
<h4 style="text-align: left;">
Related Links</h4>
<div>
<ul style="text-align: left;">
<li><a href="https://opensourceforgeeks.blogspot.com/2017/01/creating-threads-with-executorservice.html">Creating Threads with Executor service(OSFG)</a></li>
<li><a href="https://opensourceforgeeks.blogspot.com/2015/02/adapter-and-facade-design-patterns-in.html">Adapter and Facade Design Patterns in Java(OSFG)</a></li>
</ul>
</div>
</div>
Aniket Thakurhttp://www.blogger.com/profile/07553743551249736583noreply@blogger.com0tag:blogger.com,1999:blog-5013829528944984059.post-14289798355195672202018-12-30T23:06:00.003-08:002018-12-30T23:06:50.956-08:00How to write your own attribute directive in Angular?<div dir="ltr" style="text-align: left;" trbidi="on">
<h4 style="text-align: left;">
Background</h4>
<div>
In the last post, we saw how to use structural directives like <b>*ngIf </b>and <b>*</b><b>ngFor</b> that can be used to modify DOM elements. </div>
<div>
<ul style="text-align: left;">
<li><a href="http://opensourceforgeeks.blogspot.com/2018/12/using-structural-directives-in-angular.html">Using structural directives in Angular</a></li>
</ul>
</div>
<div>
Attribute directives can change the appearance or behavior of an element, component, or another directive. In this post, I am going to show you how to write your own attribute directives in Angular.</div>
<div>
<br /></div>
<div>
For this, we are going to create a directive which on single click will enlarge our text and on double click get it back to original size. </div>
<div>
<br /></div>
<h4 style="text-align: left;">
How to write your own attribute directive in Angular?</h4>
<div>
Let's start by writing our directive class file. Under the app folder create a new file called <b>enlarge.directive.ts. </b>In this file add following code -</div>
<div>
<br /></div>
<div>
<br /></div>
<pre class="brush: java">import { Directive, ElementRef, HostListener, Input, Renderer2 } from '@angular/core';
@Directive({
selector: '[appEnlarge]'
})
export class EnlargeDirective {
constructor(private el: ElementRef, private renderer: Renderer2) { }
@Input('appEnlarge') appEnlargeSize: string;
@HostListener('click') onclick() {
this.enlarge( this.appEnlargeSize || '100px');
}
@HostListener('dblclick') ondblclick() {
this.enlarge('50px');
}
private enlarge(enlargeSize: string) {
this.renderer.setStyle(this.el.nativeElement, 'font-size', enlargeSize);
}
}
</pre>
<div>
<br /></div>
<div>
<br /></div>
<div>
Let's go over this code and try to understand what we are doing here. 1st line has a couple of imports that we will understand as we go ahead. Next line has an annotation called @Directive which states that this class is a directive and its selector is appEnlarge. So you could use this directive as follows -</div>
<div>
<ul style="text-align: left;">
<li><b><p appEnlarge>Directive applied for this content!</p></b></li>
</ul>
</div>
<div>
We will see this in action in some time. Next, we have a constructor where we have access to the native element and the renderer. We can use APIs from renderer or Native element to actually make changes to the element.</div>
<div>
<br /></div>
<div>
Next, we have an input called <b>appEnlargeSize. </b>Here the user can specify how much the context needs to be enlarged. Notice how we have used an alias here in the bracket. This is so that we could specify input and directive in the same binding as below -</div>
<div>
<ul style="text-align: left;">
<li><b><p [appEnlarge]="'120px'">Directive applied for this content!</p></b></li>
</ul>
</div>
<div>
Then we are using HostListener APIs for single and double click to actually do our transformation - which is increasing the font size. You can see all HostListener APIs here -</div>
<div>
<ul style="text-align: left;">
<li><a href="https://angular.io/api/core/HostListener">https://angular.io/api/core/HostListener</a></li>
</ul>
</div>
<div>
Notice how in enlarge function we have used renderer API of setStyle to apply our desired style. You can see all renderer2 APIs here -</div>
<div>
<ul style="text-align: left;">
<li><a href="https://angular.io/api/core/Renderer2">https://angular.io/api/core/Renderer2</a></li>
</ul>
</div>
<div>
<br /></div>
<div>
Now that your directive is done let's import it and declare it in our main module. Go to <b>app.module.ts </b> and import it. Also, add it in the declaration section. Your app module should look like below -</div>
<div>
<br /></div>
<pre class="brush: java">import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';
import { AppRoutingModule } from './app-routing.module';
import { AppComponent } from './app.component';
import {EnlargeDirective} from './enlarge.directive'
@NgModule({
declarations: [
AppComponent,
EnlargeDirective
],
imports: [
BrowserModule,
AppRoutingModule
],
providers: [],
bootstrap: [AppComponent],
})
export class AppModule { }
</pre>
<div>
<br /></div>
<div>
And that's it. Save all your changes and start your angular app using -</div>
<div>
<ul style="text-align: left;">
<li><b>ng serve</b></li>
</ul>
<div>
Go to <a href="http://localhost:4200/">http://localhost:4200/</a> and see your changes.</div>
</div>
<div>
<br /></div>
<div>
Single click on the text to enlarge it and double click it to bring it to its original size.<br />
<br />
<div class="separator" style="clear: both; text-align: center;">
<a href="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEgQgnJ5d3d4M07gzssQoweOW3RkCcx54QGpJF0JCg8WVy6NMH6TeJ6zHvrZJP2-mx3WcjjkWjdpaNcREud8X8cAxWHz1XdduzBv3ezNW6azdKchItZyv0kjS9gY6VUUUoMXVRRYcmAcwH9O/s1600/1.png" imageanchor="1" style="margin-left: 1em; margin-right: 1em;"><img border="0" data-original-height="588" data-original-width="1345" height="276" src="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEgQgnJ5d3d4M07gzssQoweOW3RkCcx54QGpJF0JCg8WVy6NMH6TeJ6zHvrZJP2-mx3WcjjkWjdpaNcREud8X8cAxWHz1XdduzBv3ezNW6azdKchItZyv0kjS9gY6VUUUoMXVRRYcmAcwH9O/s640/1.png" width="640" /></a></div>
<br />
<div class="separator" style="clear: both; text-align: center;">
<a href="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEj1257RcIkg73-obFpeg1Z1k0LiTKPb-QBbAMV1D7IpijkBjdJaOvMCPU33Rh5hTDSIhN4kxsUN19ngniy2KUQ-6JGLz5UG-9ELu06ePn1WxeByqdWI44hiHQ6ulI4dUz4XR0VEXJRAplBW/s1600/2.png" imageanchor="1" style="margin-left: 1em; margin-right: 1em;"><img border="0" data-original-height="588" data-original-width="1345" height="278" src="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEj1257RcIkg73-obFpeg1Z1k0LiTKPb-QBbAMV1D7IpijkBjdJaOvMCPU33Rh5hTDSIhN4kxsUN19ngniy2KUQ-6JGLz5UG-9ELu06ePn1WxeByqdWI44hiHQ6ulI4dUz4XR0VEXJRAplBW/s640/2.png" width="640" /></a></div>
<br /></div>
<div>
<br /></div>
<div>
<br /></div>
<div>
<br /></div>
<div>
This is not a great example with perfect CSS and animation but I hope this gives you an idea of how you can write custom directives in angular. These are very powerful techniques to change the appearance of your components. Let me know if you have any questions. Thanks.<br />
<br />
<span style="background-color: blue;"><br /></span>
<span style="background-color: white; color: #38761d; font-size: large;">This is the last post of the year 2018 :). So wishing all a very happy new year! Hoping coming year would be more awesome with a lot of more learning and sharing!</span></div>
<div>
<br /></div>
<h4 style="text-align: left;">
Related Links</h4>
<div>
<ul style="text-align: left;">
<li><a href="https://angular.io/guide/attribute-directives">https://angular.io/guide/attribute-directives</a></li>
<li><a href="http://opensourceforgeeks.blogspot.com/2018/11/angular-hello-world-example.html">Angular Hello World example(OSFG)</a></li>
<li><a href="http://opensourceforgeeks.blogspot.com/2018/11/understanding-angular-application.html">Understanding angular application folder structure(OSFG)</a></li>
<li><a href="http://opensourceforgeeks.blogspot.com/2018/11/routing-and-navigation-in-angular.html">Routing and navigation in Angular(OSFG)</a></li>
<li><a href="http://opensourceforgeeks.blogspot.com/2018/11/building-nested-components-in-angular.html">Building nested components in Angular (OSFG)</a></li>
<li><a href="http://opensourceforgeeks.blogspot.com/2018/12/passing-data-between-nested-component.html">Passing data between the nested component in Angular(OSFG)</a></li>
<li><a href="http://opensourceforgeeks.blogspot.com/2018/12/how-to-customize-build-configuration.html">How to customize build configuration with custom webpack config in Angular CLI 6(OSFG)</a></li>
<li><a href="http://opensourceforgeeks.blogspot.com/2018/12/how-to-write-your-own-webpack-plugin.html">How to write your own webpack plugin?(OSFG)</a></li>
<li><a href="http://opensourceforgeeks.blogspot.com/2018/12/how-to-dynamically-create-component-in.html">How to dynamically create a component in Angular?(OSFG)</a></li>
</ul>
</div>
</div>
Aniket Thakurhttp://www.blogger.com/profile/07553743551249736583noreply@blogger.com0