<?xml version="1.0" encoding="utf-8" standalone="yes"?>
<rss version="2.0" xmlns:atom="http://www.w3.org/2005/Atom" xmlns:content="http://purl.org/rss/1.0/modules/content/">
  <channel>
    <title>Posts on Abdullah Diab&#39;s Blog</title>
    <link>https://mpcabd.xyz/post/</link>
    <description>Recent content in Posts on Abdullah Diab&#39;s Blog</description>
    <generator>Hugo</generator>
    <language>en-us</language>
    <lastBuildDate>Tue, 18 Aug 2026 09:13:47 +0000</lastBuildDate>
    <atom:link href="https://mpcabd.xyz/post/index.xml" rel="self" type="application/rss+xml" />
    <item>
      <title>One on One</title>
      <link>https://mpcabd.xyz/one-on-one/</link>
      <pubDate>Tue, 18 Aug 2026 09:13:47 +0000</pubDate>
      <guid>https://mpcabd.xyz/one-on-one/</guid>
      <description>You show up prepared, attentive, and honest for the meeting with your boss. There&amp;#39;s a far more important one on your calendar, it comes around a lot more often than you&amp;#39;d think, and what you get out of it makes any performance review look small.</description>
      <content:encoded><![CDATA[<p>The most important 1:1 meeting you can ever have, and you&rsquo;re absent.</p>
<p>We all know one-on-one meetings, I hope you do, it&rsquo;s a meeting where you meet your superior at work, where they check up on you, talk to you, give you guidance, listen to you, and take your requests for consideration. The talk that grows you in your career and guides you around the challenges you&rsquo;re facing at work. The talk that you feel safe having, I also hope so, because you know your superior wants what&rsquo;s best for you, you trust them, you trust their experience and knowledge, and you trust that from above they see and listen a bit more than you, and can foresee things you can&rsquo;t think of.</p>
<p>During that meeting, that call; how attentive are you? How carefully do you listen to absorb and understand every single word being said? How well do you speak? I believe you&rsquo;d be the most attentive in that call, and you&rsquo;d be trying to show the best version of yourself, even when complaining or asking for help and guidance. How often do you have that call? Once a week? Biweekly? Once a month?</p>
<p>Now let&rsquo;s take a look at the much more important one-on-one meeting you have, it&rsquo;s with a superior beyond superiors, high above every other rank you can ever imagine, it&rsquo;s with the Lord of Lords, the one who created you, who knows every single detail about you, and not only can He see you, He can see everyone else, He can listen to everyone else, He knows what&rsquo;s within you and everyone else.</p>
<p>If this were an Earthly lord you wouldn&rsquo;t even think of wishing to meet him once in your lifetime. This is different, in Islam you must meet your God five times every single day until the day you die. It&rsquo;s not an option to skip the call. You hear the call to prayer &ldquo;حي على الفلاح&rdquo; {Come forward to grab success}, you hear it five times a day.</p>
<p>You stand in front of your Creator, seventeen times a day across five different prayer times, you recite His words to you and to all mankind, you recite al-Fatiha. You thank Him for everything you have, الحمد لله رب العالمين {All praise is for Allah the Lord of all worlds}, you remind yourself that He is your Lord and everyone else&rsquo;s Lord, that He holds all your fates and knows all about you. You remind yourself that, knowing all that He knows about us, He is still the most merciful, الرحمن الرحيم {The most compassionate, the most merciful}, that despite all your wrongdoings He is still happy to have you back, to have you repent for your sins, that He still provides for you and for everyone else what you need to sustain your life as long as you&rsquo;re on Earth. You remember your actions, and others&rsquo; actions, you remember that you and they will stand one day to be judged by those actions, مالك يوم الدين {Master of the day of judgement}. You then refocus yourself, you go over your eternal oath, you remind yourself that it is He who you should serve and ask for help and guidance, إياك نعبد وإياك نستعين {You ˹alone˺ we worship and You ˹alone˺ we ask for help.}. This is an ongoing conversation, you just can&rsquo;t hear the response, but we were told about it. Allah says &ldquo;حمدني عبدي&rdquo; {My servant has thanked Me}, &ldquo;أثنى علي عبدي&rdquo; {My servant has lauded Me}, &ldquo;مجدني عبدي&rdquo; {My servant has glorified Me}, that&rsquo;s His answer to every sentence you said earlier.</p>
<p>Now you&rsquo;ve got to the moment, now you&rsquo;ve set up your heart and your mind, now you know what you want, it is now you ask &ldquo;اهدنا الصراط المستقيم&rdquo; {Guide us along the straight path}, because you know you need that guidance, you cannot go through life and its challenges without it, you need your superior&rsquo;s experience and knowledge to guide you every step of the way; otherwise, you&rsquo;re lost. You know the path you want to be guided to, you have seen examples of how other people thought they had the path and lost it, so you ask more specifically &ldquo;صراط الذين أنعمت عليهم ولا الضالين&rdquo; {The path of those You have blessed, not those You are displeased with, or those who are astray}. How does the conversation go further? To that, Allah replies &ldquo;هذا بيني وبين عبدي، هذا لعبدي ولعبدي ما سأل&rdquo; {This is between Me and My servant, and My servant will receive what he asks for}.</p>
<p>Can you imagine it? Have you thought about this conversation that you must have seventeen times a day across five different prayer times? It&rsquo;s a whole conversation, between you, your heart, your mind, and your God. Are you listening? Are you approaching your conversation with Him properly? It is He who guides you, it is He who provides for you, it is He who has your salvation, it is He who is the most merciful of all to you. This is the most important one-on-one meeting you can ever ask for, give it all you can, give it all your mind, all your soul, and you shall receive what you&rsquo;ve asked for.</p>
<p>Think about what&rsquo;s actually on the table. Your manager, however good, can only offer you what they know, filtered through their own time, their own mood, their own limits. Here you&rsquo;re standing before the One who knows what you haven&rsquo;t even figured out about yourself yet, who holds every door you think is closed, who can undo in a moment what you&rsquo;ve been stuck on for years. No deadline, no difficult project, no dreaded call with your boss carries that kind of weight, and none of them can give you that kind of return. Be present in it, truly present, say الله أكبر {Allah is greater} and mean it, and watch how small everything else you walked in with suddenly looks. That&rsquo;s not by accident, that&rsquo;s the whole point of standing there.</p>
<ul>
<li><a href="https://quran.com/al-fatihah">Read al-Fatiha</a></li>
<li><a href="https://www.youtube.com/watch?v=Ki2FMWn5GGI">Listen to al-Fatiha</a></li>
<li><a href="https://sunnah.com/muslim:395a">The conversation in al-Fatiha</a></li>
</ul>
]]></content:encoded>
    </item>
    <item>
      <title>In the celebration of 10M questions on StackOverflow</title>
      <link>https://mpcabd.xyz/in-the-celebration-of-10m-questions-on-stackoverflow/</link>
      <pubDate>Sat, 22 Aug 2015 15:06:15 +0000</pubDate>
      <guid>https://mpcabd.xyz/in-the-celebration-of-10m-questions-on-stackoverflow/</guid>
      <description>&lt;p&gt;Who among us developers doesn’t know &lt;a href=&#34;http://stackoverflow.com/&#34; target=&#34;_blank&#34;&gt;StackOverflow&lt;/a&gt;? If you don’t know it then there is a big chance you didn’t search for any programming related question in the last 7 years, so you either are doing a super great job, using a super old community of old school programmers, or actually didn’t practice programming for some really long time.&lt;/p&gt;
&lt;p&gt;StackOverflow reached more than 10 million questions, I won’t list those amazing numbers and statistics here, feel free to see them on &lt;a href=&#34;http://stackoverflow.com/10m&#34; target=&#34;_blank&#34;&gt;StackOverflow’s 10M page&lt;/a&gt;, they are really great to read and to try to imagine them.&lt;/p&gt;
&lt;p&gt;I’m not going to talk about its history, the internet is full of those articles, you can read about it from &lt;a href=&#34;https://en.wikipedia.org/wiki/Stack_Overflow&#34; target=&#34;_blank&#34;&gt;Wikipedia&lt;/a&gt; or from its co-founder &lt;a href=&#34;http://www.joelonsoftware.com/items/2008/09/15.html&#34; target=&#34;_blank&#34;&gt;Joel Spolsky&lt;/a&gt;. I will talk about my story and how I see StackOverflow in this occasion, it’s my way of celebrating the success of this global platform, and the success of humanity there.&lt;/p&gt;</description>
      <content:encoded><![CDATA[<p>Who among us developers doesn’t know <a href="http://stackoverflow.com/" target="_blank">StackOverflow</a>? If you don’t know it then there is a big chance you didn’t search for any programming related question in the last 7 years, so you either are doing a super great job, using a super old community of old school programmers, or actually didn’t practice programming for some really long time.</p>
<p>StackOverflow reached more than 10 million questions, I won’t list those amazing numbers and statistics here, feel free to see them on <a href="http://stackoverflow.com/10m" target="_blank">StackOverflow’s 10M page</a>, they are really great to read and to try to imagine them.</p>
<p>I’m not going to talk about its history, the internet is full of those articles, you can read about it from <a href="https://en.wikipedia.org/wiki/Stack_Overflow" target="_blank">Wikipedia</a> or from its co-founder <a href="http://www.joelonsoftware.com/items/2008/09/15.html" target="_blank">Joel Spolsky</a>. I will talk about my story and how I see StackOverflow in this occasion, it’s my way of celebrating the success of this global platform, and the success of humanity there.</p>
<h2 id="section1">My Story Before StackOverflow</h2>
<p>Feel free to skip to the <a href="#section2">next section</a> if you’re not interested in my personal history 🙂</p>
<p>When I first started my programming path, around year 1999, I had no internet, never even heard of it back then, we were living in the dark in Syria, anyway this is not the place for politics, so I started my programming path with no internet, and the only way I could get help was by searching through the thick book I was reading, I taught myself Visual Basic by reading the famous SAMS Teach Yourself Visual Basic 6 in 21 Days, and whenever I had any question back then I would try to find the answer there in that book, if I can’t find it I had no one to ask, I knew of no programmers then, my dad knew a bit of Visual Basic and he put me on the path of programming, but he couldn’t answer my questions as he was using it only for programming in Excel. In around 2001 I think we had our first dial-up connection, and it was bloody expensive, so I wasn’t allowed to use it, we’d use it very wisely, and couldn’t spend time wandering online, so I barely got to know any website for programmers.</p>
<p>Things started to get better by time, and I discovered <a href="http://www.codeproject.com/" target="_blank">CodeProject</a> – I think I was using MSN to search for stuff back then, I don’t remember when was the first time I used Google actually – and I was able to learn some extra good stuff, downloaded some Visual Basic projects, and I could understand them and learn. I also remember I was searching in Arabic a lot, my English wasn’t good enough back then, so I got to know some Arabic programming forums, and that was the way I was able to ask my questions, and many people were using those forums and would help me, I still remember <a href="http://arabteam2000-forum.com/" target="_blank">Arab Team 2000</a> as one of those leading forums back then. Then my path on .NET started and I found very nice Arabic content related to the new framework, I still remember me reading the books written by <a href="http://mhmdhmdy.blogspot.com" target="_blank">M. Hamdy Ghanem</a> and I remember me sending him lots of emails back in 2005 and 2006 asking about many different questions and he’d answer them all, also I remember reading the books of <a href="http://www.al-asiri.com/" target="_blank">Turki Al-Asiri</a> and checking his website which had a forum for questions and answers.</p>
<p>Right around 2006 I remember I found a website that was a community for those who are interested in computer science in Syria, it was called CSC-SY (<strong>C</strong>omputer <strong>SC</strong>ience <strong>– SY</strong>ria) and unfortunately it is not live anymore, it’s a long story why it’s not there anymore that involves politics too. On CSC-SY I was able to actually find a community that I fit it completely, many like-minded people all discussing computers, programming, algorithms, and all these stuff that I like, and actually discovering that community is the main reason that I entered the Informatics Engineering Faculty in Damascus University, because before that community I thought that people are still living in the dark in Syria. The forum on CSC-SY allowed me to ask a lot, and eventually I started answering a lot, and in a couple of years I became a moderator and then a manager of the forum, this was the place I hanged out everyday for at least 4 years.</p>
<p>Then in 2009 I joined StackOverflow and started finding answers to my questions there, and since then I’m a user of that platform and a part of that community.</p>
<p>Life before CSC-SY was hard, and it got way better when StackOverflow came into the picture, and now I can’t imagine the programming world without StackOverflow.</p>
<h2 id="section2">Together For a Better Life!</h2>
<p>I believe in paying the community back for the knowledge I get, in Islam we have the concept of <a href="https://en.wikipedia.org/wiki/Zakat" target="_blank">Zakat</a>, a great way of ensuring that each person contributes to the better of the community they live in, the contribution is based on what you have, and must be spent to those who need it and to make the whole community better. Many scholars have generalized this idea from money and valuable stocks to everything that can benefit the community, and knowledge is one of the biggest contributors to the prosperity of nations, and I believe that I have to pay back, to contribute, to pay it forward, too many names to one concept: <strong>Together For a Better Life!</strong>.</p>
<p>Now as a professional software developer I see that there are many ways for me to make life better, two main ways are in my opinion <strong>open source projects</strong> whether it is contributing to them, starting them, or maintaining them; the other one is <strong>spreading knowledge</strong> and that’s by me writing on my blog about the stuff I find interesting and might help someone, and by me answering questions on StackOverflow.</p>
<p>I’ve got some open source projects that I worked on or contributed to on my <a href="http://github.com/mpcabd" target="_blank">GitHub profile</a>, not much, but I try to keep it going, and whenever I see something that I can fix I don’t hesitate to fix it.</p>
<p>Also I don’t spend time on StackOverflow now the same way I used to spend time on CSC-SY, but that’s mainly because I’m now much busier than how I was 6 years ago, I only contributed around <a href="http://stackoverflow.com/users/99557/mpcabd?tab=answers" target="_blank">60 answers</a> now, but I try to open the site every couple of days and I check the questions there and try to help when I can.</p>
<p>In general I’m giving some time, even if it’s little, to the community of developers that I can benefit, and to the world by working on projects for a better life. I don’t think that I’ve covered my part of the Knowledge Zakat in any way, but I’m trying to cover more.</p>
<p>The community on StackOverflow and GitHub are paying it forward, keeping it going and making this world a better world to live in, everyone contributes amounts of knowledge and time, and no matter how small that amount is, the massive effect is really world changing, and the numbers on StackOverflow’s celebration page are a proof that humanity works together for the better of humanity itself.</p>
<p>So in the celebration of 10M questions on StackOverflow I would say: To humanity, to mankind, to life! Let’s all make it better! We’ve already done a great job! Let’s keep it going!</p>]]></content:encoded>
    </item>
    <item>
      <title>Verifying User Input – Thinking Outside The Box</title>
      <link>https://mpcabd.xyz/verifying-user-input-thinking-outside-the-box/</link>
      <pubDate>Fri, 31 Jul 2015 20:54:36 +0000</pubDate>
      <guid>https://mpcabd.xyz/verifying-user-input-thinking-outside-the-box/</guid>
      <description>&lt;p&gt;Now I’m not going to talk about user input validation, no that’s something that’s been covered a lot around the web, I’m going to talk about something else.&lt;/p&gt;
&lt;p&gt;Let’s imagine you are designing a game, where the user can create a puzzle, for example a maze, and you want to verify that what the user has input is a valid maze, that if played by another player that player will have a chance of winning it. Normally the solution that would come to your (and mine) mind is to try to solve that maze automatically – also we’re not going to talk about the different algorithms for solving mazes – but there is another way to do it that no one told us about in Algorithms 101!&lt;/p&gt;</description>
      <content:encoded><![CDATA[<p>Now I’m not going to talk about user input validation, no that’s something that’s been covered a lot around the web, I’m going to talk about something else.</p>
<p>Let’s imagine you are designing a game, where the user can create a puzzle, for example a maze, and you want to verify that what the user has input is a valid maze, that if played by another player that player will have a chance of winning it. Normally the solution that would come to your (and mine) mind is to try to solve that maze automatically – also we’re not going to talk about the different algorithms for solving mazes – but there is another way to do it that no one told us about in Algorithms 101!</p>
<p>Guess what! You can verify it manually! Yes Yes I know this is super smart right? No one thought about it!</p>
<img class="aligncenter wp-image-446 size-full" src="http://mpcabd.xyz/wp-content/uploads/2015/07/smart-language-blog.jpg" alt="So smart ... duh" width="310" height="232" srcset="https://mpcabd.xyz/wp-content/uploads/2015/07/smart-language-blog.jpg 310w, https://mpcabd.xyz/wp-content/uploads/2015/07/smart-language-blog-300x225.jpg 300w" sizes="(max-width: 310px) 100vw, 310px" />
<p>Come one enough kidding, but yes verifying it manually will save you a lot of work and complexity, and will also mean that other people will have a good chance (not very high necessarily) of solving the puzzle, let’s face it, if a backtracking algorithm is able to solve a puzzle it doesn’t mean that people will be able to do so too, it might be very hard for people to find that solution, so the point here is that by verifying the puzzle manually you can ensure you give people a better and fair chance.</p>
<img class="aligncenter size-full wp-image-447" src="http://mpcabd.xyz/wp-content/uploads/2015/07/JCLdMDveAn.png" alt="Ain't nobody got time for dat" width="310" height="256" srcset="https://mpcabd.xyz/wp-content/uploads/2015/07/JCLdMDveAn.png 310w, https://mpcabd.xyz/wp-content/uploads/2015/07/JCLdMDveAn-300x248.png 300w" sizes="(max-width: 310px) 100vw, 310px" />
<p>Of course I’m not telling you to verify it yourself, that would be nonsense, this is not 1990s, when you would afford verifying user input yourself after you throw it in some queue, now everything seems to be built for the masses and you can’t afford sparing your time or buying someone else’s time to do so. Then what am I talking about?!</p>
<p>Well the idea is not mine unfortunately, I saw the idea in the latest game by <a href="http://www.zeptolab.com/" target="_blank">Zeptolab</a>, an <a href="https://en.wikipedia.org/wiki/Massively_multiplayer_online_game" target="_blank">MMO</a> strategy game called <a href="http://www.zeptolab.com/games/king_of_thieves/" target="_blank">King Of Thieves</a>.<figure id="attachment_443" style="width: 300px" class="wp-caption aligncenter"></p>
<p><a href="http://mpcabd.xyz/wp-content/uploads/2015/07/Screenshot_2015-07-31-19-03-49.png" rel="lightbox[442]" title="Verifying User Input - Thinking Outside The Box"><img class="wp-image-443" src="http://mpcabd.xyz/wp-content/uploads/2015/07/Screenshot_2015-07-31-19-03-49-300x169.png" alt="King Of Thieves Splash Screen" width="300" srcset="https://mpcabd.xyz/wp-content/uploads/2015/07/Screenshot_2015-07-31-19-03-49-300x169.png 300w, https://mpcabd.xyz/wp-content/uploads/2015/07/Screenshot_2015-07-31-19-03-49-1024x576.png 1024w" sizes="(max-width: 300px) 100vw, 300px" /></a><figcaption class="wp-caption-text">King Of Thieves Splash Screen © 2015 Zeptolab</figcaption></figure></p>
<p>In this game you have a dungeon and a chest of gold and some gems, and like all the other strategy games, you get to design your defences to work the best way against your enemies (every other player out there!), and the goal of your design is to make reaching the chest of gold very hard for other thieves (players) who enter your dungeon, but <strong>not impossible or super hard</strong>, and that’s the catch; how do you verify that the user doesn’t make it extremely hard if not impossible for other players to reach his/her gems and gold?</p>
<p>The way the game creators solved it is a creative way – I’m not sure where it comes from and whether it is their original idea or it’s known in the game industry, but personally I only saw it in their game so far -, and this idea is to ask the user who designs the dungeon to prove that he/she can reach the chest within this design, if the user can’t solve the puzzle (reach the chest here), don’t allow him/her to save the design, and don’t run complex algorithms to check if the design is not an impossible design or a very hard design.<figure id="attachment_444" style="width: 300px" class="wp-caption aligncenter"></p>
<p><a href="http://mpcabd.xyz/wp-content/uploads/2015/07/Screenshot_2015-07-31-19-03-09.png" rel="lightbox[442]" title="Verifying User Input - Thinking Outside The Box"><img class="wp-image-444" src="http://mpcabd.xyz/wp-content/uploads/2015/07/Screenshot_2015-07-31-19-03-09-300x169.png" alt="King Of Thieves Splash Screen" width="300" srcset="https://mpcabd.xyz/wp-content/uploads/2015/07/Screenshot_2015-07-31-19-03-09-300x169.png 300w, https://mpcabd.xyz/wp-content/uploads/2015/07/Screenshot_2015-07-31-19-03-09-1024x576.png 1024w" sizes="(max-width: 300px) 100vw, 300px" /></a><figcaption class="wp-caption-text">King Of Thieves Screenshot © 2015 Zeptolab</figcaption></figure></p>
<p>By doing this the user would have to play in his/her own dungeon trying to defeat his/her defences to reach the chest, and by doing so twice in a row we can be sure that other players stand a good and fair chance of solving this puzzle. One thing that might be of a problem is when the user can actually design a good puzzle but he/she is not yet experienced in this game to solve it, then he/she might need to make their designs easier so that they can save them; but for that the game creators saw a chance where they can make money and they would offer you a proven design that works and is hard in exchange of some valuable resource in the game or you can purchase that design for real money.</p>
<p>The other major benefit of this approach is that you end up with a solution to the puzzle – or more than one solution if the user tried two different approaches -, with detailed steps (because you tracked the user while he/she was trying to solve the puzzle). You can use this data to do two important things; 1. You can sell the solution to the players who are trying to solve this puzzle (and betray the user but that’s another moral story), 2. You got yourself a training set for your machine learning algorithms that will be able to mimic the human’s way of solving such puzzles after studying all these massive solutions (and the other ones that users come up with when solving other users’ puzzles themselves).</p>
<p>I find this very genius, don’t you think?!</p>
<p>You can apply this idea to other games where the user creates defences against intruders and still you want to give the intruders a chance not allowing the user to make it impossible for them, and you can generalize the idea to many puzzle games where the user sets up the puzzle for other users.</p>
<p>With this idea the creators of that game spared a lot of time, effort and money from being spent on verifying the user’s input, and I think it’s something that’s worth sharing and applying to other platforms, maybe not only to other games.</p>]]></content:encoded>
    </item>
    <item>
      <title>Using curl with Proxy PAC configuration files</title>
      <link>https://mpcabd.xyz/using-curl-with-proxy-pac-configuration-files/</link>
      <pubDate>Mon, 16 Mar 2015 12:39:24 +0000</pubDate>
      <guid>https://mpcabd.xyz/using-curl-with-proxy-pac-configuration-files/</guid>
      <description>&lt;p&gt;&lt;a href=&#34;http://curl.haxx.se/&#34; target=&#34;_blank&#34;&gt;curl&lt;/a&gt; is an essential tool that most developers use, it will allow you to execute a wide range of HTTP requests from your terminal, it supports using a proxy to execute your requests, but it does not support &lt;a href=&#34;http://en.wikipedia.org/wiki/Proxy_auto-config#The_PAC_File&#34; target=&#34;_blank&#34;&gt;PAC configuration files&lt;/a&gt;.&lt;/p&gt;
&lt;p&gt;At my work I have to use a PAC file due to the large list of servers I’d interact with, and many would require me passing through specific proxies. It is a cumbersome process for me to memorize or try every URL I want to request and to identify which proxy to use, that’s why I wrote a simple perl script (yes perl not Python!) to help me with this issue.&lt;/p&gt;</description>
      <content:encoded><![CDATA[<p><a href="http://curl.haxx.se/" target="_blank">curl</a> is an essential tool that most developers use, it will allow you to execute a wide range of HTTP requests from your terminal, it supports using a proxy to execute your requests, but it does not support <a href="http://en.wikipedia.org/wiki/Proxy_auto-config#The_PAC_File" target="_blank">PAC configuration files</a>.</p>
<p>At my work I have to use a PAC file due to the large list of servers I’d interact with, and many would require me passing through specific proxies. It is a cumbersome process for me to memorize or try every URL I want to request and to identify which proxy to use, that’s why I wrote a simple perl script (yes perl not Python!) to help me with this issue.</p>
<h2 id="before-you-use-it">Before you use it</h2>
<ul>
<li>This script is written with Perl 5.16 in mind I haven’t tested it on other versions, but I suppose it should work properly, please let me know if it doesn’t work for you.</li>
<li>It also makes use of the following perl modules: <a title="Regexp::Common" href="http://search.cpan.org/~abigail/Regexp-Common-2013031301/lib/Regexp/Common.pm" target="_blank">Regexp::Common</a> and <a title="HTTP::ProxyPAC" href="http://search.cpan.org/~miyagawa/HTTP-ProxyPAC-0.01/lib/HTTP/ProxyPAC.pm" target="_blank">HTTP::ProxyPAC</a>.</li>
</ul>
<h2 id="download">Download</h2>
<p><a href="https://gist.github.com/mpcabd/b09688a0f5ec183afc68" target="_blank">The script’s gist is here</a></p>
<p>The script is available under <a href="http://www.gnu.org/copyleft/gpl.html" target="_blank">GPLv3</a>.</p>
<p>After downloading the script make sure it is executable:</p>
<pre class="lang:bash decode:true">chmod +x curlp.pl
</pre>
<p>And edit the file and set the variable <code>$PAC_URI</code> to your PAC URI in line 14.</p>
<h2 id="how-to-use">How to use</h2>
<p>You can use the script just like you use curl normally, it will automatically call curl with the appropriate proxy, but <strong>PLEASE NOTE</strong> this script will accept the URL as its last parameter always, and will pass any parameters that are before the url to curl blindly.</p>
<pre class="lang:bash decode:true">./curlp.pl ....... [URL]
</pre>]]></content:encoded>
    </item>
    <item>
      <title>Joining Booking.com</title>
      <link>https://mpcabd.xyz/joining-booking-com/</link>
      <pubDate>Mon, 01 Dec 2014 04:00:02 +0000</pubDate>
      <guid>https://mpcabd.xyz/joining-booking-com/</guid>
      <description>&lt;p&gt;After spending 3 years in Dubai and working at 2 different startups there, and after having worked at 5 different startups since I started working, I decided it’s time for me to move up and faraway from Dubai and startups, I started looking for jobs at big companies, Google, Facebook, Twitter, and got into a couple of interviews, and in the end I chose to go with Booking.com and I will be joining their team starting December 2014 as an IT Developer!&lt;/p&gt;</description>
      <content:encoded><![CDATA[<p>After spending 3 years in Dubai and working at 2 different startups there, and after having worked at 5 different startups since I started working, I decided it’s time for me to move up and faraway from Dubai and startups, I started looking for jobs at big companies, Google, Facebook, Twitter, and got into a couple of interviews, and in the end I chose to go with Booking.com and I will be joining their team starting December 2014 as an IT Developer!</p>
<p>Joining Booking.com opens great doors for me, meeting new people, very talented people, working in a stable organization, working on big systems with huge traffic, trying new technologies (like programming with Perl), and so many more!</p>
<p>I have relocated from Dubai to Amsterdam and thanks to Booking.com Global Mobility Team the relocation was super smooth, and I’m happily settled down now in Amsterdam!</p>
<p>Hopefully I will have more free time so 2015 will have some new projects and posts!</p>
]]></content:encoded>
    </item>
    <item>
      <title>Django Country Context</title>
      <link>https://mpcabd.xyz/django-country-context/</link>
      <pubDate>Sat, 05 Apr 2014 21:46:42 +0000</pubDate>
      <guid>https://mpcabd.xyz/django-country-context/</guid>
      <description>&lt;p&gt;This module solves a small problem that can be found in many sites, where the website has to support multiple countries, e.g. e-commerce website with different stores for different countries, this module allows the developer to define a context per thread, this context holds all the information about the currently available country, and allows the developer to rely on the context always to get the current country instead of passing it through the different levels of code. This module is thread-safe, it defines a different context for each thread.&lt;/p&gt;</description>
      <content:encoded><![CDATA[<p>This module solves a small problem that can be found in many sites, where the website has to support multiple countries, e.g. e-commerce website with different stores for different countries, this module allows the developer to define a context per thread, this context holds all the information about the currently available country, and allows the developer to rely on the context always to get the current country instead of passing it through the different levels of code. This module is thread-safe, it defines a different context for each thread.</p>
<h2 id="using-the-context">Using The Context</h2>
<p>To use the country context</p>
<ol>
<li>You activate the country of choice when you start to process the request, one place for activating the country is by writing a <a href="https://docs.djangoproject.com/en/dev/topics/http/middleware/" title="Middleware | Django documentation | Django" target="_blank">Django middleware</a> that activates the country in the <code>process_request</code> method.</li>
<li>After that your code should depend on the <code>country_context.get_current_country_code</code> to get the current country code, and that should be everywhere, so that you don’t have to pass the current country from the view to the controllers and to other parts of your code.</li>
<li>In the end when you finish processing the request you should deactivate the country, also you can do that in the middleware in the <code>process_response</code> method.</li>
</ol>
<p>If you want to create a middleware you can extend the <code>CountryContextMiddleware</code> included with this package.</p>
<h2 id="settings">Settings</h2>
<p>You should have the following two variables:</p>
<ol>
<li><code>DEFAULT_COUNTRY</code>: The default country code that will be the active country by default.</li>
<li><code>ENABLED_COUNTRIES</code>: A list of country codes that are enabled for your site. Codes are in <a href="http://en.wikipedia.org/wiki/ISO_3166-1_alpha-2" target="_blank">ISO 3166-1 Alpha 2</a> format.</li>
</ol>
<h2 id="example-usage">Example Usage</h2>
<p>We will imagine a Django site, an e-commerce site that serves multiple stores in US and UK, by default it’ll be serving the US site, but if the URL was prefixed with UK then the site will serve the UK store.</p>
<pre class="lang:python decode:true"># site/settings.py
# ...
DEFAULT_COUNTRY = 'US'
ENABLED_COUNTRIES = ['US', 'UK']
# ...
MIDDLEWARE_CLASSES = (
  # ...
  'site.country_context_middleware.SiteCountryContextMiddleware',
  # ...
)
</pre>
<pre class="lang:python decode:true"># site/country_context_middleware.py
import re

from django_country_context.country_context_middleware import CountryContextMiddleware


class SiteCountryContextMiddleware(CountryContextMiddleware):
  def get_country_code_from_request(self, request):
    if re.match(r'^/UK/', request.path_info, re.I):
      return 'UK'
    return 'US'
</pre>
<pre class="lang:python decode:true"># site/urls.py

from django.contrib import admin
from django.conf import settings
from django.conf.urls import patterns, include, url

urlpatterns = patterns('',
  url(r'^(?:%s)?/' % '|'.join(
    ''.join(
      '[%s%s]' % (c.upper(), c.lower()) for c in country
    ) for country in settings.ENABLED_COUNTRIES
  ), include('app.urls')),
)
</pre>
<pre class="lang:python decode:true"># app/models.py

from django.db import models
from django_country_context import country_context, countries_data


class StoreManager(models.Manager):
  def __init__(self, countries_enabled=True):
    super(StoreManager, self).__init__()
    self.countries_enabled = countries_enabled

  def get_query_set(self):
    qs = super(StoreManager, self).get_query_set()
    if self.countries_enabled:
      qs = qs.filter(country=country_context.get_current_country_code())
    return qs


class Store(models.Model):
  # ...
  country = models.CharField(max_length=2, default=country_context.get_current_country_code, choices=countries_data.ENABLED_COUNTRIES_TUPLE, db_index=True)

  objects = StoreManager()
  objects_no_countries = StoreManager(countries_enabled=False)
</pre>
<pre class="lang:python decode:true"># app/admin.py

from django.contrib import admin
from models import Store


class StoreAdmin(admin.ModelAdmin):
  model = Store
  def queryset(self, request):
    self.model._default_manager = self.model.objects_no_countries
    return super(StoreAdmin, self).queryset(request)
  # ...

admin.site.register(Store, StoreAdmin)
</pre>
<p>Using the setup above will allow the views to call the query the Store model without handling special cases for countries, and you can change the logic of getting the current country without any change to your views, this way we’ve separated the country context completely from the logic of the site. And when you need to get the current country name or code you can use <code>country_context.get_current_country_name()</code> and <code>country_context.get_current_country_code()</code> respectively. Please note that the setup above was written for a Django 1.4.x.</p>
<h2 id="download">Download</h2>
<p><a href="https://github.com/mpcabd/django-country-context/">Django Country Context on source code on GitHub</a></p>]]></content:encoded>
    </item>
    <item>
      <title>How to make django management commands send errors email to admins</title>
      <link>https://mpcabd.xyz/make-django-management-commands-send-errors-email-admins/</link>
      <pubDate>Sun, 08 Dec 2013 13:15:42 +0000</pubDate>
      <guid>https://mpcabd.xyz/make-django-management-commands-send-errors-email-admins/</guid>
      <description>&lt;p&gt;I usually use django’s &lt;a title=&#34;Writing custom django-admin commands&#34; href=&#34;https://docs.djangoproject.com/en/dev/howto/custom-management-commands/&#34; target=&#34;_blank&#34;&gt;custom management commands&lt;/a&gt; to do different tasks on the web application, most of the times with a cron job running those commands. The problem is that when you’re using a cron job, you won’t get the beautiful django error email when something goes wrong.&lt;/p&gt;</description>
      <content:encoded><![CDATA[<p>I usually use django’s <a title="Writing custom django-admin commands" href="https://docs.djangoproject.com/en/dev/howto/custom-management-commands/" target="_blank">custom management commands</a> to do different tasks on the web application, most of the times with a cron job running those commands. The problem is that when you’re using a cron job, you won’t get the beautiful django error email when something goes wrong.</p>
<p><a href="http://mpcabd.xyz/wp-content/uploads/2013/12/django-error-email.jpg" rel="lightbox[403]" title="How to make django management commands send errors email to admins"><img class="aligncenter size-medium wp-image-404" alt="Django's error email sample" src="http://mpcabd.xyz/wp-content/uploads/2013/12/django-error-email-300x207.jpg" width="300" height="207" srcset="https://mpcabd.xyz/wp-content/uploads/2013/12/django-error-email-300x207.jpg 300w, https://mpcabd.xyz/wp-content/uploads/2013/12/django-error-email.jpg 996w" sizes="(max-width: 300px) 100vw, 300px" /></a></p>
<p>You can of course log all the commands you run and the cron jobs you have in files, but the problem is that sometimes you need to be notified instantly via your email, so here’s how to make django management commands send you the errors email.</p>
<h2 id="understanding-how-django8217s-error-email-works">Understanding how django’s error email works</h2>
<p>If you check django’s logging documentation you will find that it has a built-in handler called <a href="https://docs.djangoproject.com/en/dev/topics/logging/#django.utils.log.AdminEmailHandler" title="Django Logging AdminEmailHandler" target="_blank">AdminEmailHandler</a> this handler sends an email to the site admins for each log message it receives.</p>
<p>So basically all you need to do is to tell your django commands to log the errors using a logger with that handler, and you’ll receive the emails.</p>
<p>To do so define a logger in your <code>settings.py</code>:</p>
<pre class="lang:python decode:true">LOGGING = {
    #OTHER OPTIONS
    'filters': {
        #OTHER FILTERS
        'require_debug_false': {
            '()': 'django.utils.log.RequireDebugFalse'
        }
    },
    'handlers': {
        #OTHER HANDLERS
        'mail_admins': {
            'level': 'ERROR',
            'filters': ['require_debug_false'],
            'class': 'django.utils.log.AdminEmailHandler',
            'include_html': True
        }
    },
    'loggers': {
        #OTHER LOGGERS
        'management_commands': {
            'handlers': ['mail_admins'],
            'level': 'ERROR',
            'propagate': True,
        },
    }
}
</pre>
<p>And after that in your custom commands log the errors you face using the logger you defined:</p>
<pre class="lang:python decode:true">from django.utils.log import getLogger
from django.core.management.base import BaseCommand
import sys

logger = getLogger('management_commands')

class Command(BaseCommand):
    def handle(self, *args, **options):
        try:
            #DO YOUR STUFF HERE
        except Exception as e:
            logger.error('Admin Command Error: %s', ' '.join(sys.argv), exc_info=sys.exc_info())
            #Raise the exception again so it gets logged in standard error also.
            raise e
</pre>
<h2 id="enabling-the-logger-to-all-commands-in-one-configuration">Enabling the logger to all commands in one configuration</h2>
<p>You can also make all the commands (custom or not) send the error by email by editing <code>manage.py</code> almost the same way as we edited the command file above:</p>
<pre class="lang:python decode:true">from django.utils.log import getLogger
import sys

logger = getLogger('management_commands')

#Wrap this line with a try-catch execute_from_command_line(sys.argv)
    try:
        execute_from_command_line(sys.argv)
    except Exception as e:
        logger.error('Admin Command Error: %s', ' '.join(sys.argv), exc_info=sys.exc_info())
        raise e
</pre>
<p>This way all the commands will send the error by email also to django admins.</p>
<p>Enjoy it!</p>]]></content:encoded>
    </item>
    <item>
      <title>How to make logrotate use SSMTP</title>
      <link>https://mpcabd.xyz/make-logrotate-use-ssmtp/</link>
      <pubDate>Sun, 08 Dec 2013 12:25:41 +0000</pubDate>
      <guid>https://mpcabd.xyz/make-logrotate-use-ssmtp/</guid>
      <description>&lt;p&gt;A few days ago I was looking at my server logs, my website logs are more than a year old and growing, so I was reading some of them and wanted to download the old logs, truncate the logs, so that next time I read the logs I won’t have to look at very old data. So basically I wanted to rotate the logs and archive them, luckily &lt;a title=&#34;logrotate man page&#34; href=&#34;http://linuxcommand.org/man_pages/logrotate8.html&#34; target=&#34;_blank&#34;&gt;logrotate&lt;/a&gt; is there to let me manage and administer log files in my system. It has a long list of features with a very easy configuration, so it was the tool I’m looking for.&lt;/p&gt;</description>
      <content:encoded><![CDATA[<p>A few days ago I was looking at my server logs, my website logs are more than a year old and growing, so I was reading some of them and wanted to download the old logs, truncate the logs, so that next time I read the logs I won’t have to look at very old data. So basically I wanted to rotate the logs and archive them, luckily <a title="logrotate man page" href="http://linuxcommand.org/man_pages/logrotate8.html" target="_blank">logrotate</a> is there to let me manage and administer log files in my system. It has a long list of features with a very easy configuration, so it was the tool I’m looking for.</p>
<p>logrotate uses the system’s mail <code>/bin/mail</code> to send the email when a log file is to be archived and removed from the system. But my system doesn’t use /bin/mail, it uses <a title="SSMTP man page" href="http://linux.die.net/man/8/ssmtp" target="_blank">SSMTP</a> with some custom configurations. I wanted to use SSMTP with logrotate but apparently it’s not a very simple task, since the man page for logrotate says:</p>
<blockquote>
<p>Option -m, –mail <command></p>
</blockquote>
<blockquote>
<p>Tells logrotate which command to use when mailing logs. This command should accept two arguments: <strong>1) the subject of the message, and 2) the recipient. The command must then read a message on standard input and mail it to the recipient.</strong> The default mail command is /bin/mail -s.</p>
</blockquote>
<p>Which is not actually how SSMT works, SSMTP as it’s described in the man page accepts the recipients emails as command line arguments, and reads the message (along with it’s subject header) from the standard input.</p>
<h2 id="the-shell-script">The shell script</h2>
<p>The solution to this problem would be by creating a shell script that behaves like a middleware between logrotate and SSMTP.</p>
<p>The shell script would simply read the arguments passed from logrotate and then build the right command to call SSMTP with by prepending the appropriate SMTP headers (To, Subject, From) to the message.</p>
<p>You can download the shell script from this link <a title="logrotate_smtp.sh Gist on GitHub" href="https://gist.github.com/mpcabd/03ce7d302eb4e1f5bfb7" target="_blank">logrotate_ssmtp.sh</a>.</p>
<p>As you can easily see that the shell script only accepts two arguments, so it sends the email to only one person, if you want to have more than one recipient and you’ve configured logrotate to send them the email, you’ll have to modify the script to accept more arguments and pass them to SSMTP.</p>
<p>Also you’ll have to replace <code>server@example.com</code> with the email address you’re sending from.</p>
<h2 id="configuring-logrotate">Configuring logrotate</h2>
<p>Now all we have to do is to configure logrotate to use the shell script as a mail command instead of /bin/mail. To do so you’ll have to edit all the calls that you make to logrotate to be like:</p>
<p><code>/usr/sbin/logrotate -m '~/logrotate_ssmtp.sh' /etc/logrotate.conf</code></p>
<p>The main call that you should change is located in <code>cron.daily</code> directory, I’m using Ubuntu so I have to edit this file <code>/etc/cron.daily/logrotate</code> and change the command at the end of the file to the command above.</p>
<p>Hope this helps you with your logs 🙂<figure style="width: 648px" class="wp-caption aligncenter"></p>
<p><img class="" alt="Logs Vancouver - photo by ahisgett on Flickr" src="http://images.cdn.fotopedia.com/flickr-220279395-original.jpg" width="648" height="972" /><figcaption class="wp-caption-text">photo by <a href="http://www.flickr.com/photos/37804979@N00" target="_blank">ahisgett</a> on Flickr</figcaption></figure></p>]]></content:encoded>
    </item>
    <item>
      <title>Adding a timestamp to command output in linux</title>
      <link>https://mpcabd.xyz/adding-a-timestamp-to-command-output-in-linux/</link>
      <pubDate>Wed, 13 Feb 2013 06:03:59 +0000</pubDate>
      <guid>https://mpcabd.xyz/adding-a-timestamp-to-command-output-in-linux/</guid>
      <description>&lt;p&gt;This is just a quick solution to put a timestamp with each line of the output of some command in Linux (*nix). It’s a very simple thing, thought I’d write it down here so maybe it’ll help somebody some day.&lt;/p&gt;
&lt;p&gt;I have a cron job running on my server, it’s a high frequency job so I don’t want to send email reports each time, I’m logging it into a file, but I want to log the timestamp of each time it runs and logs something to this file, I didn’t want to change the code behind it to also print the timestamp with each write to the output, so I pipelined the command to a simple bash script that will append the timestamp to each line in the output then write the result to the stdout again.&lt;/p&gt;</description>
      <content:encoded><![CDATA[<p>This is just a quick solution to put a timestamp with each line of the output of some command in Linux (*nix). It’s a very simple thing, thought I’d write it down here so maybe it’ll help somebody some day.</p>
<p>I have a cron job running on my server, it’s a high frequency job so I don’t want to send email reports each time, I’m logging it into a file, but I want to log the timestamp of each time it runs and logs something to this file, I didn’t want to change the code behind it to also print the timestamp with each write to the output, so I pipelined the command to a simple bash script that will append the timestamp to each line in the output then write the result to the stdout again.</p>
<p>Here is the bash script:</p>
<pre class="lang:bash decode:true">#!/bin/bash
while read x; do
	echo -n `date +%d/%m/%Y\ %H:%M:%S`;
	echo -n " ";
	echo $x;
done
</pre>
<p>Then I edited the cron job line to be like this:</p>
<pre class="lang:bash decode:true">... /path/to/my/command.sh 2&gt;&1 | /path/to/timestap.sh &gt;&gt; /var/log/cron/my_log.log
</pre>
<p>And you’re done!</p>
<p>Enjoy it.</p>]]></content:encoded>
    </item>
    <item>
      <title>Get Pattern From an Image in PIL Python</title>
      <link>https://mpcabd.xyz/get-pattern-from-an-image-in-pil-python/</link>
      <pubDate>Mon, 14 Jan 2013 11:14:23 +0000</pubDate>
      <guid>https://mpcabd.xyz/get-pattern-from-an-image-in-pil-python/</guid>
      <description>&lt;p&gt;Two days ago I needed to generate a PIL image that is made up from repeating a pattern – another PIL image – multiple times, I didn’t find a code online to do it so I just wrote this small code to do it, thought might share it to help somebody out there.&lt;/p&gt;</description>
      <content:encoded><![CDATA[<p>Two days ago I needed to generate a PIL image that is made up from repeating a pattern – another PIL image – multiple times, I didn’t find a code online to do it so I just wrote this small code to do it, thought might share it to help somebody out there.</p>
<pre class="lang:python decode:true">def get_pattern_from_image(file_name, pattern_width, pattern_height):
    import Image
    pattern_image = Image.open(file_name, 'r')
    result_image = Image.new('RGB', (pattern_width, pattern_height))
    x = 0
    while x &lt; pattern_width:
        y = 0
        while y &lt; pattern_height:
            result_image.paste(pattern_image, (x, y))
            y += pattern_image.size[1]
        x += pattern_image.size[0]
    return result_image
</pre>
<p>It&rsquo;s a very simple solution which uses the <a href="http://www.pythonware.com/library/pil/handbook/image.htm#Image.paste" title="The Image Module - Paste" target="_blank">Image.paste</a> method to repeat the pattern.</p>
<p>You can download this snippet of code from here: <a href="https://gist.github.com/4529367" target="_blank"><a href="https://gist.github.com/4529367">https://gist.github.com/4529367</a></a>.</p>
<p>Enjoy 🙂</p>]]></content:encoded>
    </item>
    <item>
      <title>Python Celery Asynchronous Task Decorator</title>
      <link>https://mpcabd.xyz/python-celery-asynchronous-task-decorator/</link>
      <pubDate>Wed, 10 Oct 2012 20:58:02 +0000</pubDate>
      <guid>https://mpcabd.xyz/python-celery-asynchronous-task-decorator/</guid>
      <description>&lt;p&gt;A while ago I was working on a project in Django that had many tasks that needed to be executed asynchronously such as sending emails, generating reports, and checking some database related issues.&lt;/p&gt;
&lt;p&gt;Executing asynchronous tasks in Python can be made in multiple ways, one of them is using &lt;a href=&#34;http://celeryproject.org/&#34; title=&#34;Celery: Distributed Task Queue&#34; target=&#34;_blank&#34;&gt;celery&lt;/a&gt;, a distributed task queue written in Python which has proved itself to be a great solid task queue system.&lt;/p&gt;
&lt;p&gt;And if you’re using Django then there is a Django app to make your life easier, &lt;a href=&#34;https://github.com/celery/django-celery/&#34; title=&#34;Celery integration for Django&#34; target=&#34;_blank&#34;&gt;django-celery&lt;/a&gt;.&lt;/p&gt;
&lt;p&gt;Now as always I like to make my own life easier also by implementing generic solutions for my needs, so I have written this simple piece of code to create a function decorator that declares the function as an asynchronous task, which means that by just adding this decorator to the function it becomes asynchronous.&lt;/p&gt;</description>
      <content:encoded><![CDATA[<p>A while ago I was working on a project in Django that had many tasks that needed to be executed asynchronously such as sending emails, generating reports, and checking some database related issues.</p>
<p>Executing asynchronous tasks in Python can be made in multiple ways, one of them is using <a href="http://celeryproject.org/" title="Celery: Distributed Task Queue" target="_blank">celery</a>, a distributed task queue written in Python which has proved itself to be a great solid task queue system.</p>
<p>And if you’re using Django then there is a Django app to make your life easier, <a href="https://github.com/celery/django-celery/" title="Celery integration for Django" target="_blank">django-celery</a>.</p>
<p>Now as always I like to make my own life easier also by implementing generic solutions for my needs, so I have written this simple piece of code to create a function decorator that declares the function as an asynchronous task, which means that by just adding this decorator to the function it becomes asynchronous.</p>
<p>So let’s get started!</p>
<figure class="auto center">
    <img loading="lazy" src="/wp-content/uploads/2012/10/celery-python.png"/> 
</figure>

<h3 id="description">Description</h3>
<p>The following code will allow you to decorate Python functions with a decorator that will allow them to be executed asynchronously in a seamless easy way. You don’t have to change any thing in your code, just add the <code>asynchronous_task</code> decorator to the functions you want them to be executed asynchronously and you’re done.</p>
<p>This code can be used with Django also, just uncomment the Django block in it and it’ll work.</p>
<p>I wrote this code in a file called <code>celery_tasks.py</code> which probably the place you’ll have your all celery tasks, it adds a task called <code>execute</code> that is responsible for executing the passed function and parameters.</p>
<pre class="lang:python decode:true">import os, sys
from celery.task import task

sys.path.insert(0, os.path.dirname(os.path.dirname(__file__)))
sys.path.insert(0, os.path.dirname(__file__))

##########################
# Uncomment the following code block to enable it to work with Django.
# Either put this file next to the settings.py file, or change the block code to import your settings module from the correct path.
##########################

#from django.core.management import setup_environ
#import settings
#setup_environ(settings)

@task(name='execute')
def execute(module_name, method_name, *args, **kwargs):
	try:
		m = __import__(module_name)
		if m.__name__ != module_name:
			modules = module_name.split('.')[1:]
			for module in modules:
				m = getattr(m, module)
		f = getattr(m, method_name)
		if hasattr(f, 'func'):
			f = f.func
		return f(*args, **kwargs)
	except Exception, e:
		raise e
</pre>
<p>The code looks like a mess I know, but simply what it does is that you pass this task the following parameters:</p>
<ol>
<li>Python module name to get the function from</li>
<li>Method name to be executed</li>
<li>Positional and named parameters</li>
</ol>
<p>The second part is defining the decorator, lets assume that this file is called <code>celery_decorator.py</code>:</p>
<p><strong>Note that I’m assuming that <code>celery_decorator.py</code> is in the same folder of your <code>celery_tasks.py</code> file.</strong></p>
<pre class="lang:python decode:true">from django.utils.decorators import available_attrs
from django.utils.functional import wraps

def asynchronous_task(check_if_active = False):
	def wrapper(f):
		try:
			@wraps(f, assigned=available_attrs(f))
			def _wrapper(*args, **kwargs):
				try:
					if check_if_active:
						from celery.task.control import inspect
						insp = inspect()
						d = insp.active()
						if not d:
							raise Exception
					from celery_tasks import execute
					execute.delay(f.__module__, f.func_name, *args, **kwargs)
				except Exception as e:
					f(*args, **kwargs)
			_wrapper.func = f
			return _wrapper
		except Exception:
			return f
	return wrapper
</pre>
<p>This decorator simply wraps the function in a call to the <code>execute</code> task on celery, so that it’ll be executed asynchronously, it accept an optional parameter that defines whether the decorator should check if celery is running and if it’s not then execute the function synchronously, it is set to <code>False</code> by default because it takes some time to check celery, so it makes the performance poor a little bit.</p>
<p>Now we can us it on any function inside our code:</p>
<pre class="lang:python decode:true">from celery_decorator import asynchronous_task

#Default not to check if celery is running
@asynchronous_task
def a_very_long_process(p1, p2):
    pass #TODO: Do something

#Force check
@asynchronous_task(check_if_active = True)
def another_very_long_process(p1, p2):
    pass #TODO: Do something
</pre>
<p>Now in your code you just simply don’t change anything, all the calls to these two functions will be asynchronous calls.</p>
<h3 id="download">Download</h3>
<p>The source code is licensed under the <a href="http://www.gnu.org/copyleft/gpl.html">GNU Public License (GPL)</a>.</p>
<p>You can download a copy of <code>celery_tasks.py</code> and <code>celery_decorators.py</code> from this Gist: <a href="https://gist.github.com/3874979">https://gist.github.com/3874979</a></p>
<p>Hope this helps somebody to perform faster 🙂</p>]]></content:encoded>
    </item>
    <item>
      <title>Python Arabic Text Reshaper</title>
      <link>https://mpcabd.xyz/python-arabic-text-reshaper/</link>
      <pubDate>Thu, 10 May 2012 17:40:11 +0000</pubDate>
      <guid>https://mpcabd.xyz/python-arabic-text-reshaper/</guid>
      <description>&lt;p&gt;I was trying today to generate PDF reports using &lt;a href=&#34;http://www.geraldoreports.org/&#34; target=&#34;_blank&#34;&gt;Geraldo Reports&lt;/a&gt; and I needed to generate reports with Arabic text in them. Arabic is a very special script language with two essential features:&lt;/p&gt;
&lt;ol&gt;
&lt;li&gt;It is written from right to left.&lt;/li&gt;
&lt;li&gt;The characters change shape according to their surrounding characters.&lt;/li&gt;
&lt;/ol&gt;
&lt;p&gt;So when you try to print Arabic text in an application – or a library – that doesn’t support Arabic you’re pretty likely to end up with something that looks like this:&lt;/p&gt;
&lt;figure class=&#34;auto center&#34;&gt;
    &lt;img loading=&#34;lazy&#34; src=&#34;https://mpcabd.xyz/wp-content/uploads/2012/05/arabic-1.png&#34;
         alt=&#34;Arabic text, broken, left to right&#34;/&gt; &lt;figcaption&gt;
            &lt;p&gt;Arabic text, broken, left to right&lt;/p&gt;
        &lt;/figcaption&gt;
&lt;/figure&gt;

&lt;p&gt;We have two problems here, first, the characters are in the isolated form, which means that every character is rendered regardless of its surroundings, and second is that the text is written from left to right.&lt;/p&gt;</description>
      <content:encoded><![CDATA[<p>I was trying today to generate PDF reports using <a href="http://www.geraldoreports.org/" target="_blank">Geraldo Reports</a> and I needed to generate reports with Arabic text in them. Arabic is a very special script language with two essential features:</p>
<ol>
<li>It is written from right to left.</li>
<li>The characters change shape according to their surrounding characters.</li>
</ol>
<p>So when you try to print Arabic text in an application – or a library – that doesn’t support Arabic you’re pretty likely to end up with something that looks like this:</p>
<figure class="auto center">
    <img loading="lazy" src="/wp-content/uploads/2012/05/arabic-1.png"
         alt="Arabic text, broken, left to right"/> <figcaption>
            <p>Arabic text, broken, left to right</p>
        </figcaption>
</figure>

<p>We have two problems here, first, the characters are in the isolated form, which means that every character is rendered regardless of its surroundings, and second is that the text is written from left to right.</p>
<p>To solve the latter issue all we have to do is to use the <a title="Unicode Bidirectional Algorithm" href="http://unicode.org/reports/tr9/" target="_blank">Unicode bidirectional algorithm</a>, which is implemented purely in Python in <a title="python-bidi; Unicode Bidirectional Algorithm" href="https://github.com/MeirKriheli/python-bidi" target="_blank">python-bidi</a>. If you use it you’ll end up with something that looks like this:</p>
<figure class="auto center">
    <img loading="lazy" src="/wp-content/uploads/2012/05/arabic-6.png"
         alt="Arabic text, broken, right to left"/> <figcaption>
            <p>Arabic text, broken, right to left</p>
        </figcaption>
</figure>

<p>The only issue left to solve is to reshape those characters and replace them with their correct shapes according to their surroundings.</p>
<p>I solved this issue more than four years ago in a small application that I wrote in Visual Basic, my solution was naive but it solved it well, anyway, a few days ago I faced the same problem – rendering Arabic text correctly – but on Android, and I searched and used the solution in <a title="Stack Overflow answer by breceivemail that solves Arabic rendering in Android" href="http://stackoverflow.com/a/7962813/99557" target="_blank">this SO answer</a>, which is pretty similar to the solution provided in <a title="Better Arabic Reshaper, Java class for Android" href="https://github.com/agawish/Better-Arabic-Reshaper/" target="_blank">Better Arabic Reshaper</a>.</p>
<p>Today I ported the solution in Better Arabic Reshaper from Java to Python, tweaked it a little bit, and used it to successfully render Arabic text in PDF, and the result was:</p>
<figure class="auto center">
    <img loading="lazy" src="/wp-content/uploads/2012/05/arabic-3.png"
         alt="Arabic text, correctly shaped, right to left"/> <figcaption>
            <p>Arabic text, correctly shaped, right to left</p>
        </figcaption>
</figure>

<p>Pretty cool right? Here is another test with English text in it some diacritics:</p>
<figure class="auto center">
    <img loading="lazy" src="/wp-content/uploads/2012/05/arabic-4.png"
         alt="Arabic text, with English text, correctly shaped, correctly directed, with diacritics"/> <figcaption>
            <p>Arabic text, with English text, correctly shaped, correctly directed, with diacritics</p>
        </figcaption>
</figure>

<p>It looks fine! in Word the same text looks like this:</p>
<figure class="auto center">
    <img loading="lazy" src="/wp-content/uploads/2012/05/arabic-5.png"
         alt="Arabic text, with English text, correctly shaped, correctly directed, with diacritics, in Microsoft Word"/> <figcaption>
            <p>Arabic text, with English text, correctly shaped, correctly directed, with diacritics, in Microsoft Word</p>
        </figcaption>
</figure>

<p>Amazing, now it is time for you to use the ported library along with python-bidi to solve those issues.</p>
<h3 id="usage">Usage</h3>
<pre class="lang:python decode:1">import arabic_reshaper
from bidi.algorithm import get_display

#...
reshaped_text = arabic_reshaper.reshape(u'اللغة العربية رائعة')
bidi_text = get_display(reshaped_text)
pass_arabic_text_to_render(bidi_text)  # &lt;-- This function does not really exist
#...
</pre>
<p>The <code>pass_arabic_text_to_render</code> function here is an imaginary function, it is just here to say that the variable bidi_text is the variable that you would need to use in your code afterwards, for example to print it in PDF, or to write it in an Image, etc.</p>
<h3 id="demo">Demo</h3>
<p>You can try an online demo of this script on my page here: <a href="http://reshaper.mpcabd.xyz/">Arabic Reshaper Online</a>.</p>
<h3 id="download">Download</h3>
<p>The source code is licensed under the <a href="https://opensource.org/licenses/MIT">MIT License</a>.</p>
<p>You can install it into your Python installation with pip:</p>
<pre class="lang:bash decode:1">$ pip install arabic-reshaper</pre>
<p><a href="https://github.com/mpcabd/python-arabic-reshaper" target="_blank">Project on GitHub</a></p>
<p><a href="https://github.com/mpcabd/python-arabic-reshaper/tarball/master" target="_blank">Source code download from GitHub</a></p>
<p>Have fun واستمتع! 🙂</p>]]></content:encoded>
    </item>
    <item>
      <title>Android Map View With Pan &amp; Zoom Events</title>
      <link>https://mpcabd.xyz/android-map-view-with-pan-zoom-events/</link>
      <pubDate>Thu, 15 Dec 2011 18:29:51 +0000</pubDate>
      <guid>https://mpcabd.xyz/android-map-view-with-pan-zoom-events/</guid>
      <description>&lt;p&gt;I was working an Android application, and I had an activity that contains a map in it, the map is hosted inside a &lt;a href=&#34;http://developer.android.com/resources/tutorials/views/hello-mapview.html&#34;&gt;MapView&lt;/a&gt;. The application had to show some pins over the map, the pins locations are obtained from a web service. I had to retrieve the pins locations after the user pans the map or zooms in or out.&lt;/p&gt;
&lt;p&gt;Google didn’t provide events for panning and zooming inside MapView class, but you can extend the class and do it your self, and that’s what I did.&lt;/p&gt;</description>
      <content:encoded><![CDATA[<p>I was working an Android application, and I had an activity that contains a map in it, the map is hosted inside a <a href="http://developer.android.com/resources/tutorials/views/hello-mapview.html">MapView</a>. The application had to show some pins over the map, the pins locations are obtained from a web service. I had to retrieve the pins locations after the user pans the map or zooms in or out.</p>
<p>Google didn’t provide events for panning and zooming inside MapView class, but you can extend the class and do it your self, and that’s what I did.</p>
<p><a href="http://mpcabd.xyz/wp-content/uploads/2011/12/Androids.png" rel="lightbox[320]" title="Androids"><img src="http://mpcabd.xyz/wp-content/uploads/2011/12/Androids-300x105.png" alt="" title="Androids" width="300" height="105" class="aligncenter size-medium wp-image-315" srcset="https://mpcabd.xyz/wp-content/uploads/2011/12/Androids-300x105.png 300w, https://mpcabd.xyz/wp-content/uploads/2011/12/Androids.png 766w" sizes="(max-width: 300px) 100vw, 300px" /></a></p>
<h3 id="listener-interface">Listener Interface</h3>
<pre class="lang:java decode:true">import com.google.android.maps.GeoPoint;

public interface MapViewListener {
	void onPan(GeoPoint oldTopLeft,
			   GeoPoint oldCenter,
			   GeoPoint oldBottomRight,
			   GeoPoint newTopLeft,
			   GeoPoint newCenter,
			   GeoPoint newBottomRight);
	void onZoom(GeoPoint oldTopLeft,
				GeoPoint oldCenter,
				GeoPoint oldBottomRight,
				GeoPoint newTopLeft,
				GeoPoint newCenter,
				GeoPoint newBottomRight,
				int oldZoomLevel,
				int newZoomLevel);
	void onClick(GeoPoint clickedPoint);
}
</pre>
<p>This listener will receive three events, onPan when the user pans the map, onZoom when the user zooms in or out, onClick when the user taps on the map without panning.</p>
<p>Each event will pass useful parameters, which are old and new values for the top left corner, bottom right corner, center point and zoom level.</p>
<h3 id="map-view-code">Map View Code</h3>
<p>The new map view will inherit the MapView class, and define some useful variables:</p>
<pre class="lang:java decode:true">import android.content.Context;
import android.graphics.Canvas;
import android.util.AttributeSet;
import android.view.MotionEvent;

import com.google.android.maps.GeoPoint;
import com.google.android.maps.MapView;

public class ObservableMapView extends MapView {
	public ObservableMapView(Context context, String apiKey) { super(context, apiKey); }
	public ObservableMapView(Context context, AttributeSet attrs) { super(context, attrs); }
	public ObservableMapView(Context context, AttributeSet attrs, int defStyle) { super(context, attrs, defStyle); }
	
	private GeoPoint mOldTopLeft;
	private GeoPoint mOldCenter;
	private GeoPoint mOldBottomRight;
	private int mOldZoomLevel = -1;
	
	private MapViewListener mMapViewListener;
	public MapViewListener getMapViewListener() { return mMapViewListener; }
	public void setMapViewListener(MapViewListener value) { mMapViewListener = value; }

// ...
}
</pre>
<p>To get touch events we’re going to override the onTouchEvent:</p>
<pre class="lang:java decode:true">@Override
	public boolean onTouchEvent(MotionEvent ev) {
		if (ev.getAction() == MotionEvent.ACTION_UP) {
			GeoPoint newCenter = this.getMapCenter();
			GeoPoint newTopLeft = this.getProjection().fromPixels(0, 0);
			GeoPoint newBottomRight = this.getProjection().fromPixels(this.getWidth(), this.getHeight());
			
			if (this.mMapViewListener != null &&
				newTopLeft.getLatitudeE6() == mOldTopLeft.getLatitudeE6() &&
				newTopLeft.getLongitudeE6() == mOldTopLeft.getLongitudeE6()) {
				mMapViewListener.onClick(this.getProjection().fromPixels((int)ev.getX(), (int)ev.getY()));
			}
		}
		return super.onTouchEvent(ev);
	}
</pre>
<p>Here we’re checking the new coordinates with the old coordinates, if they haven’t changed then the user has tapped on the map, but if they changed then it is a panning event, we’re not going to emit the event of panning now.</p>
<p>To be able to find if the user has zoomed we’re going to override the dispatchDraw method, because it will be called when the user pans or zooms, so it is the place we’re going to check for events in it.</p>
<pre class="lang:java decode:true">@Override
	protected void dispatchDraw(Canvas canvas) {
		super.dispatchDraw(canvas);
		
		GeoPoint newCenter = this.getMapCenter();
		GeoPoint newTopLeft = this.getProjection().fromPixels(0, 0);
		GeoPoint newBottomRight = this.getProjection().fromPixels(this.getWidth(), this.getHeight());
		int newZoomLevel = this.getZoomLevel();
		
		if (mOldCenter == null)
			mOldCenter = newCenter;
		
		if (mOldTopLeft == null)
			mOldTopLeft = newTopLeft;

		if (mOldBottomRight == null)
			mOldBottomRight = newBottomRight;

		if (newTopLeft.getLatitudeE6() != mOldTopLeft.getLatitudeE6() || newTopLeft.getLongitudeE6() != mOldTopLeft.getLongitudeE6()) {
			if (this.mMapViewListener != null) {
				GeoPoint oldTopLeft, oldCenter, oldBottomRight;
				
				oldTopLeft = mOldTopLeft;
				oldCenter = mOldCenter;
				oldBottomRight = mOldBottomRight;
		
				mOldBottomRight = newBottomRight;
				mOldTopLeft = newTopLeft;
				mOldCenter = newCenter;
				
				mMapViewListener.onPan(oldTopLeft,
									   oldCenter,
									   oldBottomRight,
									   newTopLeft,
									   newCenter,
									   newBottomRight);
			}
		}
		
		if (mOldZoomLevel == -1)
			mOldZoomLevel = newZoomLevel;
		else if (mOldZoomLevel != newZoomLevel && mMapViewListener != null) {
			int oldZoomLevel = mOldZoomLevel;
			GeoPoint oldTopLeft, oldCenter, oldBottomRight;
			oldTopLeft = mOldTopLeft;
			oldCenter = mOldCenter;
			oldBottomRight = mOldBottomRight;
	
			mOldZoomLevel = newZoomLevel;
			mOldBottomRight = newBottomRight;
			mOldTopLeft = newTopLeft;
			mOldCenter = newCenter;
			
			mMapViewListener.onZoom(oldTopLeft,
									oldCenter,
									oldBottomRight,
									newTopLeft,
									newCenter,
									newBottomRight,
									oldZoomLevel,
									newZoomLevel);
		}
	}
</pre>
<h3 id="download">Download</h3>
<p>The source code is licensed under the <a href="http://www.gnu.org/copyleft/gpl.html">GNU Public License (GPL)</a>.</p>
<p>You can download the source code from here:</p>
<p><a href="https://github.com/mpcabd/android-map-view-pan-zoom">Project on GitHub</a></p>
<p><a href="https://github.com/mpcabd/android-map-view-pan-zoom/tarball/master">Source code from GitHub</a></p>]]></content:encoded>
    </item>
    <item>
      <title>Log to a file on computer in Android</title>
      <link>https://mpcabd.xyz/log-to-a-file-on-computer-in-android/</link>
      <pubDate>Mon, 12 Dec 2011 19:53:04 +0000</pubDate>
      <guid>https://mpcabd.xyz/log-to-a-file-on-computer-in-android/</guid>
      <description>&lt;p&gt;It’s been a long time since the last time I blogged about something, and many things have changed since then,&lt;/p&gt;
&lt;p&gt;I graduated, got engaged and moved to Dubai.&lt;/p&gt;
&lt;p&gt;I have plenty of things in my mind to blog about, many solutions and many tools that I developed that I’d like to share it with everyone, but I haven’t settled down, and my schedule is not stable yet, so I haven’t got enough time to sort things out and start blogging, anyway this post is simple and it doesn’t need much description so I thought I’d share it with you now.&lt;/p&gt;
&lt;p&gt;&lt;a href=&#34;http://mpcabd.xyz/wp-content/uploads/2011/12/Androids.png&#34; rel=&#34;lightbox[310]&#34; title=&#34;Androids&#34;&gt;&lt;img src=&#34;http://mpcabd.xyz/wp-content/uploads/2011/12/Androids-300x105.png&#34; alt=&#34;&#34; title=&#34;Androids&#34; width=&#34;300&#34; height=&#34;105&#34; class=&#34;aligncenter size-medium wp-image-315&#34; srcset=&#34;https://mpcabd.xyz/wp-content/uploads/2011/12/Androids-300x105.png 300w, https://mpcabd.xyz/wp-content/uploads/2011/12/Androids.png 766w&#34; sizes=&#34;(max-width: 300px) 100vw, 300px&#34; /&gt;&lt;/a&gt;Now let’s move to business, so I was working on an &lt;a href=&#34;http://developer.android.com/index.html&#34; title=&#34;Android Developers&#34;&gt;Android&lt;/a&gt; application and I needed to log some debug messages, normally I’d use &lt;code&gt;Log.d(TAG, message);&lt;/code&gt; and this will send the message to &lt;a href=&#34;http://developer.android.com/guide/developing/tools/logcat.html&#34; title=&#34;logcat | Android Developers&#34;&gt;logcat&lt;/a&gt;, but logcat is not useful for long messages, like for example if I needed to log the response I received from a web service, this response might be long and sending it to logcat will truncate it.&lt;/p&gt;</description>
      <content:encoded><![CDATA[<p>It’s been a long time since the last time I blogged about something, and many things have changed since then,</p>
<p>I graduated, got engaged and moved to Dubai.</p>
<p>I have plenty of things in my mind to blog about, many solutions and many tools that I developed that I’d like to share it with everyone, but I haven’t settled down, and my schedule is not stable yet, so I haven’t got enough time to sort things out and start blogging, anyway this post is simple and it doesn’t need much description so I thought I’d share it with you now.</p>
<p><a href="http://mpcabd.xyz/wp-content/uploads/2011/12/Androids.png" rel="lightbox[310]" title="Androids"><img src="http://mpcabd.xyz/wp-content/uploads/2011/12/Androids-300x105.png" alt="" title="Androids" width="300" height="105" class="aligncenter size-medium wp-image-315" srcset="https://mpcabd.xyz/wp-content/uploads/2011/12/Androids-300x105.png 300w, https://mpcabd.xyz/wp-content/uploads/2011/12/Androids.png 766w" sizes="(max-width: 300px) 100vw, 300px" /></a>Now let’s move to business, so I was working on an <a href="http://developer.android.com/index.html" title="Android Developers">Android</a> application and I needed to log some debug messages, normally I’d use <code>Log.d(TAG, message);</code> and this will send the message to <a href="http://developer.android.com/guide/developing/tools/logcat.html" title="logcat | Android Developers">logcat</a>, but logcat is not useful for long messages, like for example if I needed to log the response I received from a web service, this response might be long and sending it to logcat will truncate it.</p>
<p>So usually in such situations we use files and log whatever we need inside them, but I’m working on an Android phone/emulator, and dealing with files and logging to them and reading them later from the computer will be a tedious thing to do, so I came up with a simple solution to log messages from Android to my computer.</p>
<p>The idea is to create a simple web server that accepts POST requests, these requests have only one parameter which is the data to be logged. I made it as simple as possible, I could have defined levels for logging and tags and other sorts of things, but I wanted a simple solution that wouldn’t take more than five minutes to write and get it working.</p>
<h3 id="simple-web-server">Simple web server</h3>
<p>Since I’m a pythonist geek I couldn’t think of anything better than Python to implement the simple web server, and it was really great, since I didn’t have to write so much code!</p>
<p>I’ll be using <code>HTTPServer</code> and <code>BaseHTTPRequestHandler</code> from <a href="http://docs.python.org/library/basehttpserver.html">BaseHTTPServer</a> module, some <a href="http://docs.python.org/library/threading.html">threading</a> and <a href="http://docs.python.org/library/cgi.html">cgi</a>.</p>
<pre class="lang:python decode:true">from BaseHTTPServer import HTTPServer, BaseHTTPRequestHandler

import threading
import cgi
import time

IP = '192.168.1.3'
PORT = 5500

LOG_FILE = r'C:\AndroidLogFile.log'

POST_PARAMETER = 'log'
</pre>
<p>I set the server to run on port 5500, don’t ask why I chose this number, I didn’t think of it 😛</p>
<p>I define a function that will execute a function in a separate thread as a daemon thread:</p>
<pre class="lang:python decode:true">def startThread(fn):
    thread = threading.Thread(target=fn)
    thread.setDaemon(True)
    thread.start()
    return thread
</pre>
<p>I define the block of code to be executed when running the server:</p>
<pre class="lang:python decode:true">if __name__ == '__main__':
    httpd = HTTPServer((IP, PORT), lambda *args, **kwargs: LogHandler(*args, **kwargs))
    serve_thread  = startThread(httpd.serve_forever)
    while serve_thread.isAlive():
        serve_thread.join(timeout=1)
</pre>
<p>Here I created an HTTP web server that is bound to the IP/PORT set at the beginning of the script, and I mapped the handler for this web server to a class called LogHandler.</p>
<p>This handler will handle the requests, and hence it’ll handle POST requests and save their contents into the specified file.</p>
<pre class="lang:python decode:true">class LogHandler(BaseHTTPRequestHandler):
    def __init__(self, *args, **kwargs):
        BaseHTTPRequestHandler.__init__(self, *args, **kwargs)

    def do_POST(self):
        length = int(self.headers.getheader('content-length'))
        postvars = cgi.parse_qs(self.rfile.read(length), keep_blank_values=1)
        f = open(LOG_FILE, 'a')
        f.write('%s:\n%s\n%s\n' % (time.strftime('%Y/%m/%d %H:%M:%S'), postvars[POST_PARAMETER][0], '*' * 20))
        f.close()

        self.send_response(200)
        self.send_header('Content-Type', 'text/plain')
        self.send_header('Cache-Control', 'no-cache')
        self.end_headers()
        self.wfile.write('Saved!')
</pre>
<p>Pretty simple, not more than 35 lines of code!</p>
<p>Now let’s move to the Android/Java side.</p>
<h3 id="androidjava-class">Android/Java class</h3>
<p>This class will be responsible for sending POST requests to the server, I’ll be using Apache classes to do the HTTP requests, and I’ll use some other classes from Java standard library, along with Android log class to log exceptions.</p>
<pre class="lang:java decode:true">import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.methods.HttpUriRequest;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;

import android.util.Log;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Map.Entry;
</pre>
<p>The class starts with defining some constants:</p>
<pre class="lang:java decode:true">public class LogToFile {
	private static final String LOG_TO_FILE_ADDRESS = "http://192.168.1.3";
	private static final String LOG_TO_FILE_URL = "/";
	private static final String LOG_TO_FILE_LOG_PARAMETER = "log";
	private static final int LOG_TO_FILE_PORT = 5500;
</pre>
<p>Then I define a method that constructs an HTTP POST request to the specified url along with the specified parameters:</p>
<pre class="lang:java decode:true">private static HttpPost Post(String url, HashMap&lt;String, String> params, HashMap&lt;String, ArrayList&lt;String>> arrayParams) {
		try {
			if (!url.endsWith("/"))
				url += "/";
			List&lt;NameValuePair> params_list = null;
			if (params != null) {
				params_list = new LinkedList&lt;NameValuePair>();
				for (Entry&lt;String, String> entry : params.entrySet())
					params_list.add(new BasicNameValuePair(entry.getKey(), entry.getValue()));
			}
			if (arrayParams != null) {
				if (params_list == null)
					params_list = new LinkedList&lt;NameValuePair>();
				for (Entry&lt;String, ArrayList&lt;String>> entry : arrayParams.entrySet())
					for (String value : entry.getValue())
						params_list.add(new BasicNameValuePair(entry.getKey(), value));
			}
			HttpPost request = new HttpPost(url);
			if (params != null)
				request.setEntity(new UrlEncodedFormEntity(params_list, "utf-8"));
			return request;
		} catch (Exception e) {
			Log.e("", e.getClass().getName() + "\n" + e.getMessage());
		}
		return null;
	}
</pre>
<p>I know this is a lot of code for such thing, but this method is used elsewhere in my application and that’s why it had to be this generic.</p>
<p>Another method will be used to execute the request, also it is generic to be used elsewhere, you can edit the code and make it more specific to your needs.</p>
<pre class="lang:java decode:true">private static HttpResponse ExecuteRequest(HttpUriRequest request) {
		try {
			HttpClient httpclient = new DefaultHttpClient();
			HttpResponse response = httpclient.execute(request);
			return response;
		} catch (Exception e) {
			Log.e("", e.getClass().getName() + "\n" + e.getMessage());
		}
		return null;
	}
</pre>
<p>And now to the final piece of code here, this is the method that you’ll call from anywhere in your application to log messages to the file:</p>
<pre class="lang:java decode:true">public static void LogToFile(String log) {
		try {
			HashMap&lt;String, String> params = new HashMap&lt;String, String>();
			params.put(LOG_TO_FILE_LOG_PARAMETER, log);
			HttpPost request = Post(String.format("%s:%d%s", LOG_TO_FILE_ADDRESS, LOG_TO_FILE_PORT, LOG_TO_FILE_URL), params, null);
			HttpResponse response = ExecuteRequest(request);
			response.getEntity().consumeContent();
		} catch (Exception e) {
			Log.e("", e.getClass().getName() + "\n" + e.getMessage());
		}
	}
</pre>
<h3 id="download">Download</h3>
<p>The source code is licensed under the <a href="http://www.gnu.org/copyleft/gpl.html">GNU Public License (GPL)</a>.</p>
<p><a href="https://github.com/mpcabd/android-log-to-pc-file">Project on GitHub</a></p>
<p>You can download the source code from here:</p>
<p><a href="https://github.com/mpcabd/android-log-to-pc-file/tarball/master">Source code from GitHub</a></p>]]></content:encoded>
    </item>
    <item>
      <title>Collaborative Software Development with SVN Lecture</title>
      <link>https://mpcabd.xyz/collaborative-software-development-with-svn-lecture/</link>
      <pubDate>Tue, 19 Oct 2010 20:40:12 +0000</pubDate>
      <guid>https://mpcabd.xyz/collaborative-software-development-with-svn-lecture/</guid>
      <description>&lt;p&gt;Today I gave a lecture in my faculty about “Collaborative Software Development with SVN”, it was prepared and set by the collaboration of iCommunity, Syrian Computer Society and Damascus University.&lt;/p&gt;
&lt;p&gt;The lecture included the following points:&lt;/p&gt;
&lt;ol&gt;
&lt;li&gt;A Tribute to &lt;a href=&#34;http://en.wikipedia.org/wiki/Mahmoud_Darwish&#34;&gt;Mahmoud Darwish&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;iCommunity Introduction&lt;/li&gt;
&lt;li&gt;Introduction&lt;/li&gt;
&lt;li&gt;Problem Definition&lt;/li&gt;
&lt;li&gt;Introducing &lt;strong&gt;V&lt;/strong&gt;ersion &lt;strong&gt;C&lt;/strong&gt;ontrol &lt;strong&gt;S&lt;/strong&gt;ystem&lt;/li&gt;
&lt;li&gt;Definitions&lt;/li&gt;
&lt;li&gt;How it works&lt;/li&gt;
&lt;li&gt;Introducing SVN&lt;/li&gt;
&lt;li&gt;How to SVN:
&lt;ol&gt;
&lt;li&gt;Hosting Projects.&lt;/li&gt;
&lt;li&gt;Local Servers.&lt;/li&gt;
&lt;li&gt;Installing TortoiseSVN.&lt;/li&gt;
&lt;li&gt;Basic Operations&lt;/li&gt;
&lt;li&gt;Advanced Operations.&lt;/li&gt;
&lt;/ol&gt;
&lt;/li&gt;
&lt;li&gt;Conclusion&lt;/li&gt;
&lt;/ol&gt;</description>
      <content:encoded><![CDATA[<p>Today I gave a lecture in my faculty about “Collaborative Software Development with SVN”, it was prepared and set by the collaboration of iCommunity, Syrian Computer Society and Damascus University.</p>
<p>The lecture included the following points:</p>
<ol>
<li>A Tribute to <a href="http://en.wikipedia.org/wiki/Mahmoud_Darwish">Mahmoud Darwish</a></li>
<li>iCommunity Introduction</li>
<li>Introduction</li>
<li>Problem Definition</li>
<li>Introducing <strong>V</strong>ersion <strong>C</strong>ontrol <strong>S</strong>ystem</li>
<li>Definitions</li>
<li>How it works</li>
<li>Introducing SVN</li>
<li>How to SVN:
<ol>
<li>Hosting Projects.</li>
<li>Local Servers.</li>
<li>Installing TortoiseSVN.</li>
<li>Basic Operations</li>
<li>Advanced Operations.</li>
</ol>
</li>
<li>Conclusion</li>
</ol>
<p>The lecture went well, and I hope that students will start using such technologies during their projects.</p>
<p>You can download the presentation slides from here:</p>
<p><a href="http://bit.ly/huppKY">iCommunity – Collaborative Software Development with SVN Power Point 2007</a></p>
<p><a href="http://bit.ly/foXo2j">iCommunity – Collaborative Software Development with SVN Power Point 97 – 2003</a></p>]]></content:encoded>
    </item>
    <item>
      <title>Google Buzz, OAuth And Python</title>
      <link>https://mpcabd.xyz/google-buzz-oauth-and-python/</link>
      <pubDate>Mon, 27 Sep 2010 21:18:45 +0000</pubDate>
      <guid>https://mpcabd.xyz/google-buzz-oauth-and-python/</guid>
      <description>&lt;p&gt;&lt;a href=&#34;http://www.google.com/buzz&#34;&gt;Google Buzz&lt;/a&gt; is a social networking and messaging tool from Google Inc. that’s integrated into &lt;a href=&#34;http://www.gmail.com&#34;&gt;GMail&lt;/a&gt;. Google Buzz was released in early February this year (9th Feb 2010), and since then it has emerged as an important social network for GMail users, and many people (including me) prefer it now to other social networking platforms such as &lt;a href=&#34;http://www.facebook.com&#34;&gt;Facebook&lt;/a&gt;.&lt;/p&gt;
&lt;figure id=&#34;attachment_268&#34; style=&#34;width: 145px&#34; class=&#34;wp-caption alignleft&#34;&gt;&lt;a href=&#34;http://mpcabd.xyz/wp-content/uploads/2010/09/GoogleBuzzOAuthPython.png&#34; rel=&#34;lightbox[264]&#34; title=&#34;Logos of Google Buzz, OAuth And Python&#34;&gt;&lt;img src=&#34;http://mpcabd.xyz/wp-content/uploads/2010/09/GoogleBuzzOAuthPython.png&#34; alt=&#34;Logos of Google Buzz, OAuth And Python&#34; title=&#34;Logos of Google Buzz, OAuth And Python&#34; width=&#34;145&#34; height=&#34;150&#34; class=&#34;size-full wp-image-268&#34; /&gt;&lt;/a&gt;&lt;figcaption class=&#34;wp-caption-text&#34;&gt;Logos of Google Buzz, OAuth And Python&lt;/figcaption&gt;&lt;/figure&gt;
&lt;p&gt;In May Google revealed the &lt;a href=&#34;http://code.google.com/apis/buzz/docs/&#34;&gt;Buzz API&lt;/a&gt; to the public so developers around the world could write applications to interact with Google Buzz to read and/or write.&lt;/p&gt;</description>
      <content:encoded><![CDATA[<p><a href="http://www.google.com/buzz">Google Buzz</a> is a social networking and messaging tool from Google Inc. that’s integrated into <a href="http://www.gmail.com">GMail</a>. Google Buzz was released in early February this year (9th Feb 2010), and since then it has emerged as an important social network for GMail users, and many people (including me) prefer it now to other social networking platforms such as <a href="http://www.facebook.com">Facebook</a>.</p>
<figure id="attachment_268" style="width: 145px" class="wp-caption alignleft"><a href="http://mpcabd.xyz/wp-content/uploads/2010/09/GoogleBuzzOAuthPython.png" rel="lightbox[264]" title="Logos of Google Buzz, OAuth And Python"><img src="http://mpcabd.xyz/wp-content/uploads/2010/09/GoogleBuzzOAuthPython.png" alt="Logos of Google Buzz, OAuth And Python" title="Logos of Google Buzz, OAuth And Python" width="145" height="150" class="size-full wp-image-268" /></a><figcaption class="wp-caption-text">Logos of Google Buzz, OAuth And Python</figcaption></figure>
<p>In May Google revealed the <a href="http://code.google.com/apis/buzz/docs/">Buzz API</a> to the public so developers around the world could write applications to interact with Google Buzz to read and/or write.</p>
<p>Google uses OAuth for authentication and authorization to their services. OAuth is an open standard that allows users to share their content (or data generally) from one site to another (or to an application generally) without having to hand the other site their credentials. For more information about OAuth Open Standard go <a href="http://oauth.net/">here</a></p>
<p>I was digging around to make a small application to notify me of new Buzzes or new comments on Buzzes, so I searched and read the API to interact with Google Buzz. In this post I’ll share my Python code that uses OAuth to authorize the application to use Google Buzz data, and soon I’ll share my application when it’s done 🙂</p>
<!--more-->
<h1 id="the-process">The Process</h1>
<p>The process of authentication and authorization according to OAuth consists of three steps:</p>
<ol>
<li>Asking Google for a <code>Request Token</code>. The token is bound to a scope, this scope identifies the interests of your application with the user’s data.</li>
</ol>
<pre><code>&lt;a id=&quot;GoogleBuzzScopes&quot;&gt;&lt;/a&gt;Google Buzz has two scopes; Full Access scope `https://www.googleapis.com/auth/buzz` and Read Only Scope `https://www.googleapis.com/auth/buzz.readonly`, you must select the scope that suits your needs.
</code></pre>
<ol start="2">
<li>Asking the user to authorize your needs by redirecting him/her to a page in Google’s website to log in and authorize your application. As a result the user gets a verification code that must be delivered to your application so it can continue to step 3. There are three ways of getting the verification from the user listed <a href="http://code.google.com/apis/accounts/docs/OAuthForInstalledApps.html#tokensLaunchingBrowser">here</a>.</li>
<li>Exchanging the <code>Request Token</code> for an <code>Access Token</code> that can be used later for authorizing your requests for data. Your application should save this token to use it later, this token has unlimited expiration time, so you don’t need to bother the user with authorization more than once (Unless the user revokes the access of your application from his/her account).</li>
</ol>
<h1 id="prerequisites">Prerequisites</h1>
<ul>
<li>My class depends on <a href="http://github.com/simplegeo/python-oauth2">Python-OAuth2</a>, so you need to download and install it first.</li>
<li>The code is written using Python 2.6.</li>
</ul>
<h1 id="general-parameters">General Parameters</h1>
<p>All OAuth requests must have the following parameters:</p>
<ul>
<li><strong>oauth_version</strong>: Which defines the version of OAuth to use (since when writing this post there were only 1.0 and 1.0a I’ll be using 1.0).</li>
<li><strong>oauth_nonce</strong>: A pseudo-random number.</li>
<li><strong>oauth_timestamp</strong>: The timestamp when generating the request.</li>
<li><strong>oauth_signature_method</strong>: The signature method used to sign the base string that identifies the request, which is either <code>HMAC-SHA1</code> or <code>RSA-SHA1</code> (It can be <code>PLAINTEXT</code> but Google doesn’t support it).</li>
<li><strong>oauth_consumer_key</strong> and <strong>oauth_consumer_secret</strong>: The key and secret of your application, if you have registered your application then you’ll have a pair of key and secret for your application. If you don’t have a registered application you can use <code>anonymous</code> for both key and secret.</li>
<li><strong>oauth_signature</strong>: Which is generated using the chosen signature method for the base string which identifies the request</li>
</ul>
<p>So basically we’ll need to add those parameters to every request we make and we’ll have to sign the request. The former is done internally by calling <code>__getParams</code>, while the latter is done internally by calling <code>__signRequest</code> for each request.</p>
<h1 id="getting-the-request-token">Getting The Request Token</h1>
<p>This request has the following parameters added to the general parameters:</p>
<ul>
<li><strong>oauth_callback</strong>: The URL that the user would be redirected to after authorizing your application, and when redirected the verification code is passed to this URL as a parameter along other token parameters. If you don’t have a URL or can’t redirect the user for some reasons you can use the special value <code>oob</code> (Out Of Bounds) so that Google redirects the user to a page in Google’s website that has the verification code inside it.</li>
<li><strong>scope</strong>: The scope you selected for your application from <a href="#GoogleBuzzScopes">here</a>.</li>
<li><strong>xoauth_displayname</strong>: The friendly name of your application that will Google will use when asking the user to authorize it.</li>
</ul>
<p>This procedure is done by sending a <code>POST</code> request to the following URL <code>https://www.google.com/accounts/OAuthGetRequestToken</code> with the previous parameters while setting the <code>ContentType</code> header to <code>application/x-www-form-urlencoded</code>.</p>
<p>The response must be <code>Request Token</code> data with status code <code>HTTP 200</code>.</p>
<pre class="lang:python decode:true">params = self.__getParams()
params.update({'oauth_callback' : self.callbackURL, 'scope' : self.defaultScope, 'xoauth_displayname' : self.applicationName})
oauthRequest = oauth.Request(method="POST", url=REQUEST_TOKEN_URL, parameters=params)
self.__signRequest(oauthRequest)
self.connection.request('POST', REQUEST_TOKEN_URL, body=oauthRequest.to_postdata(), headers={'Content-Type': 'application/x-www-form-urlencoded'})
resp = self.connection.getresponse()
if resp.status != 200:
	raise Exception, "Couldn't get a Request Token, status code: %d." % resp.status
self._token = oauth.Token.from_string(resp.read())
self.__destroyConnection()
</pre>
<p>This method <code>__destroyConnection</code> is used to destroy the connection because it becomes invalid after a few requests.</p>
<h1 id="redirecting-the-user-to-authorization-page">Redirecting The User To Authorization Page</h1>
<p>Here we’ll have to know what is the URL of the page to redirect the user to, and that’s done by sending a <code>GET</code> request to the following URL <code>https://www.google.com/buzz/api/auth/OAuthAuthorizeToken</code> with the following parameters:</p>
<ul>
<li><strong>oauth_token</strong>: The key of the <code>Request Token</code> received in the previous step.</li>
<li><strong>scope</strong>: Described earlier.</li>
<li><strong>domain</strong>: The domain that your application uses, this is used for web applications, you must set it to anonymous for desktop applications.</li>
<li><strong>xoauth_displayname</strong>: Described earlier.</li>
</ul>
<p>The response would be a page with <code>HTTP 302</code> status code, this page contains the URL to redirect the user to in the <code>location</code> header.</p>
<pre class="lang:python decode:true">self.connection.request('GET', AUTHORIZE_TOKEN_URL + '?oauth_token=' + self.token.key + '&scope=' + self.defaultScope + '&domain=anonymous' + '&' + urllib.urlencode({'xoauth_displayname' : self.applicationName}).replace('+', '%20'))
resp = self.connection.getresponse()
if resp.status != 302:
	raise Exception, "Couldn't authorize the token, status code: %d." % resp.status
url = resp.getheader('location')
webbrowser.open(url)
self.__destroyConnection()
</pre>
<p>This method <code>webbrowser.open</code> is used to open the URL in the web browser of the user, it is -obviously- contained in the <code>webbrowser</code> Python standard module.</p>
<p>As a result of the authorization Google gives you (or the user) the verification code for the token, after acquiring it (automatically or by asking the user to give it to your application somehow) we give it to the token by calling <code>setTokenVerifier</code> method.</p>
<h1 id="exchanging-the-request-token-for-the-access-token">Exchanging The Request Token For The Access Token</h1>
<p>This request has the following parameters added to the general parameters:</p>
<ul>
<li><strong>oauth_token</strong>: Described earlier.</li>
<li><strong>oauth_verifier</strong>: The verification code acquired from the previous step.</li>
</ul>
<p>This procedure is done by sending a <code>POST</code> request with the previous parameters to the following URL <code>https://www.google.com/accounts/OAuthGetAccessToken</code>.</p>
<p>The result is the <code>Access Token</code> data in a page with <code>HTTP 200</code> status code.</p>
<pre class="lang:python decode:true">params = self.__getParams()
params.update({
'oauth_token' : self.token.key,
'oauth_verifier' : self.token.verifier
})
oauthRequest = oauth.Request(method="POST", url=ACCESS_TOKEN_URL, parameters=params)
self.__signRequest(oauthRequest)
self.connection.request('POST', ACCESS_TOKEN_URL, body=oauthRequest.to_postdata(), headers={'Content-Type': 'application/x-www-form-urlencoded'})
resp = self.connection.getresponse()
if resp.status != 200:
        raise Exception, "Couldn't exchange the token with an Access Token, status code: %d.\nMessage: %s" % (resp.status, resp.read())
self._token = oauth.Token.from_string(resp.read())
self.__destroyConnection()
</pre>
<h1 id="authorizing-requests">Authorizing Requests</h1>
<p>Authorizing your requests for data is done by adding <code>Authorization</code> header to your request which includes the OAuth parameters along with the <code>Access Token</code> data, and by setting the <code>ContentType</code> header to either <code>application/json</code> or <code>application/atom+xml</code>:</p>
<pre class="lang:python decode:true">params = self.__getParams()
params.update({
	'oauth_token' : self.token.key,
})
oauthRequest = oauth.Request(method=method, url=url, parameters=params)
self.__signRequest(oauthRequest)
if isJSON:
	headers = {'Content-Type': 'application/json'}
else:
	headers = {'Content-Type': 'application/atom+xml'}
headers.update(oauthRequest.to_header())
self.connection.request(method, url, body=body, headers=headers)
resp = self.connection.getresponse()
data = resp.read()
self.__destroyConnection()
return resp.status, data
</pre>
<h1 id="example-on-using-buzzoauth-class">Example On Using BuzzOAuth Class</h1>
<p>This example uses the BuzzOAuth class to get the list of Buzzes for the user to read (The list of his/her friends’ Buzzes).</p>
<pre class="lang:python decode:true">from BuzzOAuth import BuzzOAuth

boauth = BuzzOAuth()
boauth.requestToken()
boauth.authorizeToken()
boauth.setTokenVerifier(raw_input('Enter the verifier please: '))
boauth.convertToAccessToken()
boauth.saveTokenToFile()
status, data = boauth.request('GET', 'https://www.googleapis.com/buzz/v1/activities/@me/@consumption?alt=json')
print status
print ""
print data
</pre>
<p>The method <code>request</code> uses the <code>Access Token</code> to do the request passed to it and returns a tuple of the status code and data returned by the request.</p>
<p>In line 8 the call for method <code>saveTokenToFile</code> saves the <code>Access Token</code> to a binary file called <code>token.tok</code> by default, so that the application can later just use this token like this:</p>
<pre class="lang:python decode:true">from BuzzOAuth import BuzzOAuth
		
boauth = BuzzOAuth()
boauth.loadTokenFromFile()
status, data = boauth.request('GET', 'https://www.googleapis.com/buzz/v1/activities/@me/@consumption?alt=json')
print status
print ""
print data
</pre>
<h1 id="download">Download</h1>
<p>You can download this class (BuzzOAuth.py) from here: <a href="http://www.box.net/shared/2m9srr12z7">http://www.box.net/shared/2m9srr12z7</a></p>
<h1 id="license">License</h1>
<p>This work is licensed under the GNU Public License (GPL). To view a copy of this license, visit <a href="http://www.gnu.org/copyleft/gpl.html">http://www.gnu.org/copyleft/gpl.html</a>.</p>]]></content:encoded>
    </item>
    <item>
      <title>Google Talk Status Countdown</title>
      <link>https://mpcabd.xyz/google-talk-status-countdown/</link>
      <pubDate>Tue, 25 May 2010 19:46:21 +0000</pubDate>
      <guid>https://mpcabd.xyz/google-talk-status-countdown/</guid>
      <description>&lt;p&gt;A few days ago I was counting down to a presentation in my faculty. As I was setting counters all over my world (Side Bar Gadget, To Do List) I thought of a way to change my Google Talk status to a counter also.&lt;/p&gt;
&lt;p&gt;Since I know that Google Talk uses &lt;a href=&#34;http://www.xmpp.org&#34;&gt;XMPP&lt;/a&gt; protocol, and since my friends and I implemented XMPP last year in our faculty I tried to make a program to set my status to a counter; and here is the result:&lt;/p&gt;
&lt;p&gt;&lt;a href=&#34;http://mpcabd.xyz/wp-content/uploads/2010/05/XMPPStatusChanger.png&#34; rel=&#34;lightbox[231]&#34; title=&#34;XMPP Status Changer&#34;&gt;&lt;img src=&#34;http://mpcabd.xyz/wp-content/uploads/2010/05/XMPPStatusChanger-300x190.png&#34; alt=&#34;XMPP Status Changer&#34; title=&#34;XMPP Status Changer&#34; width=&#34;300&#34; height=&#34;190&#34; class=&#34;alignnone size-medium wp-image-234&#34; srcset=&#34;https://mpcabd.xyz/wp-content/uploads/2010/05/XMPPStatusChanger-300x190.png 300w, https://mpcabd.xyz/wp-content/uploads/2010/05/XMPPStatusChanger.png 484w&#34; sizes=&#34;(max-width: 300px) 100vw, 300px&#34; /&gt;&lt;/a&gt;&lt;/p&gt;</description>
      <content:encoded><![CDATA[<p>A few days ago I was counting down to a presentation in my faculty. As I was setting counters all over my world (Side Bar Gadget, To Do List) I thought of a way to change my Google Talk status to a counter also.</p>
<p>Since I know that Google Talk uses <a href="http://www.xmpp.org">XMPP</a> protocol, and since my friends and I implemented XMPP last year in our faculty I tried to make a program to set my status to a counter; and here is the result:</p>
<p><a href="http://mpcabd.xyz/wp-content/uploads/2010/05/XMPPStatusChanger.png" rel="lightbox[231]" title="XMPP Status Changer"><img src="http://mpcabd.xyz/wp-content/uploads/2010/05/XMPPStatusChanger-300x190.png" alt="XMPP Status Changer" title="XMPP Status Changer" width="300" height="190" class="alignnone size-medium wp-image-234" srcset="https://mpcabd.xyz/wp-content/uploads/2010/05/XMPPStatusChanger-300x190.png 300w, https://mpcabd.xyz/wp-content/uploads/2010/05/XMPPStatusChanger.png 484w" sizes="(max-width: 300px) 100vw, 300px" /></a></p>
<h1 id="the-basic-idea-behind-status-changing">The basic idea behind status changing</h1>
<p>Since Google Talk uses <a href="http://www.xmpp.org">XMPP</a> then if you can connect using an XMPP client to your Google account you can use the client instead of Google talk. But indeed that’s not what we want here, we want to use Google Talk while changing the status automatically.</p>
<p>I searched to see if there were an API to communicate with Google Talk from any other program but I had no luck.</p>
<p>So the solution was to use XMPP’s Presence Priority attribute.</p>
<p>In <a href="http://www.xmpp.org">XMPP</a>, a user can connect from multiple clients with the same ID, each client will have a unique `resource` so messages sent from one client get their replies to the same client. But what about status? XMPP has an attribute sent with each status (Status is called Presence in XMPP) which is `Priority`, this attribute describes the priority of this resource presence. In Google Talk the highest priority is 24. So if you can change the priority of the automatic presence to 24 it will be considered high priority and its status will appear instead of the old one.</p>
<h1 id="programming-it">Programming it</h1>
<p>I used Java for developing the program. There is no direct reason for using Java but that’s what I used 🙂</p>
<p>To be able to use XMPP I used the <a href="http://www.igniterealtime.org/downloads/index.jsp">Smack XMPP Library</a> because it is simple and serves me well.</p>
<p>The whole mechanism is too simple:</p>
<ol>
<li>Login.</li>
<li>Calculate difference between now and the targeted date.</li>
<li>Send the presence.</li>
</ol>
<p>Using Smack makes the whole process so easy.</p>
<h2 id="login">Login</h2>
<pre class="lang:java decode:true">import org.jivesoftware.smack.XMPPConnection;

public void connect() {
    XMPPConnection connection = new XMPPConnection(server); //Server is gmail.com for Google Talk.
    connection.connect();
    connection.login(username, password); //Username and password.
}
</pre>
<h2 id="calculate-difference-between-now-and-the-targeted-date">Calculate difference between now and the targeted date</h2>
<p>This process is done using Java Calendar and Date objects:</p>
<pre class="lang:java decode:true">import java.util.Calendar;
import java.util.Date;

{
        Calendar calendar1 = Calendar.getInstance();
        Date d = new Date();
        calendar1.setTime(d);

        Calendar calendar2 = Calendar.getInstance();
        calendar2.setTime(endLine); //End line is the date we're counting to.

        long milliseconds1 = calendar1.getTimeInMillis();
        long milliseconds2 = calendar2.getTimeInMillis();
        long diff = milliseconds2 - milliseconds1;

        long diffDays = diff / (24 * 60 * 60 * 1000);
        diff = diff % (24 * 60 * 60 * 1000);

        long diffHours = diff / (60 * 60 * 1000);
        diff = diff % (60 * 60 * 1000);

        long diffMinutes = diff / (60 * 1000);
        diff = diff % (60 * 1000);
}
</pre>
<p>This code calculates the difference between the two dates in days, hours and minutes.</p>
<h2 id="send-the-presence">Send the presence</h2>
<p>After calculating the difference all we have to do is to send the presence:</p>
<pre class="lang:java decode:true">import org.jivesoftware.smack.packet.Presence;

{
         String remaining = Long.toString(diffDays) + " day(s), " + Long.toString(diffHours) + " hour(s), " + Long.toString(diffMinutes) + " minute(s) " + message; //Message is usually: Until "something".

        Presence presence = new Presence(Presence.Type.available);
        presence.setStatus(remaining);
        presence.setPriority(24); //Highest priority in Google Talk
        presence.setMode(presenceMode); //This is one of XMPP modes (Available, Chat, DND, Away, XA).
        connection.sendPacket(presence);
}
</pre>
<p>After this point people will see your new status instead of the one in Google Talk. (Notice that you won’t be able to see the change inside Google Talk but rest assured it is changed ;)).</p>
<h1 id="testing">Testing</h1>
<p><a href="http://mpcabd.xyz/wp-content/uploads/2010/05/XMPPStatusChanger2.png" rel="lightbox[231]" title="XMPP Status Changer Test"><img src="http://mpcabd.xyz/wp-content/uploads/2010/05/XMPPStatusChanger2-300x127.png" alt="XMPP Status Changer Test" title="XMPP Status Changer Test" width="300" height="127" class="alignnone size-medium wp-image-242" srcset="https://mpcabd.xyz/wp-content/uploads/2010/05/XMPPStatusChanger2-300x127.png 300w, https://mpcabd.xyz/wp-content/uploads/2010/05/XMPPStatusChanger2.png 493w" sizes="(max-width: 300px) 100vw, 300px" /></a></p>
<h1 id="last-note">Last note</h1>
<p>The GUI is self explanatory, just make sure you enter a big value for “Update Interval” because when you’re talking to others and your status changes they’ll have a red line with the new status in the conversation window and certainly you don’t want them to be distracted by the counter from the real conversation.</p>
<p>And BTW, you can use this program with any XMPP account, not just Google Talk. And it’s cross platform 😉</p>
<h1 id="download">Download</h1>
<p>Google Talk Status Countdown on <a href="https://github.com/mpcabd/gtalk-status-countdown">GitHub</a></p>
<p>Smack library is attached to the files already, no need to download it separately.</p>
<ul>
<li><a href="https://github.com/mpcabd/gtalk-status-countdown/tarball/master">Source Code</a></li>
<li><a href="https://github.com/downloads/mpcabd/gtalk-status-countdown/statusChangerExecutable.tar.gz">Executable Jar File</a></li>
</ul>
<p>Hope you use it 🙂</p>]]></content:encoded>
    </item>
    <item>
      <title>Display Sub-terms In Drupal Term Page</title>
      <link>https://mpcabd.xyz/display-sub-terms-in-drupal-term-page/</link>
      <pubDate>Tue, 30 Mar 2010 22:06:42 +0000</pubDate>
      <guid>https://mpcabd.xyz/display-sub-terms-in-drupal-term-page/</guid>
      <description>&lt;p&gt;After working with Drupal in the last two months I’ve really got used to searching for modules for every problem I face and installing them.&lt;/p&gt;
&lt;p&gt;While I was working on &lt;a href=&#34;http://www.communityi.net&#34;&gt;iCommunity website&lt;/a&gt;, I was creating taxonomy terms to categorize the files using them. I created terms with sub terms. The problem was that when browsing a specified term the term page doesn’t display the sub terms of that term.&lt;/p&gt;</description>
      <content:encoded><![CDATA[<p>After working with Drupal in the last two months I’ve really got used to searching for modules for every problem I face and installing them.</p>
<p>While I was working on <a href="http://www.communityi.net">iCommunity website</a>, I was creating taxonomy terms to categorize the files using them. I created terms with sub terms. The problem was that when browsing a specified term the term page doesn’t display the sub terms of that term.</p>
<p>I searched the internet and found <a href="http://www.rbgrn.net/content/194-drupal-taxonomy-how-to-add-list-clickable-sub-categories">a solution</a> that’s working.</p>
<p>After trying it I decided to try developing a module for doing that (just like the author of the solution suggested).</p>
<p>I’m a newbie in developing for Drupal but I knew how to dig my way through it 😀</p>
<p>(You’d be shocked if you knew that I don’t know PHP 😛 I just write code!)</p>
<p>So before I start this post please this is the first time I write modules, and I learned it yesterday 😛 so if you find any error or something wrong tell me 🙂</p>
<p>I named the module Taxonomy subterms. 😀</p>
<p>So the process is just re-implement the function <em>‘theme_taxonomy_term_page’</em> from taxonomy module, but to override it I needed to let Drupal call the function in my module when the user requests <em>‘/taxonomy/term/’</em> so to do that I needed to add the <em>‘hook_menu’</em> function.</p>
<pre class="lang:php decode:1">function taxonomy_subterms_menu() {  
  $items['taxonomy/term/%'] = array(
    'title' =&gt; 'Taxonomy term',
    'page callback' =&gt; 'taxonomy_subterms_term_page',
    'page arguments' =&gt; array(2),
    'access arguments' =&gt; array('access content'),
    'type' =&gt; MENU_CALLBACK,
  );
  
  return $items;
}
</pre>
<p>But by doing this I discovered that the Taxonomy module won’t handle the page, so I couldn’t find a way to tell Taxonomy module to handle the page and my module to complete the handling 🙁 So I copied the ‘taxonomy_term_page’ function and renamed it to ‘taxonomy_subterms_term_page’</p>
<p>Then I re-implemented the ‘theme_taxonomy_term_page’ function so I can add the sub-terms section (just like the solution I mentioned did):</p>
<pre class="lang:php decode:1">function theme_taxonomy_term_page($tids, $result) {
  drupal_add_css(drupal_get_path('module', 'taxonomy') . '/taxonomy.css');
  drupal_add_css(drupal_get_path('module', 'taxonomy_subterms') . '/taxonomy_subterms.css');
  $output = '';

  // Only display the description if we have a single term, to avoid clutter and confusion.
  if (count($tids) == 1) {
    $term = taxonomy_get_term($tids[0]);
    $children = taxonomy_get_children($tids[0]);
    $description = $term-&gt;description;
    if (!empty($description) || sizeof($children) &gt; 0) {
      $output .= '&lt;div class="taxonomy-details-wrapper"&gt;';
      $is_wrapped = true;
    } else {
      $is_wrapped = false;
    }
    // Check that a description is set.
    if (!empty($description)) {
      $output .= '&lt;div class="taxonomy-term-description"&gt;';
      $output .= filter_xss_admin($description);
      $output .= '&lt;/div&gt;';
    }
    if (sizeof($children) &gt; 0) {
      $output .= '&lt;div class="sub-terms-list"&gt;&lt;h3&gt;' . t('Sub-Terms:') . '&lt;/h3&gt; &lt;ul class="sub-terms inline"&gt;';
      foreach($children as $child) {
        $output .= '&lt;li&gt;' . l($child-&gt;name, taxonomy_term_path($child)) . '&lt;/li&gt;';
      }
      $output .= '&lt;/ul&gt;&lt;/div&gt;';
    }
    if ($is_wrapped) {
      $output .= '&lt;/div&gt;';
    }
  }

  $output .= taxonomy_render_nodes($result);

  return $output;
}
</pre>
<p>Then I had my module working and installed it in the website (you can check it out <a href="http://www.communityi.net/taxonomy/term/3">here</a>. The page is in Arabic but you can easily find the sub terms).</p>
<h2 id="download">Download</h2>
<p>You can download the module <a href="http://www.box.net/shared/hzahnghh6x">here</a> (I didn’t maintain a project @ Drupal because I’m not yet ready to do that, this is just a small experiment).</p>]]></content:encoded>
    </item>
    <item>
      <title>Simple AJAX Comment Preview in Drupal 6</title>
      <link>https://mpcabd.xyz/simple-ajax-comment-preview-in-drupal-6/</link>
      <pubDate>Mon, 15 Feb 2010 15:15:48 +0000</pubDate>
      <guid>https://mpcabd.xyz/simple-ajax-comment-preview-in-drupal-6/</guid>
      <description>&lt;p&gt;As I said in my previous post, I’m working on upgrading &lt;a href=&#34;http://www.csc-sy.net&#34;&gt;Computer Science in Syria&lt;/a&gt; website to Drupal 6.&lt;/p&gt;
&lt;p&gt;I wanted also to have AJAX comment preview in nodes, but I wanted it to be simple without lots of JavaScript loaded. So as usual I got pissed off and decided to create my own code to do it. 8)&lt;/p&gt;</description>
      <content:encoded><![CDATA[<p>As I said in my previous post, I’m working on upgrading <a href="http://www.csc-sy.net">Computer Science in Syria</a> website to Drupal 6.</p>
<p>I wanted also to have AJAX comment preview in nodes, but I wanted it to be simple without lots of JavaScript loaded. So as usual I got pissed off and decided to create my own code to do it. 8)</p>
<p>I used <a href="http://www.ericmmartin.com/projects/simplemodal/">Simple Modal</a> by Eric Martin to display the preview in a model instead of a new page.</p>
<p>The code is easy too like the previous post’s code, I edited also the drupal.js file and added the following code:</p>
<pre class="lang:javascript decode:true">if (location.pathname.match('^' + Drupal.settings.basePath + 'node/\\d')) {
		$('#edit-preview').click(function () {
			$.modal('&lt;div&gt;&lt;h1&gt;Preview&lt;/h1&gt;&lt;div id="previewContent"&gt;&lt;img style="width: 126px; height: 22px;" class="previewing" src="' + Drupal.settings.basePath + 'misc/previewing.gif" alt="Loading ..." /&gt;&lt;/div&gt;&lt;/div&gt;');
			var comment = $('#edit-comment').val();
			if ($('#wysiwyg-toggle-edit-comment').text() == Drupal.settings.wysiwyg.disable) {
				$('#wysiwyg-toggle-edit-comment').click();
				comment = $('#edit-comment').val();
				$('#wysiwyg-toggle-edit-comment').click();
			}
			$.post(
				$('form#comment-form').attr('action'),
				{
					'comment' : comment,
					'form_build_id' : $('form#comment-form input[name="form_build_id"]').val(),
					'form_id' : 'comment_form',
					'form_token' : $('form#comment-form input[name="form_token"]').val(),
					'op' : $('form#comment-form input#edit-preview').val(),
				},
				function (html) {
					$('div#previewContent img').remove();
					$('div#previewContent').append($(html).children().find('div.preview div.content').html());
					$('form#comment-form input[name="form_token"]').val($(html).children().find('form#comment-form input[name="form_token"]').val());
					$('form#comment-form input[name="form_build_id"]').val($(html).children().find('form#comment-form input[name="form_build_id"]').val());
				}
			);
			return false;
		});
	}
</pre>
<p>The process is too simple:</p>
<ol>
<li>@line 01: I check to see if the current page is a node page, I just want to make the preview code working on node page.</li>
<li>@line 03: I show the user a modal with a loading image <img alt="Loading &hellip;" loading="lazy" src="http://www.csc-sy.net/misc/previewing.gif"></li>
<li>@lines 04~09: I check the editor, if it is enabled I disable it to get the HTML from the comment. If it is not enabled I get the HTML directly without disabling it.</li>
<li>@lines 10~18: I gather the data of the form and post them.</li>
<li>@line 20: I remove the loading image.</li>
<li>@line 21: I append the HTML data from the response to the modal content.</li>
<li>@lines 22~23: I set the form hidden values (form_build_id and form_token) to the values from the response so I don’t get a Validation Error.</li>
<li>@line 26: I return false so the browser doesn’t post the data again to the new page.</li>
</ol>
<p>Here is an example:</p>
<p><a href="http://mpcabd.xyz/wp-content/uploads/2010/02/1.png" rel="lightbox[207]" title="1"><img src="http://mpcabd.xyz/wp-content/uploads/2010/02/1-300x138.png" alt="" title="1" width="300" height="138" class="alignnone size-medium wp-image-211" srcset="https://mpcabd.xyz/wp-content/uploads/2010/02/1-300x138.png 300w, https://mpcabd.xyz/wp-content/uploads/2010/02/1.png 668w" sizes="(max-width: 300px) 100vw, 300px" /></a></p>
<p><a href="http://mpcabd.xyz/wp-content/uploads/2010/02/2.png" rel="lightbox[207]" title="2"><img src="http://mpcabd.xyz/wp-content/uploads/2010/02/2-300x138.png" alt="" title="2" width="300" height="138" class="alignnone size-medium wp-image-211" /></a></p>
<p>Simple 😉</p>]]></content:encoded>
    </item>
    <item>
      <title>Simple AJAX Quote in Drupal 6</title>
      <link>https://mpcabd.xyz/simple-ajax-quote-in-drupal-6/</link>
      <pubDate>Fri, 12 Feb 2010 23:02:34 +0000</pubDate>
      <guid>https://mpcabd.xyz/simple-ajax-quote-in-drupal-6/</guid>
      <description>&lt;p&gt;I’ve been upgrading the forum of &lt;a href=&#34;http://www.csc-sy.net/&#34; target=&#34;_blank&#34;&gt;Computer Science in Syria&lt;/a&gt; for a week now.&lt;/p&gt;
&lt;p&gt;The forum uses Drupal, and it ran a beta version of Drupal 4, and I upgraded it to the latest Drupal version now.&lt;/p&gt;
&lt;p&gt;I wanted to have AJAX quoting in the forum, but I wanted it to be simple without lots of JavaScript loaded. So as usual I got pissed off and decided to create my own code to do it. 8)&lt;/p&gt;</description>
      <content:encoded><![CDATA[<p>I’ve been upgrading the forum of <a href="http://www.csc-sy.net/" target="_blank">Computer Science in Syria</a> for a week now.</p>
<p>The forum uses Drupal, and it ran a beta version of Drupal 4, and I upgraded it to the latest Drupal version now.</p>
<p>I wanted to have AJAX quoting in the forum, but I wanted it to be simple without lots of JavaScript loaded. So as usual I got pissed off and decided to create my own code to do it. 8)</p>
<p>The code was very simple, knowing that the Quote link will get you to a page where the textarea has the quoted text, and knowing that Drupal 6 has <a href="http://jquery.com/">jQuery</a> loaded in it 🙂</p>
<p>I added the following code to /misc/drupal.js file:</p>
<pre class="lang:javascript decode:true">$('a.quote, li.quote a').click(function () {
	$(this).after($('&nbsp;&lt;img style="width: 16px; height: 16px;" class="quoting" src="/misc/quoting.gif" alt="loading" /&gt;'));
	$.ajax({
		url: $(this).attr('href'),
		cache: false,
		success: function(html){
			$('img.quoting').remove();
			var changed = false;
			if ($('#wysiwyg-toggle-edit-comment').text() == Drupal.settings.wysiwyg.disable) {
				$('#wysiwyg-toggle-edit-comment').click();
				changed = true;
			}
			$('#edit-comment').val($('#edit-comment').val() + ($('#edit-comment').val() == '' ? '' : '\n') + $(html).children().find('#edit-comment').val());
			var $target = $('#edit-comment');
			$target = $target.length && $target || $('[name=' + this.hash.slice(1) +']');
			if ($target.length) {
					var targetOffset = $target.offset().top;
					$('html,body').animate({scrollTop: targetOffset}, 1000);
			}
			if (changed)
				$('#wysiwyg-toggle-edit-comment').click();
			$('#edit-comment').scrollTop($('#edit-comment')[0].scrollHeight);
		}
	});
	return false;
});
</pre>
<p>You can see that I used this image to be displayed while loading the quote into the textarea  <img alt="Quoting" loading="lazy" src="http://www.csc-sy.net/misc/quoting.gif">because it matches the colors of the forum style.</p>
<p>The process is too simple:</p>
<ol>
<li>@line 02: Display a loading image.</li>
<li>@line 03: Request the quoting page which is located in the href attribute of the quote link.</li>
<li>@line 07: Remove the image.</li>
<li>@lines 08 ~ 12: Checking if the HTML editor is enabled, and disabling it so I can assign the value directly to the textarea.</li>
<li>@line 13: Assigning the value of the textarea in the quote page to the textarea in this page.</li>
<li>@lines 14 ~ 19: Scrolling the page’s vertical scroll to reach the textarea.</li>
<li>@lines 20 ~ 21: Re-enabling the editor if I disabled it.</li>
<li>@line 22: Scrolling the textarea’s vertical scroll to reach the end of the text.</li>
<li>@line 25: Returning false to the browser so it doesn’t redirect the page to the quoting page.</li>
</ol>
<p>You see? it is as simple as this 🙂</p>
<p>I’ll soon post some other modifications that made the forum more simple 🙂</p>]]></content:encoded>
    </item>
    <item>
      <title>Notepad&#43;&#43; Plugin To Run Python Scripts</title>
      <link>https://mpcabd.xyz/notepad-plugin-to-run-python-scripts/</link>
      <pubDate>Tue, 03 Nov 2009 20:25:44 +0000</pubDate>
      <guid>https://mpcabd.xyz/notepad-plugin-to-run-python-scripts/</guid>
      <description>&lt;p&gt;I use Python everyday, it has become my first tool to use when I need to do anything. In Arabic (in &lt;a href=&#34;http://en.wikipedia.org/wiki/Syria&#34; target=&#34;_blank&#34;&gt;Syrian&lt;/a&gt; Arabic specifically) I’d say that Python has become my hand and leg 😛&lt;/p&gt;
&lt;p&gt;Yesterday I was writing a small Python script to read the YACC file and generate a list of all the specified rules inside it, so I don’t have to scroll through the long file to find out what rules are inside it 😉&lt;/p&gt;
&lt;p&gt;I use Notepad++ as my default text editor on Windows, and I was writing the script using it – Notepad++. I wanted to test if the script is working, so I ran an instance of Command Line Prompt, and as I was going to change the directory to the directory of the script I thought; “Why doesn’t Notepad++ have a &lt;em&gt;Run In Python&lt;/em&gt; command in it?”. So as usual I got pissed off and decided to create my own plugin to have that command in Notepad++ 8)&lt;/p&gt;</description>
      <content:encoded><![CDATA[<p>I use Python everyday, it has become my first tool to use when I need to do anything. In Arabic (in <a href="http://en.wikipedia.org/wiki/Syria" target="_blank">Syrian</a> Arabic specifically) I’d say that Python has become my hand and leg 😛</p>
<p>Yesterday I was writing a small Python script to read the YACC file and generate a list of all the specified rules inside it, so I don’t have to scroll through the long file to find out what rules are inside it 😉</p>
<p>I use Notepad++ as my default text editor on Windows, and I was writing the script using it – Notepad++. I wanted to test if the script is working, so I ran an instance of Command Line Prompt, and as I was going to change the directory to the directory of the script I thought; “Why doesn’t Notepad++ have a <em>Run In Python</em> command in it?”. So as usual I got pissed off and decided to create my own plugin to have that command in Notepad++ 8)</p>
<h3 id="the-reference">The Reference</h3>
<p>I searched on the net, I found this <a href="http://sourceforge.net/projects/notepad-plus/forums/forum/482781/topic/3393597" target="_blank">Notepad++ Plugin Template</a>, I edited it a little bit and I managed to do it 🙂</p>
<p>You can read below about the process and how it works, but if you just came here to <a href="#download">download it click here</a>.</p>
<h3 id="the-process">The Process</h3>
<p>To run a Python script; the plugin must do the following:</p>
<ul>
<li>Get the path of the selected file in Notepad++.</li>
<li>Get the path of Python executable file, since not everyone has Python in the PATH environment variable.</li>
<li>Building the run command.</li>
<li>Execute the run command.</li>
</ul>
<h3 id="get-the-path-of-the-selected-file-in-notepad">Get The Path of The Selected File In Notepad++</h3>
<p>I also searched the net and found the following code:</p>
<pre class="lang:c++ decode:true">std::wstring getCurrentFile(bool &ok)
{
	LRESULT result = ::SendMessage(nppData._nppHandle, NPPM_SAVECURRENTFILE, 0, 0);
	TCHAR path[MAX_PATH];
	::SendMessage(nppData._nppHandle, NPPM_GETFULLCURRENTPATH, MAX_PATH, (LPARAM)path);
	std::wstring wPath(path);
	if (result == 0) {
		ok = false;
		for (int i = 0; i &lt; wPath.length() && !ok; i++)
			if (wPath[i] == '\\')
				ok = true;
	}
	else
		ok = true;
	return wPath;
}
</pre>
<p>The function sends a message to Notepad++ asking it to save the file before trying to run it, the result of the message will be either 1 which means that the file was saved, or 0 which means that the file wasn’t.</p>
<p>Then the function sends a message to Notepad++ asking it to put the full path of the currently selected file into a specific variable.</p>
<p>Now a little problem occurs when the file is unmodified, and the problem is that the first message will return 0 which means that the file wasn’t saved, while the second message will return a valid file path. So the function will search the path for a backslash `` which is the path separator in Windows, because a valid full path must contain at least one separator.</p>
<p>When the path is valid and the file is saved the function returns the path and sets the `ok` parameter to true, while in other cases it will return the path and set `ok` parameter to false.</p>
<h3 id="get-the-path-of-python-executable-file">Get The Path Of Python Executable File</h3>
<p>The plugin will search for Python in its default path (“C:\Python[VER]”). If this method fails the plugin will search in registry for the key.</p>
<pre class="lang:c++ decode:true">bool pythonExists(std::wstring foldername) {
	std::wstring path = L"C:\\";
	path += foldername;
	path += L"\\python.exe";
	WIN32_FIND_DATA data;
	HANDLE h = FindFirstFile(const_cast&lt;LPCWSTR&gt;(path.c_str()), &data);
	return (h != INVALID_HANDLE_VALUE);
}

	//This code will be run before the plugin calls the function 'getPythonLocation'
	std::wstring pythonLoc = L"";
	bool pythonInstalled = false;

	WIN32_FIND_DATA data;
	HANDLE h = FindFirstFile(L"c:\\python*", &data);
	if( h != INVALID_HANDLE_VALUE ) 
	{
		do 
		{
			if (!(data.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY))
				continue;

			char*   nPtr = new char [lstrlen( data.cFileName ) + 1];
			for( int i = 0; i &lt; lstrlen( data.cFileName ); i++ )
				nPtr[i] = char( data.cFileName[i] );

			nPtr[lstrlen( data.cFileName )] = '&#92;&#48;';
			if (pythonExists(const_cast&lt;LPWSTR&gt;(data.cFileName)))
			{
				pythonLoc = L"C:\\";
				pythonLoc += const_cast&lt;LPWSTR&gt;(data.cFileName);
				pythonLoc += L"\\";
				pythonInstalled = true;
				break;
			}
		} while (FindNextFile(h, &data));
	}
</pre>
<p>The Python installation path exists in the Windows Registry, so I wrote a small function to search the registry for the path and return it:</p>
<pre class="lang:c++ decode:true">bool getPythonLocationFromRegistry(std::wstring &loc, HKEY baseKey) {
{
	HKEY hKey;
	if(RegOpenKeyEx(baseKey, TEXT("Software\\Python\\PythonCore"), 0,
		KEY_READ, &hKey) != ERROR_SUCCESS)
	{
		return false;
	}
	DWORD dwIdx=0;
	TCHAR szKeyName[1024];
	DWORD dwSize=1024;
	FILETIME fTime;
	TCHAR pyPath[MAX_PATH];
	DWORD length = MAX_PATH;

	if (RegEnumKeyEx(hKey, dwIdx, szKeyName, &dwSize, NULL, NULL, NULL, &fTime) == ERROR_SUCCESS)
	{
		HKEY hSubKey;
		if (RegOpenKeyEx(hKey, szKeyName, 0, KEY_READ, &hSubKey) == ERROR_SUCCESS)
		{
			LONG x = RegOpenKeyEx(hSubKey, TEXT("InstallPath"), 0, KEY_READ, &hSubKey);
			if (x == ERROR_SUCCESS)
			{
				if(RegQueryValueEx(
					hSubKey,
					TEXT(""),
					NULL,
					NULL,
					(LPBYTE)pyPath,
					&length) != ERROR_SUCCESS)
				{
					return false;
				}

				loc = loc.append(pyPath);
				return true;
			}
			else
				return false;
		}
		else
			return false;
	}
	else
		return false;
}
</pre>
<p>The code above accepts the root key as a parameter, and the code that calls it will call it twice, once with <code>HKEY_CURRENT_USER</code> and the other with <code>HKEY_LOCAL_MACHINE</code>, so it will try to find it in both locations <code>HKEY_CURRENT_USER\Software\Python\PythonCore</code> and <code>HKEY_LOCAL_MACHINE\Software\Python\PythonCore</code>.</p>
<h3 id="building-the-run-command">Building The Run Command</h3>
<p>The plugin allows the user to choose to run the file in interactive mode, so the window won’t disappear after the program is done. I’ve also added another thing, that is the ability to run the file in pythonw.exe instead of python.exe, and that’s for applications with GUI, so you don’t have to see a console window behind your application GUI 😉</p>
<p>This one would be very simple, just concatenate: Python installation path, “python.exe” and the full path of the current file.</p>
<pre class="lang:c++ decode:true">std::wstring buildRunCommand(std::wstring &filePath, std::wstring &pypath, bool isW = false, bool isI = false)
{
	std::wstring command = pypath;
	command += TEXT("python");
	if (isW)
		command += TEXT("w");
	command += TEXT(".exe ");
	if (isI)
		command += TEXT("-i ");
	command += TEXT("\"");
	command += filePath;
	command += TEXT("\"");
	return command;
}
</pre>
<h3 id="execute-the-run-command">Execute The Run Command</h3>
<p>This function accepts a path parameter so it will run the process in the specified path (which is the path of the folder that includes the Python file to run) instead of the default path, this allows applications reading/writing files inside the same folder (or a relative path) of the application path to find those files.</p>
<p>This one is also simple, just create a new process with the run command.</p>
<pre class="lang:c++ decode:true">bool launchPython(std::wstring &command, std::wstring &path)
{
	STARTUPINFOW si;
	PROCESS_INFORMATION pi;
	memset(&si, 0, sizeof(si));
	memset(&pi, 0, sizeof(pi));
	si.cb = sizeof(si);

	return CreateProcess(
		NULL,
		const_cast&lt;LPWSTR&gt;(command.c_str()),
		NULL,
		NULL,
		FALSE,
		CREATE_DEFAULT_ERROR_MODE,
		NULL,
		path.c_str(),
		&si,
		&pi) != 0;
}
</pre>
<h3 id="screenshot">Screenshot</h3>
<p><a href="http://mpcabd.xyz/wp-content/uploads/2009/11/PyNPP.png" rel="lightbox[185]" title="PyNPP Notepad++ Plugin Screenshot"><img src="http://mpcabd.xyz/wp-content/uploads/2009/11/PyNPP-300x149.png" alt="PyNPP Notepad++ Plugin Screenshot" title="PyNPP Notepad++ Plugin Screenshot" width="300" height="149" class="aligncenter size-medium wp-image-306" srcset="https://mpcabd.xyz/wp-content/uploads/2009/11/PyNPP-300x149.png 300w, https://mpcabd.xyz/wp-content/uploads/2009/11/PyNPP.png 788w" sizes="(max-width: 300px) 100vw, 300px" /></a></p>
<h3 style="text-align:left;">
  License
</h3>
<p>This work is licensed under <a href="http://www.gnu.org/licenses/gpl.html" target="_blank">GNU General Public License v3</a>.</p>
<h3 style="text-align:left;" id="download">
  Download
</h3>
<h4 id="pynpp-v12-on-github">PyNPP v1.2 on GitHub</h4>
<p><a href='https://github.com/mpcabd/PyNPP' target='_blank'>GitHub</a></p>
<h4 id="plugin-dll">Plugin DLL:</h4>
<p><a href='https://github.com/mpcabd/PyNPP/releases/download/v1.2/PyNPP.dll' target="_blank">Plugin DLL</a></p>
<h4 id="source-code">Source Code</h4>
<p><a href="https://github.com/mpcabd/PyNPP/archive/v1.2.tar.gz" target="_blank">Source Code</a></p>
<hr>
<h4 id="update-history">Update History</h4>
<ul>
<li>18, April 2010: PyNPP will search for Python in its default path <code>C:\Python[VER]\</code>.</li>
<li>13, December 2010: PyNPP will allow the user to run the file in three modes: normal, interactive and GUI. As suggested by Andrew <a href="http://mpcabd.xyz/notepad-plugin-to-run-python-scripts/comment-page-1/#comment-3433">here</a>.</li>
<li>13, December 2010: PyNPP will run the file in its folder, so it can read/write files next to it. As suggested by Andrew <a href="http://mpcabd.xyz/notepad-plugin-to-run-python-scripts/comment-page-1/#comment-3433">here</a>.</li>
<li>03, January 2011: PyNPP will search for Python in both <code>HKEY_CURRENT_USER\Software\Python\PythonCore</code> and <code>HKEY_LOCAL_MACHINE\Software\Python\PythonCore</code>.</li>
<li>05, January 2011: PyNPP will save the file before trying to run it.<br>
Fixed a bug in setting the current folder while running the process.</li>
<li>12, August 2011: PyNPP allows you to select the Python folder using an options dialog. As suggested by Hönes <a href="http://mpcabd.xyz/notepad-plugin-to-run-python-scripts/comment-page-1/#comment-5616">here</a>.
<ul>
<li>21, December 2011: PyNPP moved to GitHub.</li>
<li>27, April 2014: v1.1 released, PyNPP kills the Python instance it launches when the file is re-run. As suggested by Michał Kłopot.</li>
<li>30, March 2015: v1.2 released, PyNPP supports debugging the file with PDB. As suggested by fdufnews.</ul></li>
</ul>
</li>
</ul>]]></content:encoded>
    </item>
    <item>
      <title>Brainfuck Python Interpreter</title>
      <link>https://mpcabd.xyz/brainfuck-python-interpreter/</link>
      <pubDate>Mon, 19 Oct 2009 22:31:17 +0000</pubDate>
      <guid>https://mpcabd.xyz/brainfuck-python-interpreter/</guid>
      <description>&lt;h1 id=&#34;what-is-brainfuck&#34;&gt;What is brainfuck?&lt;/h1&gt;
&lt;p&gt;Brainfuck is a programming language&lt;img loading=&#34;lazy&#34; src=&#34;http://www.zu14.cn/coolemotion/emotions/zz_8.gif&#34;&gt;&lt;/p&gt;
&lt;p&gt;This is the definition from &lt;a href=&#34;http://en.wikipedia.org/wiki/Brainfuck&#34; target=&#34;_blank&#34;&gt;Wikipedia&lt;/a&gt;:&lt;/p&gt;
&lt;blockquote&gt;
&lt;p&gt;The &lt;strong&gt;brainfuck&lt;/strong&gt; programming language is an &lt;a href=&#34;http://en.wikipedia.org/wiki/Esoteric_programming_language&#34;&gt;esoteric programming language&lt;/a&gt; noted for its extreme minimalism. It is a &lt;a href=&#34;http://en.wikipedia.org/wiki/Turing_tarpit&#34;&gt;Turing tarpit&lt;/a&gt;, designed to challenge and amuse &lt;a href=&#34;http://en.wikipedia.org/wiki/Programmer&#34;&gt;programmers&lt;/a&gt;, and is not suitable for practical use. Its name has been variously &lt;a href=&#34;http://en.wikipedia.org/wiki/Expurgation&#34;&gt;bowdlerized&lt;/a&gt;. The name of the language is generally not capitalized, although it is a &lt;a href=&#34;http://en.wikipedia.org/wiki/Proper_noun&#34;&gt;proper noun&lt;/a&gt;.&lt;/p&gt;
&lt;/blockquote&gt;
&lt;p&gt;This programming language is very easy to learn, very hard to do work with. As the &lt;a href=&#34;http://en.wikipedia.org/wiki/Brainfuck&#34; target=&#34;_blank&#34;&gt;Wikipedia article&lt;/a&gt; describes it; the language is an esoteric language, which means it was created for fun &lt;img loading=&#34;lazy&#34; src=&#34;http://www.zu14.cn/coolemotion/emotions/zz_14.gif&#34;&gt;&lt;/p&gt;
&lt;p&gt;I discovered the language while I was reading an article about &lt;a href=&#34;http://blog.damonjablons.com/2009/10/15/the-perfect-django-settings-file/&#34; target=&#34;_blank&#34;&gt;writing the perfect settings file for Django&lt;/a&gt;. The author used &lt;a href=&#34;http://dpaste.com/&#34; target=&#34;_blank&#34;&gt;DPaste&lt;/a&gt; website to link to pieces of code. DPaste website says that it uses &lt;a href=&#34;http://pygments.org/&#34; target=&#34;_blank&#34;&gt;Pygments&lt;/a&gt; for syntax highlighting. Pygments say that their syntax highlighter even supports &lt;a href=&#34;http://www.muppetlabs.com/~breadbox/bf/&#34; target=&#34;_blank&#34;&gt;brainfuck&lt;/a&gt;. And that’s how I got to brainfuck &lt;img loading=&#34;lazy&#34; src=&#34;http://www.zu14.cn/coolemotion/emotions/zz_2.gif&#34;&gt;&lt;/p&gt;
&lt;p&gt;After I read articles about the language I wanted to test some code of it, I found some &lt;a href=&#34;http://koti.mbnet.fi/villes/php/bf.php&#34; target=&#34;_blank&#34;&gt;online interpreters&lt;/a&gt;, but I wanted to test some code on my machine. I found a &lt;a href=&#34;http://home.arcor.de/partusch/html_en/bfd.html&#34; target=&#34;_blank&#34;&gt;compiler&lt;/a&gt; for it, but I’m using Windows 7 on my machine and the compiler is not compatible with it. I got pissed off and I decided I have to write my own interpreter &lt;img loading=&#34;lazy&#34; src=&#34;http://www.zu14.cn/coolemotion/emotions/zz_3.gif&#34;&gt;&lt;/p&gt;</description>
      <content:encoded><![CDATA[<h1 id="what-is-brainfuck">What is brainfuck?</h1>
<p>Brainfuck is a programming language<img loading="lazy" src="http://www.zu14.cn/coolemotion/emotions/zz_8.gif"></p>
<p>This is the definition from <a href="http://en.wikipedia.org/wiki/Brainfuck" target="_blank">Wikipedia</a>:</p>
<blockquote>
<p>The <strong>brainfuck</strong> programming language is an <a href="http://en.wikipedia.org/wiki/Esoteric_programming_language">esoteric programming language</a> noted for its extreme minimalism. It is a <a href="http://en.wikipedia.org/wiki/Turing_tarpit">Turing tarpit</a>, designed to challenge and amuse <a href="http://en.wikipedia.org/wiki/Programmer">programmers</a>, and is not suitable for practical use. Its name has been variously <a href="http://en.wikipedia.org/wiki/Expurgation">bowdlerized</a>. The name of the language is generally not capitalized, although it is a <a href="http://en.wikipedia.org/wiki/Proper_noun">proper noun</a>.</p>
</blockquote>
<p>This programming language is very easy to learn, very hard to do work with. As the <a href="http://en.wikipedia.org/wiki/Brainfuck" target="_blank">Wikipedia article</a> describes it; the language is an esoteric language, which means it was created for fun <img loading="lazy" src="http://www.zu14.cn/coolemotion/emotions/zz_14.gif"></p>
<p>I discovered the language while I was reading an article about <a href="http://blog.damonjablons.com/2009/10/15/the-perfect-django-settings-file/" target="_blank">writing the perfect settings file for Django</a>. The author used <a href="http://dpaste.com/" target="_blank">DPaste</a> website to link to pieces of code. DPaste website says that it uses <a href="http://pygments.org/" target="_blank">Pygments</a> for syntax highlighting. Pygments say that their syntax highlighter even supports <a href="http://www.muppetlabs.com/~breadbox/bf/" target="_blank">brainfuck</a>. And that’s how I got to brainfuck <img loading="lazy" src="http://www.zu14.cn/coolemotion/emotions/zz_2.gif"></p>
<p>After I read articles about the language I wanted to test some code of it, I found some <a href="http://koti.mbnet.fi/villes/php/bf.php" target="_blank">online interpreters</a>, but I wanted to test some code on my machine. I found a <a href="http://home.arcor.de/partusch/html_en/bfd.html" target="_blank">compiler</a> for it, but I’m using Windows 7 on my machine and the compiler is not compatible with it. I got pissed off and I decided I have to write my own interpreter <img loading="lazy" src="http://www.zu14.cn/coolemotion/emotions/zz_3.gif"></p>
<h2 id="brainfuck-in-simple-description">Brainfuck in simple description</h2>
<p>The language consists of 8 symbols &lt; &gt; . , + – [ ]</p>
<p>The language deals with a 30,000 bytes array, at the start of the application all the items of that array are zeros.</p>
<p>The symbols can just deal with a pointer on that array to do specific jobs.</p>
<h1 id="ply">PLY</h1>
<p>I mentioned in a <a href="http://mpcabd.xyz/binding-netbeans-with-flex/" target="_blank">previous post</a> that I’m implementing a compiler for my 4th year in Informatics faculty. Hence I made a lot of searching around the net for information about implementing compilers. Implementing a compiler requires building a lexer which can be generated using lexer generator tools, and a parser which also can be generated using parser generator tools.</p>
<p>Since I’m a Python-Lover I searched for Python lexer and parser tools, and I came across the great PLY.</p>
<p><a href="http://www.dabeaz.com/ply/" target="_blank">PLY (Python Lex-Yacc)</a> is an implementation of lex and yacc parsing tools for Python.</p>
<p>The usage of PLY is not the target of this post.</p>
<h1 id="writing-a-lexer-for-brainfuck">Writing a lexer for brainfuck</h1>
<p>The lexer would be so simple, since the language only has 8 symbols, and capturing them requires almost nothing.</p>
<p>The lexer file is the following</p>
<pre class="lang:python decode:true">import ply.lex as lex

tokens = [
    'GoLeft',
    'GoRight',
    'Print',
    'Read',
    'Increase',
    'Decrease',
    'WhileStart',
    'WhileEnd'
]

t_GoLeft = r'\&lt;'
t_GoRight = r'\&gt;;'
t_Print = r'\.'
t_Read = r','
t_Increase = r'\+'
t_Decrease = r'\-'
t_WhileStart = r'\['
t_WhileEnd = r'\]'

def t_error(t):
    t.lexer.skip(1)

lexer = lex.lex()

if __name__ == "__main__":
    lex.runmain()
</pre>
<p>It simply captures the symbols of the language and ignores any other symbol. Simple isn’t it 🙂</p>
<h1 id="writing-a-parser-for-brainfuck">Writing a parser for brainfuck</h1>
<p>The parser will have to capture the instructions and store them in a tree so that it can do operations on the code without too much efforts.</p>
<p>The parser will ask the lexer to capture the symbols, while the parser will be responsible for making instructions from symbols.</p>
<h2 id="sparse-matrix">Sparse matrix</h2>
<p>I won’t actually allocate 30,000 bytes array for the application, and since the default value for any item is 0 then I can make use of the <a href="http://en.wikipedia.org/wiki/Sparse_matrix" target="_blank">Sparse Matrix</a>.</p>
<p>Implementing a simple sparse matrix is nothing more than a dictionary:</p>
<pre class="lang:python decode:true">class sparseMatrix:
    def __init__(self):
        self.dict = {}

    def __getitem__(self, index):
        if self.dict.has_key(index):
            return self.dict[index]
        else:
            return 0

    def __setitem__(self, index, value):
        self.dict[index] = value
</pre>
<h2 id="building-the-tree">Building the tree</h2>
<p>Six commands from the brainfuck language have no arguments or any other elements attaching to them, so they would just add elements containing the command type.</p>
<p>While two commands have a scope of code attached with them, the “[“ and “]” can be used to define while loops. So the while loop is the only command that will add an element with sub-level to the tree.</p>
<pre class="lang:python decode:true">def p_start(p):
    """
    start : code
            | empty
    """
    if p[1]:
        executeStatements(p[1])

def p_empty(p):
    'empty : '
    pass

def p_code(p):
    """
    code : code statement
            | code whilestatement
            | statement
            | whilestatement
    """
    if len(p) == 2:
        p[0] = [p[1]]
    else:
        p[0] = p[1][:]
        p[0].extend([p[2]])

def p_statement(p):
    """
    statement : GoLeft
                   | GoRight
                   | Print
                   | Read
                   | Increase
                   | Decrease
    """
    if p[1] == '&lt;':
        p[0] = ('GoLeft', None)
    elif p[1]  == '&gt;':
        p[0] = ('GoRight', None)
    elif p[1] == '.':
        p[0] = ('Print', None)
    elif p[1] == ',':
        p[0] = ('Read', None)
    elif p[1] == '+':
        p[0] = ('Increase', None)
    elif p[1] == '-':
        p[0] = ('Decrease', None)

def p_whilestatement(p):
    'whilestatement : WhileStart code WhileEnd'
    p[0] = ('While', p[2])
</pre>
<h2 id="executing-the-tree">Executing the tree</h2>
<p>Since I’m not building a real compiler I won’t have to generate machine specific code after building the tree. I decided that I can execute the code from within python since the code is too simple to be executed.</p>
<p>So I wrote a method to execute a list of tree elements and it can execute while loops using recursive calling to itself.</p>
<p>The method will be called when the parser parses a valid application and when it can recognize the start symbol of the generating rules of the language.</p>
<pre class="lang:python decode:true">def executeStatements(tuplesList):
    global matrix
    global index
    global MAX_INDEX

    for node in tuplesList:
        if node[0] == 'GoLeft':
            if index &gt; 0:
                index -= 1
            else:
                raise Exception, "Index out of array bounds!"
        elif node[0] == 'GoRight':
            if index &lt; MAX_INDEX:
                index += 1
            else:
                raise Exception, "Index out of array bounds!"
        elif node[0] == 'Print':
            print(chr(matrix[index]), sep='', end='')
        elif node[0] == 'Read':
            matrix[index] = ord(raw_input()[0])
        elif node[0] == 'Increase':
            matrix[index] += 1
        elif node[0] == 'Decrease':
            matrix[index] -= 1
        elif node[0] == 'While':
            while matrix[index] != 0:
                executeStatements(node[1])
</pre>
<h1 id="testing-the-interpreter">Testing the interpreter</h1>
<p>After running the interpreter, I tried the <a href="http://en.wikipedia.org/wiki/Brainfuck#Hello_World.21" target="_blank">Hello World example in Wikipedia</a> and I got the result:</p>
<pre class="lang:python decode:true">BrainFuck&gt; ++++++++++[&gt;+++++++&gt;++++++++++&gt;+++&gt;+&lt;&lt;&lt;&lt;-]&gt;++.&gt;+.+++++++..+++.&gt;++.&lt;&lt;+++++++++++++++.&gt;.+++.------.--------.&gt;+.&gt;.
Hello World!
BrainFuck&gt;
</pre>
<h1 id="download-source-code">Download source code</h1>
<p>You can download and test the interpreter from <a href="http://www.box.net/shared/jaranfgyz1" target="_blank">here</a>.</p>]]></content:encoded>
    </item>
    <item>
      <title>Binding NetBeans with Flex</title>
      <link>https://mpcabd.xyz/binding-netbeans-with-flex/</link>
      <pubDate>Wed, 07 Oct 2009 16:47:49 +0000</pubDate>
      <guid>https://mpcabd.xyz/binding-netbeans-with-flex/</guid>
      <description>&lt;p&gt;In my faculty – Informatics Engineering, Damascus University -, in the 4th year of Software Engineering Department, we have to build a compiler :shock:.&lt;/p&gt;
&lt;p&gt;I like using NetBeans for developing applications, it supports lots of languages and tools; like C, C++, Java, Python, Ruby and more. The compiler would be implemented in C++.&lt;/p&gt;
&lt;p&gt;The first two phases of implementing a compiler are: building a lexer (tokenizer) and building a parser. The lexer is implemented using &lt;a href=&#34;http://www.gnu.org/software/flex/&#34; target=&#34;_blank&#34;&gt;GNU Flex&lt;/a&gt; while the parser is implemented using &lt;a href=&#34;http://www.gnu.org/software/bison/&#34; target=&#34;_blank&#34;&gt;GNU Bison&lt;/a&gt;.&lt;/p&gt;
&lt;h1 id=&#34;the-problem&#34;&gt;The Problem&lt;/h1&gt;
&lt;p&gt;The first problem I faced when starting the project was to tell NetBeans how to handle the lex file:&lt;/p&gt;
&lt;p&gt;&lt;em&gt;The lex file must be passed to the flex tool to generate a C++ code file.&lt;/em&gt;&lt;/p&gt;
&lt;p&gt;The second problem was that when the code file is generated it contains errors:&lt;/p&gt;
&lt;pre class=&#34;lang:c++ decode:true&#34;&gt;#ifdef __cplusplus

#include &amp;lt;stdlib.h&amp;gt;
class istream;
#include &amp;lt;unistd.h&amp;gt;
&lt;/pre&gt;
&lt;p&gt;&lt;em&gt;When using building the file you’ll find that it contains errors regarding the usage of istream. (You might not face this problem, then you’re a lucky programmer).&lt;/em&gt;&lt;/p&gt;</description>
      <content:encoded><![CDATA[<p>In my faculty – Informatics Engineering, Damascus University -, in the 4th year of Software Engineering Department, we have to build a compiler :shock:.</p>
<p>I like using NetBeans for developing applications, it supports lots of languages and tools; like C, C++, Java, Python, Ruby and more. The compiler would be implemented in C++.</p>
<p>The first two phases of implementing a compiler are: building a lexer (tokenizer) and building a parser. The lexer is implemented using <a href="http://www.gnu.org/software/flex/" target="_blank">GNU Flex</a> while the parser is implemented using <a href="http://www.gnu.org/software/bison/" target="_blank">GNU Bison</a>.</p>
<h1 id="the-problem">The Problem</h1>
<p>The first problem I faced when starting the project was to tell NetBeans how to handle the lex file:</p>
<p><em>The lex file must be passed to the flex tool to generate a C++ code file.</em></p>
<p>The second problem was that when the code file is generated it contains errors:</p>
<pre class="lang:c++ decode:true">#ifdef __cplusplus

#include &lt;stdlib.h&gt;
class istream;
#include &lt;unistd.h&gt;
</pre>
<p><em>When using building the file you’ll find that it contains errors regarding the usage of istream. (You might not face this problem, then you’re a lucky programmer).</em></p>
<h1 id="the-first-problem-binding-netbeans-with-flex">The first problem: Binding NetBeans with Flex</h1>
<p>From NetBeans –&gt; Projects Side Tab –&gt; right click on the lex file –&gt; Properties:</p>
<p>Categories –&gt; General:</p>
<ul>
<li>
<p>Uncheck “Excluded From Build”.</p>
</li>
<li>
<p>Select “Custom Build Tool” in the Tool drop down list.</p>
</li>
</ul>
<p>Categories –&gt; Custom Build Step:</p>
<ul>
<li>
<p>Enter in the Command Line field: flex lex.l <em>Assuming that your lex file is called lex.l</em></p>
</li>
<li>
<p>Enter in the Outputs field: lex.yy.cc</p>
</li>
<li>
<p>Enter in the Description: Running Flex …</p>
</li>
</ul>
<p>Press Ok.</p>
<p>Now when you compile the solution your lex file will be passed the the flex tool.</p>
<h1 id="the-second-problem-fixing-the-error">The second problem: Fixing the error</h1>
<p>When I started fixing the error, I was doing it by hand, but I got bored of the process so I wrote a small Python script to do this for me:</p>
<p><em>Assuming that the output file of the lex file is called lex.yy.cc:</em></p>
<pre class="lang:python decode:true">f = open('lex.yy.cc')
lines = f.readlines()
i = 0
for i in range(len(lines)):
    if lines[i] == 'class istream;\n':
        break;
else:
    return;
lines[i] = '#include &lt;iostream&gt;\n'
lines.insert(i + 1, 'using namespace std;\n')
f.close()
f = open('lex.yy.cc', 'w')
f.writelines(lines)
f.close()
</pre>
<p>The script is easy, it opens the file, changes the line from “class istream;” to “#include <iostream>”, inserts “using namespace std;” next.</p>
<p>Put the file next to your sources and run it after the build process to fix the error.</p>
<h1 id="fixing-both-problems-without-executing-anything-manually">Fixing both problems without executing anything manually:</h1>
<p>After a while I got bored of executing the script manually and I decided that the script must be executed automatically.</p>
<p>To do that the script must be called by NetBeans, so back to the lex file properties I changed the Custom Build Command from “flex lex.l” to “python fixer.py”.</p>
<p>Now the fixer script is called to build the lex file, so the script must change to call the flex from the script itself:</p>
<pre class="lang:python decode:true">import os

os.system("flex token.l")

f = open('lex.yy.cc')
lines = f.readlines()
i = 0
for i in range(len(lines)):
    if lines[i] == 'class istream;\n':
        break;
else:
    return;
lines[i] = '#include &lt;iostream&gt;\n'
lines.insert(i + 1, 'using namespace std;\n')
f.close()
f = open('lex.yy.cc', 'w')
f.writelines(lines)
f.close()
</pre>
<p>Now all my problems are solved, hope that yours will be solved too 🙂</p>]]></content:encoded>
    </item>
    <item>
      <title>Get Online Users in Django</title>
      <link>https://mpcabd.xyz/get-online-users-in-django/</link>
      <pubDate>Mon, 21 Sep 2009 22:41:00 +0000</pubDate>
      <guid>https://mpcabd.xyz/get-online-users-in-django/</guid>
      <description>&lt;p&gt;I was upgrading my &lt;a href=&#34;http://mpcabd.alwaysdata.net/&#34; target=&#34;_blank&#34;&gt;Django Bookmarks&lt;/a&gt; site, and I wanted to list the online users. I searched the internet and I found a &lt;a href=&#34;http://www.djangosnippets.org/snippets/947/&#34; target=&#34;_blank&#34;&gt;simple method&lt;/a&gt;, but it doesn’t work properly. So I developed my own method.&lt;/p&gt;
&lt;h1 id=&#34;why-the-simple-method-didnt-work&#34;&gt;Why the simple method didn’t work?&lt;/h1&gt;
&lt;p&gt;The problem with it is that it depends on the last login date in the user model. This field is updated on every login for the user.&lt;/p&gt;
&lt;p&gt;Imagine the following scenario:&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;
&lt;p&gt;The user X logs in @ 1:00 pm.&lt;/p&gt;
&lt;/li&gt;
&lt;li&gt;
&lt;p&gt;The user X posts a new post @ 1:30 pm.&lt;/p&gt;
&lt;/li&gt;
&lt;li&gt;
&lt;p&gt;The user X comments on a previous post @ 1:35 pm.&lt;/p&gt;
&lt;/li&gt;
&lt;li&gt;
&lt;p&gt;The user X leaves the website @ 1:40 pm.&lt;/p&gt;
&lt;/li&gt;
&lt;li&gt;
&lt;p&gt;The user X comes back to the website @ 3:00 pm.&lt;/p&gt;
&lt;/li&gt;
&lt;li&gt;
&lt;p&gt;The user X is logged in since the session cookie has not expired yet.&lt;/p&gt;
&lt;/li&gt;
&lt;li&gt;
&lt;p&gt;The user X posts a new post @ 3:15 pm.&lt;/p&gt;
&lt;/li&gt;
&lt;li&gt;
&lt;p&gt;A guest enters the website, and looks at the online users corner.&lt;/p&gt;
&lt;/li&gt;
&lt;/ul&gt;
&lt;p&gt;The guest won’t see X’s name in the list of online users, simply because X’s last login date is @ 1 pm, even though user X is now online and he has just posted a new post.&lt;/p&gt;</description>
      <content:encoded><![CDATA[<p>I was upgrading my <a href="http://mpcabd.alwaysdata.net/" target="_blank">Django Bookmarks</a> site, and I wanted to list the online users. I searched the internet and I found a <a href="http://www.djangosnippets.org/snippets/947/" target="_blank">simple method</a>, but it doesn’t work properly. So I developed my own method.</p>
<h1 id="why-the-simple-method-didnt-work">Why the simple method didn’t work?</h1>
<p>The problem with it is that it depends on the last login date in the user model. This field is updated on every login for the user.</p>
<p>Imagine the following scenario:</p>
<ul>
<li>
<p>The user X logs in @ 1:00 pm.</p>
</li>
<li>
<p>The user X posts a new post @ 1:30 pm.</p>
</li>
<li>
<p>The user X comments on a previous post @ 1:35 pm.</p>
</li>
<li>
<p>The user X leaves the website @ 1:40 pm.</p>
</li>
<li>
<p>The user X comes back to the website @ 3:00 pm.</p>
</li>
<li>
<p>The user X is logged in since the session cookie has not expired yet.</p>
</li>
<li>
<p>The user X posts a new post @ 3:15 pm.</p>
</li>
<li>
<p>A guest enters the website, and looks at the online users corner.</p>
</li>
</ul>
<p>The guest won’t see X’s name in the list of online users, simply because X’s last login date is @ 1 pm, even though user X is now online and he has just posted a new post.</p>
<h2 id="update-8th-may-2013">UPDATE 8th May 2013</h2>
<p>Please note the solution provided in this post is an old solution, it is coded in a weird way maybe, and it is not the best way to achieve what is required. I’ll write soon a new solution that in my opinion will be far better than this one.</p>
<h1 id="so-what-is-missing-here">So what is missing here?</h1>
<p>The last login date is not enough to tell if the user online or not, we must have another field that tells us when is the last activity date for the user.</p>
<p>In ASP .NET there is a field called LastActivityDate in the users table, and it is used for this specific mission.</p>
<h1 id="when-to-update-last-activity-date">When to update last activity date?</h1>
<p>In ASP .NET you have to update the last activity manually, and there is a good way to do it; in global.asax:</p>
<pre class="lang:c# decode:true">private void Application_AuthenticateRequest(Object source, EventArgs e) {
    //Your Code Goes Here
}
</pre>
<p>In this method you can access the request, get the current user, update his/her last activity date.</p>
<p>So basically updating last activity date is done on the request, when the user makes a request to your application and he/she is authenticated.</p>
<h1 id="but-there-is-no-last-activity-date-in-djangos-user-model">But there is no last activity date in Django’s user model?</h1>
<p>Yeah I know, but you can extend the User module in Django. And to do this there are many ways, one of them is by making a new model with a foreign key to the User. Then you can do whatever you want.</p>
<h1 id="and-where-am-i-going-to-write-the-code-that-will-update-the-last-activity-date">And where am I going to write the code that will update the last activity date?</h1>
<p>In Django we have <a href="http://docs.djangoproject.com/en/dev/topics/http/middleware/" target="_blank">Middleware</a>; a Middleware is a layer that handles something on each request, its input is the request and it can process it or modify it.</p>
<p>So I simply created a new Middleware that takes the request and finds the user, then updates his/her last activity.</p>
<p>I installed the middleware in the settings module, I appended its name after ‘django.contrib.auth.middleware.AuthenticationMiddleware’ in MIDDLEWARE_CLASSES.</p>
<p>There was a problem in doing that, because the user might send many request per page, each image will send a request, and imagine how many updates there is in each page!</p>
<p>The solution is to skip a list of URLs, so if the user requests a URL within this list his/her last activity date won’t be updated. The skip list is stored within the urls.py file.</p>
<p>The skip list will contain regular expressions just like the url_patterns dictionary.</p>
<h1 id="making-the-solution-generic">Making the solution generic</h1>
<p>I wanted to publish this solution, and it had to be generic so you can use it without editing its code.</p>
<p>Making it generic required small modifications:</p>
<ul>
<li>
<p>Making a new application called lastActivityDate.</p>
</li>
<li>
<p>Pasting the extended user model inside models.py.</p>
</li>
<li>
<p>Modifying the settings module and add lastActivityDate to the INSTALLED_APPS list.</p>
</li>
</ul>
<h1 id="extending-the-user-module">Extending the user module</h1>
<pre class="lang:python decode:true">from django.db import models
from django.contrib.auth.models import User
from datetime import datetime

class UserActivity(models.Model):
    last_activity_ip = models.IPAddressField()
    last_activity_date = models.DateTimeField(default = datetime(1950, 1, 1))
    user = models.OneToOneField(User, primary_key=True)
</pre>
<p>Since the User and UserActivity models are now related one-to-one we can now type:</p>
<pre class="lang:python decode:true">a = User.objects.get(username__exact='mpcabd')
print a.useractivity.last_activity_ip

b = UserActivity.objects.get(user=a)
print b.user.username
</pre>
<h1 id="the-middleware">The Middleware</h1>
<pre class="lang:python decode:true">from models import UserActivity
from datetime import datetime
from django.conf import settings
from django.contrib.sites.models import Site
import re

compiledLists = {}

class LastActivityMiddleware(object):
    def process_request(self, request):
        if not request.user.is_authenticated():
            return
        urlsModule = __import__(settings.ROOT_URLCONF, {}, {}, [''])
        skipList = getattr(urlsModule, 'skip_last_activity_date', None)
        skippedPath = request.path
        if skippedPath.startswith('/'):
            skippedPath = skippedPath[1:]
        if skipList is not None:
            for expression in skipList:
                compiledVersion = None
                if not compiledLists.has_key(expression):
                    compiledLists[expression] = re.compile(expression)
                compiledVersion = compiledLists[expression]
                if compiledVersion.search(skippedPath):
                    return
        activity = None
        try:
            activity = request.user.useractivity
        except:
            activity = UserActivity()
            activity.user = request.user
            activity.last_activity_date = datetime.now()
            activity.last_activity_ip = request.META['REMOTE_ADDR']
            activity.save()
            return
        activity.last_activity_date = datetime.now()
        activity.last_activity_ip = request.META['REMOTE_ADDR']
        activity.save()
</pre>
<p>The compiled list is for enhancing performance, each regular expression is compiled one time; when it is accessed the first time.</p>
<p>You can see that I used the settings module to get a the URLs module name. And I used the __import__ function to import the module dynamically.</p>
<p>In line 12 I check if there is a list called ‘skip_last_activity_date’ using the getattr function, passing a third parameter to this functions specifies the default value if the list was not found so I don’t get an exception.</p>
<p>In lines 25 to 37 I get or create the UserActivity object, I update the last activity date using datetime.now(), I update the last activity IP using request.META[‘REMOTE_ADDR’] which gives me the client IP address.</p>
<h1 id="modifying-the-urls-module">Modifying the URLs module</h1>
<p>In the urls.py file insert the following code:</p>
<pre class="lang:python decode:true">skip_last_activity_date = [
    #Your expressions go here
]
</pre>
<h1 id="modifying-the-settings-module">Modifying the settings module</h1>
<p>In the settings.py file insert the following code:</p>
<pre class="lang:python decode:true">#Your settings code
MIDDLEWARE_CLASSES = (
    #Your middleware classes go here
    'django.contrib.sessions.middleware.SessionMiddleware',
    'django.contrib.auth.middleware.AuthenticationMiddleware',
    'lastActivityDate.LastActivityMiddleware.LastActivityMiddleware',
    #Your middleware classes go here
)
#Your settings code
INSTALLED_APPS = (
    #Your installed apps
    'YOUR_APP_FOLDER.lastActivityDate',
    #Your installed apps
)
#Your settings code
</pre>
<p>Replace YOUR_APP_FOLDER with the folder of your application, such that the directory tree is like this:</p>
<pre class="decode:true">YourAppFolder:
--&gt; appFolder
--&gt; …
--&gt; __init__.py
--&gt; views.py
--&gt; models.py
--&gt; …
--&gt; lastActivityDate
--&gt; __init__.py
--&gt; LastActivityMiddleware.py
--&gt; models.py
--&gt; urls.py
--&gt; settings.py
--&gt; __init__.py
--&gt; manage.py
</pre>
<h1 id="ps">P.S.</h1>
<p>Do not forget to synchronize the database using “manage.py syncdb” so that Django creates the lastactivitydate_useractivity table in the database.</p>
<h1 id="getting-online-users">Getting online users</h1>
<p>After this long trip here is how to get online users:</p>
<pre class="lang:python decode:true">from django.contrib.auth.models import User
from datetime import datetime, timedelta
from lastActivityDate.models import UserActivity

def get_online_users(num):
    fifteen_minutes = datetime.now() - timedelta(minutes=15)
    sql_datetime = datetime.strftime(fifteen_minutes, '%Y-%m-%d %H:%M:%S')
    users = UserActivity.objects.filter(last_activity_date__gte=sql_datetime, user__is_active__exact=1).order_by('-last_activity_date')[:num]
    return [u.user for u in users]
</pre>
<p>This function returns a list of users whose last activity was in the last 15 minutes. Of course you can modify it and expand the duration.</p>
<h1 id="download-source-code">Download source code</h1>
<p>Here is the link to download source code of the lastActivityDate application:</p>
<p><a href="http://www.box.net/shared/1prdvejycg" target="_blank">lastActivityDate.tar.gz</a></p>
<p>Notice that the code is written using Python 2.6 and Django 1.0. If you have different version(s) you <strong>might</strong> encounter a problem.</p>
<h1 id="license">License</h1>
<p>This work is licensed under the Creative Commons Attribution-Share Alike 3.0 License.</p>
<p>To view a copy of this license, visit <a href="http://creativecommons.org/licenses/by-sa/3.0/">http://creativecommons.org/licenses/by-sa/3.0/</a>.</p>]]></content:encoded>
    </item>
    <item>
      <title>I’m Learning Python part 10 (last one)</title>
      <link>https://mpcabd.xyz/im-learning-python-part-10-last-one/</link>
      <pubDate>Tue, 15 Sep 2009 22:24:22 +0000</pubDate>
      <guid>https://mpcabd.xyz/im-learning-python-part-10-last-one/</guid>
      <description>&lt;div dir=&#34;ltr&#34;&gt;
  &lt;div style=&#34;text-align:center;&#34; align=&#34;center&#34;&gt;
    &lt;h1 style=&#34;font-size:18pt;font-family:Verdana;&#34;&gt;
      I&#39;m Learning Python part 10
    &lt;/h1&gt;
&lt;pre&gt;&lt;code&gt;&amp;lt;p&amp;gt;
  &amp;lt;h1 style=&amp;quot;font-size:18pt;font-family:Verdana;&amp;quot;&amp;gt;
    (last one)
  &amp;lt;/h1&amp;gt;
  
  &amp;lt;p&amp;gt;
    &amp;lt;img src=&amp;quot;http://www.python.org/images/python-logo.gif&amp;quot; alt=&amp;quot;Python Logo&amp;quot; title=&amp;quot;Python Logo&amp;quot; /&amp;gt; &amp;lt;/div&amp;gt; 
    
    &amp;lt;h1 style=&amp;quot;font-family:Georgia;&amp;quot;&amp;gt;
      Back to blogging
    &amp;lt;/h1&amp;gt;
    
    &amp;lt;p&amp;gt;
      As usual, I will apologize for not blogging for a long time.&amp;lt;br /&amp;gt; I have been very busy, university exams, university projects, job projects, teaching and learning.
    &amp;lt;/p&amp;gt;
    
    &amp;lt;h1 style=&amp;quot;font-family:Georgia;&amp;quot;&amp;gt;
      Python Course
    &amp;lt;/h1&amp;gt;
    
    &amp;lt;p&amp;gt;
      At Damascus University, in the faculty of informatics we managed to create free courses to students, and I was one of the teachers there, I taught Python to students.&amp;lt;br /&amp;gt; As far as I know this course was the first Python course in Damascus University.&amp;lt;br /&amp;gt; Even though the students were a few (actually a very little few about 8 ~ 10 students) the course was great. We managed to learn Python 2.6 Syntax, a little bit of its standard library and a little bit of PyQt4 in about 7 days x 2 hours daily.&amp;lt;br /&amp;gt; As far as I know too, students understood it and found it great, and I hope they&amp;amp;#8217;ll be using this great language more in their programs.
    &amp;lt;/p&amp;gt;
    
    &amp;lt;h1 style=&amp;quot;font-family:Georgia;&amp;quot;&amp;gt;
      Why last one?
    &amp;lt;/h1&amp;gt;
    
    &amp;lt;p&amp;gt;
      The tour with Python ends here, while it ends here it starts here too, it ends here because so far you&amp;amp;#8217;ve learned what you need to start your own path in Python. And it starts here because you&amp;amp;#8217;re fully equipped with the base tool to discover more tools, I&amp;amp;#8217;ll let you discover the standard library and 3rd-party libraries on your own, because everyone differs in his/her interests.&amp;lt;br /&amp;gt; I&amp;amp;#8217;ll be blogging more on more technical issues but they might not be I&amp;amp;#8217;m Learning Python series :).&amp;lt;br /&amp;gt; Let&amp;amp;#8217;s stop talking here and move directly to the heart of our last lesson.&amp;lt;br /&amp;gt; 
&lt;/code&gt;&lt;/pre&gt;</description>
      <content:encoded><![CDATA[<div dir="ltr">
  <div style="text-align:center;" align="center">
    <h1 style="font-size:18pt;font-family:Verdana;">
      I'm Learning Python part 10
    </h1>
<pre><code>&lt;p&gt;
  &lt;h1 style=&quot;font-size:18pt;font-family:Verdana;&quot;&gt;
    (last one)
  &lt;/h1&gt;
  
  &lt;p&gt;
    &lt;img src=&quot;http://www.python.org/images/python-logo.gif&quot; alt=&quot;Python Logo&quot; title=&quot;Python Logo&quot; /&gt; &lt;/div&gt; 
    
    &lt;h1 style=&quot;font-family:Georgia;&quot;&gt;
      Back to blogging
    &lt;/h1&gt;
    
    &lt;p&gt;
      As usual, I will apologize for not blogging for a long time.&lt;br /&gt; I have been very busy, university exams, university projects, job projects, teaching and learning.
    &lt;/p&gt;
    
    &lt;h1 style=&quot;font-family:Georgia;&quot;&gt;
      Python Course
    &lt;/h1&gt;
    
    &lt;p&gt;
      At Damascus University, in the faculty of informatics we managed to create free courses to students, and I was one of the teachers there, I taught Python to students.&lt;br /&gt; As far as I know this course was the first Python course in Damascus University.&lt;br /&gt; Even though the students were a few (actually a very little few about 8 ~ 10 students) the course was great. We managed to learn Python 2.6 Syntax, a little bit of its standard library and a little bit of PyQt4 in about 7 days x 2 hours daily.&lt;br /&gt; As far as I know too, students understood it and found it great, and I hope they&amp;#8217;ll be using this great language more in their programs.
    &lt;/p&gt;
    
    &lt;h1 style=&quot;font-family:Georgia;&quot;&gt;
      Why last one?
    &lt;/h1&gt;
    
    &lt;p&gt;
      The tour with Python ends here, while it ends here it starts here too, it ends here because so far you&amp;#8217;ve learned what you need to start your own path in Python. And it starts here because you&amp;#8217;re fully equipped with the base tool to discover more tools, I&amp;#8217;ll let you discover the standard library and 3rd-party libraries on your own, because everyone differs in his/her interests.&lt;br /&gt; I&amp;#8217;ll be blogging more on more technical issues but they might not be I&amp;#8217;m Learning Python series :).&lt;br /&gt; Let&amp;#8217;s stop talking here and move directly to the heart of our last lesson.&lt;br /&gt; 
</code></pre>
<br /> 
<pre><code>      &lt;h1 style=&quot;font-family:Georgia;&quot;&gt;
        Revision
      &lt;/h1&gt;
      
      &lt;p&gt;
        The last part introduced classes, how to define them, how to use them. This lesson will continue to explain classes and functions more.&lt;br /&gt; Defining a function:
      &lt;/p&gt;
      
      &lt;pre class=&quot;lang:python decode:true&quot;&gt;
def functionName(param0, param1, ...):
	#Your function code goes here.
	#You can return values using:
	return values
</code></pre>
<p></pre></p>
<pre><code>      &lt;p&gt;
        Defining a class:
      &lt;/p&gt;
      
      &lt;pre class=&quot;lang:python decode:true&quot;&gt;
class ClassName(BaseClass0, BaseClass1, ...):
	#Your class code goes here.
	#Your class ends whenever you go out of the scope (you go back one tab).
</code></pre>
<p></pre></p>
<pre><code>      &lt;p&gt;
        The constructor of the class is defined using the special name __init__:
      &lt;/p&gt;
      
      &lt;pre class=&quot;lang:python decode:true&quot;&gt;
class A:
	def __init__(self, param0, ...):
		#Constructor code goes here.
</code></pre>
<p></pre></p>
<pre><code>      &lt;p&gt;
        The method inside a class is just a function which receives the object instance as its first parameter:
      &lt;/p&gt;
      
      &lt;pre class=&quot;lang:python decode:true&quot;&gt;
class A:
	def myMethod(self, param0, ...):
		#method is just a function
</code></pre>
<p></pre></p>
<pre><code>      &lt;p&gt;
        Properties are fields encapsulated within a function to get their values and might be encapsulated withing a function to set their values. These two functions allow you to do your business logic over the values before allowing the user to read/write them.
      &lt;/p&gt;
      
      &lt;pre class=&quot;lang:python decode:true&quot;&gt;
class A:
	@property
	def Id(self):
		return self.__id

	@Id.setter
	def setId(self, value):
		self.__id = value

	def __init__(self):
		self.__id = 0
</code></pre>
<p></pre></p>
<pre><code>      &lt;p&gt;
        Defining an object instance of the class is done by calling the class constructor:
      &lt;/p&gt;
      
      &lt;pre class=&quot;lang:python decode:true&quot;&gt;
a = A()
</code></pre>
<p></pre></p>
<pre><code>      &lt;p&gt;
        If the constructor takes a list of parameters you &lt;b&gt;might&lt;/b&gt; specify them when calling it:&lt;br /&gt;:
      &lt;/p&gt;
      
      &lt;pre class=&quot;lang:python decode:true&quot;&gt;
class B:
	def __init__(self, name):
		self.name = name

b = B('some name')
</code></pre>
<p></pre></p>
<pre><code>      &lt;p&gt;
        Properties after defining an object instance can be used as if they were fields:
      &lt;/p&gt;
      
      &lt;pre class=&quot;lang:python decode:true&quot;&gt;
a.Id = 10
print a.Id
</code></pre>
<p></pre></p>
<pre><code>      &lt;h1 style=&quot;font-family:Georgia;&quot;&gt;
        More and more about functions
      &lt;/h1&gt;
      
      &lt;p&gt;
        Functions can be used in many ways.
      &lt;/p&gt;
      
      &lt;h2&gt;
        Functions with default values
      &lt;/h2&gt;
      
      &lt;p&gt;
        You can let the parameters of the functions have default values, so that if the user didn&amp;#8217;t supply them they&amp;#8217;ll have valid values:
      &lt;/p&gt;
      
      &lt;pre class=&quot;lang:python decode:true&quot;&gt;
def f(id = 1, name = 'some name', age = 10):
	print(str(id) + ' ' + name + ' at age ' + str(age))
#All of the following calls are valid
f()				#Will print: 1 some name at age 10
f(2)			#Will print: 2 some name at age 10
f(2, 'a')		#Will print: 2 a at age 10
f(2, 'a', 3)	#Will print: 2 a at age 3
</code></pre>
<p></pre></p>
<pre><code>      &lt;p&gt;
        What if I want to supply the second paramter without supplying the first one and the third one? The solution is by:
      &lt;/p&gt;
      
      &lt;h2&gt;
        Passing specified parameters
      &lt;/h2&gt;
      
      &lt;p&gt;
        You can choose the paramters you want to supply and with any order you want:
      &lt;/p&gt;
      
      &lt;pre class=&quot;lang:python decode:true&quot;&gt;
#All of the following calls are valid
f(age = 3)						#Wil print: 1 some name at age 3
f(age = 3, id = 2)				#Will print: 2 some name at age 3
f(name = 'a', age = 3, id = 2)	#Will print: 2 a at age 3
</code></pre>
<p></pre></p>
<pre><code>      &lt;p&gt;
        You can see that this way is useful, you can choose which parameters to pass and in what order :).
      &lt;/p&gt;
      
      &lt;h2&gt;
        Passing unlimited count of paramters
      &lt;/h2&gt;
      
      &lt;p&gt;
        Yes you can do it, you can call a function and pass it any count of parameters you want:
      &lt;/p&gt;
      
      &lt;pre class=&quot;lang:python decode:true&quot;&gt;
def u(*args):
	s = ''
	for arg in args:
		s += arg + ' '
	print s
#All of the following calls are valid
u()			#Will print nothing
u(1)		#Will print: 1
u(1, 2)		#Will print: 1 2
u(1, 2, 3)	#Will print: 1 2 3
</code></pre>
<p></pre></p>
<pre><code>      &lt;p&gt;
        So args actually is enumerable type, may be a list ;).
      &lt;/p&gt;
      
      &lt;h2&gt;
        Passing unlimited named parameters
      &lt;/h2&gt;
      
      &lt;p&gt;
        Hmmmm, yes you can too specify names for those unlimited parameters of yours:
      &lt;/p&gt;
      
      &lt;pre class=&quot;lang:python decode:true&quot;&gt;
def uu(**kargs):
	s = ''
	for k, v in kargs.iteritems():
		s += k + ' =&amp;gt; ' + v + ', '
	print s
#All of the following calls are valid
uu()							#Will print nothing
uu(a = 1)						#Will print: a =&amp;gt; 1
uu(a = 1, b = 2)				#Will print: a =&amp;gt; 1, b =&amp;gt; 2,
uu(a = 1, b = 'asd', c = 0.5)	#Will print: a =&amp;gt; 1, b =&amp;gt; 'asd', c =&amp;gt; 0.5,
</code></pre>
<p></pre></p>
<pre><code>      &lt;p&gt;
        So kargs actually is a dictionary.&lt;br /&gt; If you don&amp;#8217;t already know, dictionary.iteritems is a method that iterates over the keys and values of the dictionary, yielding a tuple every iteration, the first item of the tuple is the key, and the other is the value.&lt;br /&gt; dictionary.iteritems is a great method for iterating over a dictionary of unknown keys.
      &lt;/p&gt;
      
      &lt;h2&gt;
        Overloading and why I don&amp;#8217;t need it here
      &lt;/h2&gt;
      
      &lt;p&gt;
        Overloading is simply more than one instance of the same function with one or more of the following points achieved in them:&lt;br /&gt; * The count of parameters differs between them.&lt;br /&gt; * The types of the parameters differ between them.&lt;br /&gt; * The prder of the parameters differ between them.
      &lt;/p&gt;
      
      &lt;p&gt;
        Using what we&amp;#8217;ve learned so far, we can say that the first point can be achieved using one function, by using default values for the parameters.&lt;br /&gt; The second point can also be achieved using one function since Python has no strict data types to variables and parameters.&lt;br /&gt; The third point can also be achieved using one function, by using paramters names while calling you can change the order of parameters passed.&lt;br /&gt; And so I can continue coding without overloading.
      &lt;/p&gt;
      
      &lt;h1 style=&quot;font-family:Georgia;&quot;&gt;
        Last Words
      &lt;/h1&gt;
      
      &lt;p&gt;
        After learning how to implement classes and functions properly you can start your path on learning Python standard library and 3rd-party libraries. Python is widely supported and you won&amp;#8217;t find difficulties in using it as your main programming language.&lt;br /&gt; In the last two months I learned how to use Python to develop web applications using Django (pronounced yangoo), and being an expert ASP .NET developer I assure you, Django is easier and more fun to code than ASP .NET. I made a testing website from the book I read &amp;#8211; The book was: &lt;a href=&quot;http://www.packtpub.com/django-1-0-website-development-2nd-edition&quot;&gt;Django 1.0 Website Development&lt;/a&gt;, by my colleague and friend &lt;a href=&quot;http://www.aymanh.com&quot;&gt;Ayman Hourieh&lt;/a&gt; -, the website is for sharing bookmarks, it is now hosted for free at AlwaysData here &lt;a href=&quot;http://mpcabd.alwaysdata.net&quot;&gt;http://mpcabd.alwaysdata.net&lt;/a&gt;&lt;br /&gt; You can do in Python whatever you want with less coding. Enjoy your life more.
      &lt;/p&gt;
      
      &lt;h1 style=&quot;font-family:Georgia;&quot;&gt;
        The End
      &lt;/h1&gt;
      
      &lt;p&gt;
        It is the end of this course but the start of your path.&lt;br /&gt; I hope you enjoyed it, and that I could give you the information in a nice and easy way.&lt;br /&gt; For any questions or suggestions you can leave your comments here.&lt;br /&gt; Thanks for being patient :).&lt;br /&gt; &amp;#8212; Abd Allah Diab &lt;/div&gt;
</code></pre>]]></content:encoded>
    </item>
    <item>
      <title>Bring Down IE6</title>
      <link>https://mpcabd.xyz/bring-down-ie6/</link>
      <pubDate>Sat, 28 Mar 2009 14:00:17 +0000</pubDate>
      <guid>https://mpcabd.xyz/bring-down-ie6/</guid>
      <description>&lt;div class=&#34;column&#34;&gt;
  &lt;h2&gt;
  &lt;/h2&gt;
  &lt;p&gt;
    I have copied the following post from &lt;a href=&#34;http://www.bringdownie6.com/&#34;&gt;this site&lt;/a&gt;.
  &lt;/p&gt;
  &lt;p&gt;
    &lt;img class=&#34;aligncenter&#34; title=&#34;Bring IE6 Down&#34; src=&#34;http://www.netmag.co.uk/files/bd.png&#34; alt=&#34;&#34; width=&#34;117&#34; height=&#34;120&#34; /&gt;
  &lt;/p&gt;
  &lt;h2&gt;
    Discover the mission
  &lt;/h2&gt;
  &lt;p&gt;
    The premise is simple: Internet Explorer 6 is antiquated, doesn’t support key web standards, and should be phased out. This isn’t about being anti-Microsoft, it’s about Microsoft’s lack of development in the browser market. With IE7/8 not available for Windows 2000, IE6 accounts for up to 20% of web usage, primarily via business users. Clients pressure designers to ‘force’ sites to work in IE6, and designers, not wanting to lose business, comply, using hacks and workarounds. This wastes time and money. Microsoft needs to fix this, designers need to unite, and we all need to move on.
  &lt;/p&gt;
  &lt;div class=&#34;column&#34;&gt;
    &lt;h2&gt;
      Read the article
    &lt;/h2&gt;
&lt;pre&gt;&lt;code&gt;&amp;lt;p&amp;gt;
  In our article, ‘&amp;lt;a href=&amp;quot;http://www.bringdownie6.com/bring-down-ie-6.html&amp;quot;&amp;gt;Calling time on IE6&amp;lt;/a&amp;gt;’, we ask designers and developers if it’s finally time to take IE6 behind the shed and shoot it. Major names in the web industry debate our mission, talking about the pros and cons behind dumping IE6. How feasible is it to shun the browser entirely? What can you do to minimise the impact IE6 has on you and your clients (and increasingly tight budgets)? And what can and should Microsoft do to help us all move the web and web standards on? &amp;lt;a href=&amp;quot;http://www.bringdownie6.com/bring-down-ie-6.html&amp;quot;&amp;gt;Find out by reading the article&amp;lt;/a&amp;gt;, or just ‘skip to the end’ by looking to the right and getting involved.&amp;lt;br /&amp;gt; 
&lt;/code&gt;&lt;/pre&gt;</description>
      <content:encoded><![CDATA[<div class="column">
  <h2>
  </h2>
  <p>
    I have copied the following post from <a href="http://www.bringdownie6.com/">this site</a>.
  </p>
  <p>
    <img class="aligncenter" title="Bring IE6 Down" src="http://www.netmag.co.uk/files/bd.png" alt="" width="117" height="120" />
  </p>
  <h2>
    Discover the mission
  </h2>
  <p>
    The premise is simple: Internet Explorer 6 is antiquated, doesn’t support key web standards, and should be phased out. This isn’t about being anti-Microsoft, it’s about Microsoft’s lack of development in the browser market. With IE7/8 not available for Windows 2000, IE6 accounts for up to 20% of web usage, primarily via business users. Clients pressure designers to ‘force’ sites to work in IE6, and designers, not wanting to lose business, comply, using hacks and workarounds. This wastes time and money. Microsoft needs to fix this, designers need to unite, and we all need to move on.
  </p>
  <div class="column">
    <h2>
      Read the article
    </h2>
<pre><code>&lt;p&gt;
  In our article, ‘&lt;a href=&quot;http://www.bringdownie6.com/bring-down-ie-6.html&quot;&gt;Calling time on IE6&lt;/a&gt;’, we ask designers and developers if it’s finally time to take IE6 behind the shed and shoot it. Major names in the web industry debate our mission, talking about the pros and cons behind dumping IE6. How feasible is it to shun the browser entirely? What can you do to minimise the impact IE6 has on you and your clients (and increasingly tight budgets)? And what can and should Microsoft do to help us all move the web and web standards on? &lt;a href=&quot;http://www.bringdownie6.com/bring-down-ie-6.html&quot;&gt;Find out by reading the article&lt;/a&gt;, or just ‘skip to the end’ by looking to the right and getting involved.&lt;br /&gt; 
</code></pre>
</p>
<pre><code>&lt;div class=&quot;column&quot;&gt;
  &lt;h2&gt;
    Get involved
  &lt;/h2&gt;
  
  &lt;ul&gt;
    &lt;li&gt;
      &lt;a href=&quot;http://www.netmag.co.uk/files/bd.png&quot;&gt;Put our logo on your site&lt;/a&gt; and then &lt;a href=&quot;http://www.bringdownie6.com/&quot;&gt;link to this site&lt;/a&gt;. &lt;a href=&quot;http://www.twitter.com/netmag&quot;&gt;Follow us on Twitter&lt;/a&gt;.
    &lt;/li&gt;
    &lt;li&gt;
      Educate your colleagues, users and clients regarding calling time on IE6.
    &lt;/li&gt;
    &lt;li&gt;
      Ensure sites work in IE6, but don&amp;#8217;t waste a lot of time fixing non-critical issues.
    &lt;/li&gt;
    &lt;li&gt;
      Provide an upgrade notice for IE6 users by adding this code to your page: &lt;pre class=&quot;lang:html decode:true&quot;&gt;
</code></pre>
<p>&lt;style type=&ldquo;text/css&rdquo;&gt;
#ie6Warning {
background:#E3E3E3 none repeat scroll 0 0;
border:1px solid #BBBBBB;
margin-bottom:10px;
padding:10px 10px 1px;
}
#ie6Warning h2 {
background:transparent url(<a href="http://www.bringdownie6.com/assets/ie6-warning.gif">http://www.bringdownie6.com/assets/ie6-warning.gif</a>) no-repeat scroll 0 50%;
padding-left:40px;
}
&lt;/style&gt;
&lt;!–[if lt IE 7]&gt;
&lt;div id=&ldquo;ie6Warning&rdquo;&gt;
&lt;h2&gt;Time to upgrade your browser&lt;/h2&gt;
&lt;p&gt;If you&rsquo;re reading this, you&rsquo;re surfing using Internet Explorer 6, an eight-year-old browser that cannot cope with the demands of the modern internet. For the best web experience, we strongly recommend upgrading to &lt;a xhref=&ldquo;<a href="http://www.getfirefox.com/%22&amp;gt;Firefox&amp;lt;/a&amp;gt;">http://www.getfirefox.com/&quot;&amp;gt;Firefox&amp;lt;/a&amp;gt;</a>, &lt;a xhref=&ldquo;<a href="http://www.opera.com/%22&amp;gt;Opera&amp;lt;/a&amp;gt;">http://www.opera.com/&quot;&amp;gt;Opera&amp;lt;/a&amp;gt;</a>, &lt;a xhref=&ldquo;<a href="http://www.apple.com/safari/%22&amp;gt;Safari&amp;lt;/a&amp;gt;">http://www.apple.com/safari/&quot;&amp;gt;Safari&amp;lt;/a&amp;gt;</a>, &lt;a xhref=&ldquo;<a href="http://www.google.com/chrome%22&amp;gt;Google">http://www.google.com/chrome&quot;&amp;gt;Google</a> Chrome&lt;/a&gt;, or a more recent version of &lt;a xhref=&ldquo;<a href="http://www.microsoft.com/windows/downloads/ie/getitnow.mspx%22&amp;gt;Internet">http://www.microsoft.com/windows/downloads/ie/getitnow.mspx&quot;&amp;gt;Internet</a> Explorer&lt;/a&gt;.&lt;/p&gt;
&lt;/div&gt;
&lt;![endif]–&gt;
</pre>
</li></p>
<pre><code>    &lt;li&gt;
      Spread the word
    &lt;/li&gt;
  &lt;/ul&gt;
&lt;/div&gt;
</code></pre>
  </div>
</div>]]></content:encoded>
    </item>
    <item>
      <title>I’m Learning Python part 9</title>
      <link>https://mpcabd.xyz/im-learning-python-part-9/</link>
      <pubDate>Fri, 20 Mar 2009 00:35:21 +0000</pubDate>
      <guid>https://mpcabd.xyz/im-learning-python-part-9/</guid>
      <description>&lt;div dir=&#34;ltr&#34;&gt;
  &lt;div style=&#34;text-align:center;&#34;&gt;
    &lt;h1 style=&#34;font-size:18pt;font-family:Verdana;&#34;&gt;
      I&amp;#8217;m Learning Python part 9
    &lt;/h1&gt;
&lt;pre&gt;&lt;code&gt;&amp;lt;p&amp;gt;
  &amp;lt;img title=&amp;quot;Python Logo&amp;quot; src=&amp;quot;http://www.python.org/images/python-logo.gif&amp;quot; alt=&amp;quot;Python Logo&amp;quot; /&amp;gt;&amp;lt;/div&amp;gt; 
  
  &amp;lt;h1 style=&amp;quot;font-family:Georgia;&amp;quot;&amp;gt;
    Classes In Python
  &amp;lt;/h1&amp;gt;
  
  &amp;lt;div dir=&amp;quot;ltr&amp;quot;&amp;gt;
    As I told you before, Python is a powerful programming language, and powerful it won&amp;amp;#8217;t be without Object Oriented design.
  &amp;lt;/div&amp;gt;
  
  &amp;lt;div dir=&amp;quot;ltr&amp;quot;&amp;gt;
    Python supports both Pure Object Oriented Programming (Every thing must be in a class) and Structural Programming (You can type code everywhere).
  &amp;lt;/div&amp;gt;
  
  &amp;lt;div dir=&amp;quot;ltr&amp;quot;&amp;gt;
    It supports also other programming paradigms like Functional Programming. I won&amp;amp;#8217;t write about OOP and its uses, why we should use it, I&amp;amp;#8217;ll just give you the keys to use OOP in Python.
  &amp;lt;/div&amp;gt;
  
  &amp;lt;h1 style=&amp;quot;font-family:Georgia;&amp;quot;&amp;gt;
    Defining a Class
  &amp;lt;/h1&amp;gt;
  
  &amp;lt;p&amp;gt;
    Classes in Python are defined like this:
  &amp;lt;/p&amp;gt;
  
  &amp;lt;p&amp;gt;
&lt;/code&gt;&lt;/pre&gt;</description>
      <content:encoded><![CDATA[<div dir="ltr">
  <div style="text-align:center;">
    <h1 style="font-size:18pt;font-family:Verdana;">
      I&#8217;m Learning Python part 9
    </h1>
<pre><code>&lt;p&gt;
  &lt;img title=&quot;Python Logo&quot; src=&quot;http://www.python.org/images/python-logo.gif&quot; alt=&quot;Python Logo&quot; /&gt;&lt;/div&gt; 
  
  &lt;h1 style=&quot;font-family:Georgia;&quot;&gt;
    Classes In Python
  &lt;/h1&gt;
  
  &lt;div dir=&quot;ltr&quot;&gt;
    As I told you before, Python is a powerful programming language, and powerful it won&amp;#8217;t be without Object Oriented design.
  &lt;/div&gt;
  
  &lt;div dir=&quot;ltr&quot;&gt;
    Python supports both Pure Object Oriented Programming (Every thing must be in a class) and Structural Programming (You can type code everywhere).
  &lt;/div&gt;
  
  &lt;div dir=&quot;ltr&quot;&gt;
    It supports also other programming paradigms like Functional Programming. I won&amp;#8217;t write about OOP and its uses, why we should use it, I&amp;#8217;ll just give you the keys to use OOP in Python.
  &lt;/div&gt;
  
  &lt;h1 style=&quot;font-family:Georgia;&quot;&gt;
    Defining a Class
  &lt;/h1&gt;
  
  &lt;p&gt;
    Classes in Python are defined like this:
  &lt;/p&gt;
  
  &lt;p&gt;
</code></pre>
</p>
<pre><code>  &lt;pre class=&quot;lang:python decode:true&quot;&gt;
</code></pre>
<p>class CLASS_NAME (BASE0,BASE1,BASE2):
&ldquo;&ldquo;&ldquo;OPTIONAL DOC STRING&rdquo;&rdquo;&rdquo;
#Class Code
.
.
.
</pre></p>
<pre><code>  &lt;div dir=&quot;ltr&quot;&gt;
    Yes, I know what you&amp;#8217;re thinking of, Python supports multiple inheritance.
  &lt;/div&gt;
  
  &lt;div dir=&quot;ltr&quot;&gt;
    In Python 3.0 you must at least inherit the object class (or any other class that inherits object), this is called new-style-classes, and that&amp;#8217;s because before Python 3.0 you could make a classic class that doesn&amp;#8217;t inherit any class, not even object.
  &lt;/div&gt;
  
  &lt;div dir=&quot;ltr&quot;&gt;
    Because of Python&amp;#8217;s dynamic data typing you don&amp;#8217;t need interfaces in Python, so there is no implicit syntax for declaring interfaces.
  &lt;/div&gt;
  
  &lt;h1 style=&quot;font-family:Georgia;&quot;&gt;
    Sample
  &lt;/h1&gt;
  
  &lt;div dir=&quot;ltr&quot;&gt;
    Let&amp;#8217;s create a sample class, I always implement the stack when I want to show OOP examples, I don&amp;#8217;t know why but that&amp;#8217;s what I&amp;#8217;m gonna do now:
  &lt;/div&gt;
  
  &lt;div dir=&quot;ltr&quot;&gt;
    I always start implementing stack by implementing its unit type, a class called StackItem.
  &lt;/div&gt;
  
  &lt;div dir=&quot;ltr&quot;&gt;
    StackItem is a stack unit that has two properties, its value, and a reference to its next item in the stack, so it will be defined:
  &lt;/div&gt;
  
  &lt;pre class=&quot;lang:python decode:true&quot;&gt;
</code></pre>
<p>class StackItem(object):
def <strong>init</strong>(self, value):
self.Value = value
self.Next = None</p>
<pre><code>@property
def Value(self):
	return self.__value
@Value.setter
def Value(self, value):
	self.__value = value

@property
def Next(self):
	return self.__next
@Next.setter
def Next(self, value):
	self.__next = value
</code></pre>
<p></pre></p>
<pre><code>  &lt;p&gt;
    Let&amp;#8217;s describe the whole scene of code:
  &lt;/p&gt;
  
  &lt;ol&gt;
    &lt;li&gt;
      StackItem inherits object, it is a way of saying &amp;#8220;Everything is an object&amp;#8221; 🙂
    &lt;/li&gt;
    &lt;li&gt;
      __init__ is the constructor of StackItem, it takes two arguments, the instance of StackItem to construct and the value of it, it sets the given value to the Value property of the given StackItem instance. And it sets the Next property of the given StackItem instance to None (Which is the null pointer).
    &lt;/li&gt;
    &lt;li&gt;
      @property is called function decorator, a decorator is a function which takes a function as a parameter and returns a function too. (Weird but handy).&lt;br /&gt; The decorator works as a transformer that transforms the function from one state to another. @property decorator creates a property from the given function, a property is like a variable, you store values in it for further reading/writing, but properties have a special function called a getter that returns the hidden value, and a special function called a setter that sets a given value to the hidden variable, the benefits you get from using properties instead of variables is that you can do some check before assigning the value to the variable, you can make sure that the give value is a positive number for instance.&lt;br /&gt; @property created a property called Value inside StackItem class, and it bounded its value to a private variable called __value.&lt;br /&gt; You&amp;#8217;d ask how come __value is a private variable?&lt;br /&gt; The answer is that in Python there is no access modifiers but Python annotates that any class variable with two leading underscores at least and one trailing underscore at most will be a private class variable, so other classes can&amp;#8217;t see it, so it is a way of creating private variables.
    &lt;/li&gt;
    &lt;li&gt;
      @Value.setter is another decorator which binds the setting of the Value property tho the given function.
    &lt;/li&gt;
    &lt;li&gt;
      Next is like Value, a property.&lt;br /&gt; A property can be used later by calling its name only, just like any variable: e.g.:&lt;/p&gt; &lt;pre class=&quot;lang:python decode:true&quot;&gt;
</code></pre>
<p>s.Value = 5
#This will call the function with
#@Value.setter decorator,
#passes s as the first argument,
#and 5 as the second one.
print(s.Value)
This will call the function with
#@property decorator,
#passes s as the first argument.
</pre>
</li></p>
<pre><code>    &lt;li&gt;
      self is passed to each function in the class, it refers to the instance of the class that the function was called from (Like this in C++, C#, Java and Me in Visual Basic).&lt;br /&gt; When not passing self to the function you&amp;#8217;re declaring that this function doesn&amp;#8217;t need an instance of the class to be called, in other words, you&amp;#8217;re declaring this as a static function, but you must tell the compiler that you did it on purpose so you should add @staticmethod decorator to the function, e.g.:&lt;/p&gt; &lt;pre class=&quot;lang:python decode:true&quot;&gt;
</code></pre>
<p>class C(object):
def NonStatic(self):
print (&ldquo;NonStatic&rdquo; )
@staticmethod
def Static():
print(&ldquo;Static&rdquo; )</p>
<p>cObj = C()
cObj.NonStatic() #Will print NonStatic
#(self = cObj)
cObj.Static() #Will print Static
C.Static() #Will also print Static
C.NonStatic() #Would give an error because
#NonStatic expects 1 argument
#and was called using none.
</pre>
</li>
</ol></p>
<pre><code>  &lt;p&gt;
    The other part must be easy for you after understanding the first one, now we&amp;#8217;ll implement the Stack class:
  &lt;/p&gt;
  
  &lt;pre class=&quot;lang:python decode:true&quot;&gt;
</code></pre>
<p>class Stack(object):
@property
def Head(self):
return self.__head</p>
<pre><code>@property
def Count(self):
	return self.__count

def __init__(self):
	self.__head = None
	self.__count = 0

def Push(self, value):
	if (self.__head is None):
		self.__head = StackItem(value)
	else:
		temp = StackItem(value)
		temp.Next = self.__head
		self.__head = temp
	self.__count += 1

def Pop(self):
	if (self.__head is None):
		raise Exception(&quot;Empty Stack&quot; )
	else:
		temp = self.__head
		self.__head = self.__head.Next
		self.__count -= 1
		return temp.Value

def PopAll(self):
	while (self.__count &amp;gt; 0):
		yield self.Pop()
</code></pre>
<p></pre></p>
<pre><code>  &lt;p&gt;
    Notes:
  &lt;/p&gt;
  
  &lt;ol&gt;
    &lt;li&gt;
      Stack has two read-only properties (They have no setters), Head (a reference to its top-most item) and Count (the count of items in the Stack).
    &lt;/li&gt;
    &lt;li&gt;
      The constructor sets the Count to 0 and the Head to None.
    &lt;/li&gt;
    &lt;li&gt;
      Push takes two arguments, the stack to push into, and the value to be pushed.
    &lt;/li&gt;
    &lt;li&gt;
      Pop takes one argument, the stack to pop out from, and returns the popped value. If the stack is empty Pop method will raise (throw) a new Exception with a message that says &amp;#8220;Empty Stack&amp;#8221;.
    &lt;/li&gt;
    &lt;li&gt;
      PopAll is called a Generator, it generates values from a data structure, it can be used with for loops. e.g.: &lt;pre class=&quot;lang:python decode:true&quot;&gt;
</code></pre>
<p>for value in s.PopAll():
print(value)
</pre></p>
<pre><code>      &lt;p&gt;
        yield is a keyword in Python that yields 😀 a given value to the caller. PopAll method works this way: The first time the caller calls it it would return the first value and stop. Each next time it will continue from where it stopped.&lt;/li&gt; &lt;/ol&gt; 
        
        &lt;p&gt;
          Now we can use our stack freely 🙂
        &lt;/p&gt;
        
        &lt;pre class=&quot;lang:python decode:true&quot;&gt;
</code></pre>
<p>S = Stack()</p>
<p>map(S.Push, range(1, 10))</p>
<p>for value in S.PopAll():
print value
</pre></p>
<pre><code>        &lt;div dir=&quot;ltr&quot;&gt;
          Simple code, right?
        &lt;/div&gt;
        
        &lt;div dir=&quot;ltr&quot;&gt;
          Notes:
        &lt;/div&gt;
        
        &lt;ol&gt;
          &lt;li&gt;
            S = Stack() initializes a new Stack and put its reference in S.
          &lt;/li&gt;
          &lt;li&gt;
            map is a function that takes a function as first argument and a list as second argument, and it calls the given function on each value from the give list and returns a tuple with the values of calling the function, in our case there is no return because Push returns no value. range is a function that takes two numbers and returns a list of numbers between the first one inclusively and the second one exclusively. e.g.: &lt;pre class=&quot;lang:python decode:true&quot;&gt;
</code></pre>
<p>print(rang(1, 10)) #prints from 1 to 9
</pre></p>
<pre><code>            &lt;p&gt;
              range can also take three numbers, the third would be the step between each two numbers. e.g.:
            &lt;/p&gt;
            
            &lt;pre class=&quot;lang:python decode:true&quot;&gt;
</code></pre>
<p>print(range(1, 10, 2)) #prints 1, 3, 5, 7, 9
</pre></p>
<pre><code>            &lt;p&gt;
              So map(S.Push, range(1, 10)) will fill the stack with values from 1 to 9.&lt;/li&gt; 
              
              &lt;li&gt;
                I used the PopAll method which is a generator to iterate over the StackItems and print them.
              &lt;/li&gt;&lt;/ol&gt; 
              
              &lt;h1 style=&quot;font-family:Georgia;&quot;&gt;
                Overriding and Overloading
              &lt;/h1&gt;
              
              &lt;div dir=&quot;ltr&quot;&gt;
                In OOP we use Overriding for a method in the sub-class that overrides a method in the base-class, and Overloading for two methods with the same name but differ in signature (number of arguments, types of arguments, order of arguments).
              &lt;/div&gt;
              
              &lt;div dir=&quot;ltr&quot;&gt;
                Usually to override a method in the sub-class the method must be declared virtual in the base-class, but in Python all methods are implicitly virtual.
              &lt;/div&gt;
              
              &lt;div dir=&quot;ltr&quot;&gt;
                To override a method you simply have to define it in the sub-class. e.g:
              &lt;/div&gt;
              
              &lt;pre class=&quot;lang:python decode:true&quot;&gt;
</code></pre>
<p>class A(object):
def M(self):
print (self.X)
def <strong>init</strong>(self):
self.X = 5
class B(A):
def M(self):
print (self.X + 1)</p>
<p>b = B()
b.M() #Will print 6
</pre></p>
<pre><code>              &lt;div dir=&quot;ltr&quot;&gt;
                Sometimes you need to extend the base method instead of overriding it completely, you can call the base method by using BaseClassName.MethodName(self, arguments).
              &lt;/div&gt;
              
              &lt;div dir=&quot;ltr&quot;&gt;
                e.g.:
              &lt;/div&gt;
              
              &lt;pre class=&quot;lang:python decode:true&quot;&gt;
</code></pre>
<p>class C(B):
def M(self):
B.M(self)
print (&ldquo;This is C&rdquo; )
c = C()
c.M() #Will print 6 This is C
</pre></p>
<pre><code>              &lt;div dir=&quot;ltr&quot;&gt;
                While overriding is a piece of cake, overloading is not supported by Python, you have to pick different names for different overloads from your method, that is because Python associates each function to a variable, so when overloading the variable will have the last function only.
              &lt;/div&gt;
              
              &lt;div dir=&quot;ltr&quot;&gt;
                A def statement is roughly executed like this:
              &lt;/div&gt;
              
              &lt;ol&gt;
                &lt;li&gt;
                  Compile the body of the function.
                &lt;/li&gt;
                &lt;li&gt;
                  Build a function object __f
                &lt;/li&gt;
                &lt;li&gt;
                  Assign it: FunctionName = __f
                &lt;/li&gt;
              &lt;/ol&gt;
              
              &lt;h1 style=&quot;font-family:Georgia;&quot;&gt;
                Bottom Line:
              &lt;/h1&gt;&lt;/div&gt; 
              
              &lt;div dir=&quot;ltr&quot;&gt;
                Python supports Pure Object Oriented strongly, You can write pure Object Oriented programs using Python, so why don&amp;#8217;t you start writing your programs now?
              &lt;/div&gt;
              
              &lt;div dir=&quot;ltr&quot;&gt;
                Cheers.
              &lt;/div&gt;
</code></pre>]]></content:encoded>
    </item>
    <item>
      <title>I’m Learning Python part 8</title>
      <link>https://mpcabd.xyz/im-learning-python-part-8/</link>
      <pubDate>Fri, 20 Feb 2009 22:34:20 +0000</pubDate>
      <guid>https://mpcabd.xyz/im-learning-python-part-8/</guid>
      <description>&lt;div&gt;
  &lt;div style=&#34;text-align:center;&#34;&gt;
    &lt;h1 style=&#34;font-size:18pt;font-family:Verdana;&#34;&gt;
      I&amp;#8217;m Learning Python part 8
    &lt;/h1&gt;
&lt;pre&gt;&lt;code&gt;&amp;lt;p&amp;gt;
  &amp;lt;img title=&amp;quot;Python&amp;quot; src=&amp;quot;//www.python.org/images/python-logo.gif&amp;quot; alt=&amp;quot;Python&amp;quot; /&amp;gt;&amp;lt;/div&amp;gt; 
  
  &amp;lt;h1 style=&amp;quot;font-family:Georgia;&amp;quot;&amp;gt;
    Python 3.0
  &amp;lt;/h1&amp;gt;
  
  &amp;lt;p&amp;gt;
    Since the last time I wrote an article Python many changes happened in my life, one of them is the release of Python 3.0 (Which is known also as Python3K and Python3000).
  &amp;lt;/p&amp;gt;
  
  &amp;lt;p&amp;gt;
    Python 3.0 is the first intentionally backwards incompatible Python release, which means that there are some changes you must notice before start coding in Python 3.0.
  &amp;lt;/p&amp;gt;
  
  &amp;lt;p&amp;gt;
    Don&amp;amp;#8217;t worry that much, the language has become more useful, and also there is &amp;lt;a href=&amp;quot;//docs.python.org/library/2to3.html&amp;quot;&amp;gt;2to3 source-to-source conversion tool&amp;lt;/a&amp;gt; which converts your Python 2.x code to meet the requirements of Python 3.0 🙂
  &amp;lt;/p&amp;gt;
  
  &amp;lt;p&amp;gt;
    To find more about change in Python please refer to &amp;lt;a title=&amp;quot;What&#39;s&amp;quot; href=&amp;quot;//docs.python.org/3.0/whatsnew/3.0.html&amp;quot;&amp;gt;Python website&amp;lt;/a&amp;gt;.
  &amp;lt;/p&amp;gt;
  
  &amp;lt;p&amp;gt;
&lt;/code&gt;&lt;/pre&gt;</description>
      <content:encoded><![CDATA[<div>
  <div style="text-align:center;">
    <h1 style="font-size:18pt;font-family:Verdana;">
      I&#8217;m Learning Python part 8
    </h1>
<pre><code>&lt;p&gt;
  &lt;img title=&quot;Python&quot; src=&quot;//www.python.org/images/python-logo.gif&quot; alt=&quot;Python&quot; /&gt;&lt;/div&gt; 
  
  &lt;h1 style=&quot;font-family:Georgia;&quot;&gt;
    Python 3.0
  &lt;/h1&gt;
  
  &lt;p&gt;
    Since the last time I wrote an article Python many changes happened in my life, one of them is the release of Python 3.0 (Which is known also as Python3K and Python3000).
  &lt;/p&gt;
  
  &lt;p&gt;
    Python 3.0 is the first intentionally backwards incompatible Python release, which means that there are some changes you must notice before start coding in Python 3.0.
  &lt;/p&gt;
  
  &lt;p&gt;
    Don&amp;#8217;t worry that much, the language has become more useful, and also there is &lt;a href=&quot;//docs.python.org/library/2to3.html&quot;&gt;2to3 source-to-source conversion tool&lt;/a&gt; which converts your Python 2.x code to meet the requirements of Python 3.0 🙂
  &lt;/p&gt;
  
  &lt;p&gt;
    To find more about change in Python please refer to &lt;a title=&quot;What's&quot; href=&quot;//docs.python.org/3.0/whatsnew/3.0.html&quot;&gt;Python website&lt;/a&gt;.
  &lt;/p&gt;
  
  &lt;p&gt;
</code></pre>
<p><br /> P.S.
</p></p>
<pre><code>  &lt;p&gt;
    From now on all the code will be written in Python 3.0.
  &lt;/p&gt;
  
  &lt;h1 style=&quot;font-family:Georgia;&quot;&gt;
    Decimal vs. float
  &lt;/h1&gt;
  
  &lt;p&gt;
    Please try the following code in your python console:
  &lt;/p&gt;
  
  &lt;pre class=&quot;lang:python decode:1&quot;&gt;
</code></pre>
<p>d = 0.1
print(d)
print(str(d))
</pre></p>
<pre><code>  &lt;p&gt;
    You&amp;#8217;d get this output:
  &lt;/p&gt;
  
  &lt;div&gt;
    &lt;strong&gt;&lt;span style=&quot;color:#666666;font-family:verdana;&quot;&gt;0.10000000000000001&lt;/span&gt;&lt;/strong&gt;
  &lt;/div&gt;
  
  &lt;p&gt;
    &lt;strong&gt;&lt;span style=&quot;color:#666666;font-family:verdana;&quot;&gt;0.1&lt;br /&gt; &lt;/span&gt;&lt;/strong&gt;Strange ain&amp;#8217;t it?&lt;br /&gt; The second value is the one you put in the variable.&lt;br /&gt; The first one is the real value represented in memory. This is not Python&amp;#8217;s fault, this happens because of the way computer store float values in memory as 0&amp;#8217;s and 1&amp;#8217;s, computers use floating point IEEE-745 representation.
  &lt;/p&gt;
  
  &lt;p&gt;
    Using this representation unfortunately we can&amp;#8217;t represent any float value using 0&amp;#8217;s and 1&amp;#8217;s, and 0.1 is one of those poor values (The reason is that it can&amp;#8217;t be represented in sum of powers of 0.5).
  &lt;/p&gt;
  
  &lt;p&gt;
    So what all programming languages do is that they ignore the small fraction so it would be 0.1 instead of 0.10000000000000001, but Python doesn&amp;#8217;t.
  &lt;/p&gt;
  
  &lt;p&gt;
    Try this code in Java if you have:
  &lt;/p&gt;
  
  &lt;pre class=&quot;lang:python decode:1&quot;&gt;
</code></pre>
<p>public class NoDifference{
  public static void main(String[] args){
    double a = 0.1;
    System.out.println(a);
    a = 0.10000000000000001;
    System.out.println(a);
  }
}
</pre></p>
<pre><code>  &lt;p&gt;
    You&amp;#8217;d get this output:
  &lt;/p&gt;
  
  &lt;div&gt;
    &lt;strong&gt;&lt;span style=&quot;color:#666666;font-family:verdana;&quot;&gt;0.1&lt;/span&gt;&lt;/strong&gt;
  &lt;/div&gt;
  
  &lt;p&gt;
    &lt;strong&gt;&lt;span style=&quot;color:#666666;font-family:verdana;&quot;&gt;0.1&lt;/span&gt;&lt;/strong&gt;
  &lt;/p&gt;
  
  &lt;p&gt;
    &lt;strong&gt;&lt;/strong&gt;So Java doesn&amp;#8217;t differ those two values while they&amp;#8217;re different. (Such a difference could make a disaster in a nuclear reactor :twisted:)&lt;br /&gt; If you want to go with the flow and ignore this difference in your calculations you&amp;#8217;d have to use another data type than float, you&amp;#8217;ll have to use Decimal.
  &lt;/p&gt;
  
  &lt;pre class=&quot;lang:python decode:1&quot;&gt;
</code></pre>
<p>from decimal import Decimal
d = Decimal(&ldquo;0.1&rdquo;)
print(d)
</pre></p>
<pre><code>  &lt;p&gt;
    &lt;strong&gt;&lt;span style=&quot;color:#666666;font-family:verdana;&quot;&gt;0.1&lt;/span&gt;&lt;/strong&gt;
  &lt;/p&gt;
  
  &lt;p&gt;
    &lt;strong&gt;&lt;/strong&gt;Decimal data type allows you to represent any decimal value you want 🙂
  &lt;/p&gt;
  
  &lt;p&gt;
    It also supports addition, subtraction, multiplication, division and modulo, but the two sides must be Decimals.
  &lt;/p&gt;
  
  &lt;h1 style=&quot;font-family:Georgia;&quot;&gt;
    Functions
  &lt;/h1&gt;
  
  &lt;p&gt;
    Let&amp;#8217;s write a function that prints Fibonacci series to a given boundary:
  &lt;/p&gt;
  
  &lt;pre class=&quot;lang:python decode:1&quot;&gt;
</code></pre>
<p>def fib(n):
  &ldquo;&ldquo;&ldquo;Prints Fibonacci series up to n&rdquo;&rdquo;&rdquo;
  a, b = 0, 1
  while b &lt; n:
    print(b, end = &quot; &ldquo;)
    a, b = b, a + b
#Now we can call the function by its name
fib(2000)
</pre></p>
<pre><code>  &lt;p&gt;
    &lt;strong&gt;&lt;span style=&quot;color:#666666;font-family:verdana;&quot;&gt;1 1 2 3 5 8 13 21 34 55 89 144 233 377 610 987 1597&lt;/span&gt;&lt;/strong&gt;
  &lt;/p&gt;
  
  &lt;p&gt;
    Now let&amp;#8217;s describe what we have done:
  &lt;/p&gt;
  
  &lt;ol&gt;
    &lt;li&gt;
      def is a keyword in Python, def defines 🙂 it defines methods and classes.
    &lt;/li&gt;
    &lt;li&gt;
      fib is the method&amp;#8217;s name, method&amp;#8217;s name must meet the same requirements for variable&amp;#8217;s name. (first character a-z, A-Z or _, other characters a-z, A-Z, 0-9, _)
    &lt;/li&gt;
    &lt;li&gt;
      (n) is the list of parameters, notice that no type names in this list. parameters are comma separated.
    &lt;/li&gt;
    &lt;li&gt;
      : defines the scope of the method. All statements under this scope must be tab-aligned.
    &lt;/li&gt;
    &lt;li&gt;
      &amp;#8220;&amp;#8221;&amp;#8221;Prints &amp;#8230;&amp;#8221;&amp;#8221;&amp;#8221; is an optional string literal that describes what this method does, it will help you and other developers understand the purpose of the method, and it will also help you auto-generate documentation for your code.
    &lt;/li&gt;
    &lt;li&gt;
      a, b = 0, 1. define two variables and give them two values. a handy way 🙂
    &lt;/li&gt;
    &lt;li&gt;
      a, b = b, a + b. also assign two values to two variables.
    &lt;/li&gt;
  &lt;/ol&gt;
  
  &lt;p&gt;
    The previous code defines a procedure (not a function) because it doesn&amp;#8217;t return a value, let&amp;#8217;s modify the code so it builds an array of Fibonacci values instead of printing them:
  &lt;/p&gt;
  
  &lt;pre class=&quot;lang:python decode:1&quot;&gt;
</code></pre>
<p>def fib(n):
  &ldquo;&ldquo;&ldquo;Prints Fibonacci series up to n&rdquo;&rdquo;&rdquo;
  a, b = 0, 1
  result = []
  while b &lt; n:
    result.append(b)
    a, b = b, a + b
  return result
f = fib(100)
print(f)
</pre></p>
<pre><code>  &lt;p&gt;
    &lt;strong&gt;&lt;span style=&quot;color:#666666;font-family:verdana;&quot;&gt;[1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89]&lt;/span&gt;&lt;/strong&gt;
  &lt;/p&gt;
  
  &lt;p&gt;
    What we have added is the return statement only, which returns a value to the caller.
  &lt;/p&gt;
  
  &lt;p&gt;
    One more thing to be told is default arguments:
  &lt;/p&gt;
  
  &lt;pre class=&quot;lang:python decode:1&quot;&gt;
</code></pre>
<p>def askYesNoQuestion(question, retries = 4, complaint = &ldquo;Please write Yes or No only!&rdquo;):
  while retries &gt; 0:
    answer = raw_input(question)
    if answer in [&lsquo;y&rsquo;, &lsquo;ye&rsquo;, &lsquo;yes&rsquo;, &lsquo;yep&rsquo;]: return True
    if answer in [&rsquo;n&rsquo;, &rsquo;no&rsquo;, &rsquo;nop&rsquo;]: return False
    retries -= 1
    print(complaint)
  raise IOError, &ldquo;stupid user&rdquo;
#Now we can call it
askYesNoQuestion(&ldquo;Are you sure?&rdquo;, 1, &ldquo;What?!&rdquo;)
askYesNoQuestion(&ldquo;Overwrite?&rdquo;, 1)
#Same as askYesNoQuestion(&ldquo;Overwrite?&rdquo;, 1, &ldquo;Please write Yes or No only!&rdquo;)
askYesNoQuestion(&ldquo;Do you know me?&rdquo;)
#Same as askYesNoQuestion(&ldquo;Do you know me?&rdquo;, 4, &ldquo;Please write Yes or No only!&rdquo;)
askYesNoQuestion(&ldquo;Do you have a pen?&rdquo;, complaint = &ldquo;You can say no if you want!&rdquo;)
#Same as askYesNoQuestion(&ldquo;Do you have a pen?&rdquo;, 4, &ldquo;You can say no if you want!&rdquo;)
</pre></p>
<pre><code>  &lt;p&gt;
    Default arguments are assigned a default value if they aren&amp;#8217;t when called.&lt;br /&gt; You can set arguments values when calling by writing Name = Value.&lt;br /&gt; Default parameters can&amp;#8217;t be followed by non-default arguments.&lt;br /&gt; &lt;strong&gt;Important note&lt;/strong&gt;:&lt;br /&gt; Default arguments are evaluated only once, so the following code will accumulate the values:
  &lt;/p&gt;
  
  &lt;pre class=&quot;lang:python decode:1&quot;&gt;
</code></pre>
<p>def f(a, L = []):
  L.append(a)
  return L
f(1)
print(f)
</pre></p>
<pre><code>  &lt;p&gt;
    &lt;strong&gt;&lt;span style=&quot;color:#666666;font-family:verdana;&quot;&gt;[1]&lt;/span&gt;&lt;/strong&gt;
  &lt;/p&gt;
  
  &lt;pre class=&quot;lang:python decode:1&quot;&gt;
</code></pre>
<p>f(2)
print(f)
</pre></p>
<pre><code>  &lt;p&gt;
    &lt;strong&gt;&lt;span style=&quot;color:#666666;font-family:verdana;&quot;&gt;[1, 2]&lt;/span&gt;&lt;/strong&gt;
  &lt;/p&gt;
  
  &lt;pre class=&quot;lang:python decode:1&quot;&gt;
</code></pre>
<p>f(3)
print(f)
</pre></p>
<pre><code>  &lt;p&gt;
    &lt;strong&gt;&lt;span style=&quot;color:#666666;font-family:verdana;&quot;&gt;[1, 2, 3]&lt;/span&gt;&lt;/strong&gt;&lt;br /&gt; If you don&amp;#8217;t want the function to behave like this you can write:
  &lt;/p&gt;
  
  &lt;pre class=&quot;lang:python decode:1&quot;&gt;
</code></pre>
<p>def f(a, L = None):
  if L is None:
    L = []
  L.append(a)
  return L
</pre></p>
<pre><code>  &lt;p&gt;
    Let&amp;#8217;s explain what I meant by saying &amp;#8220;are evaluated only once&amp;#8221;:&lt;br /&gt; When the Python interpreter reaches the line that defines the method, it allocates a list in the memory and assigns its address to L the reference.&lt;br /&gt; Next time you call the function L will reference the same list it referenced the time it was created in memory, so it will always reference the same object.&lt;br /&gt; The second code actually referenced to None, so every time you call the function it will assign None to L.&lt;br /&gt; By understanding what I meant you can consider the following example:
  &lt;/p&gt;
  
  &lt;pre class=&quot;lang:python decode:1&quot;&gt;
</code></pre>
<p>i = 10
def f(a, b = i):
  return a + b
i = 11
print(f(2)) # Will it print 12 or 13?
</pre></p>
<pre><code>  &lt;p&gt;
    &lt;strong&gt;&lt;span style=&quot;color:#666666;font-family:verdana;&quot;&gt;12&lt;/span&gt;&lt;/strong&gt;&lt;br /&gt; That&amp;#8217;s because b was given the value of i before the interpreter reached the line in which i was give the value of 11.
  &lt;/p&gt;
  
  &lt;h1 style=&quot;font-family:Georgia;&quot;&gt;
    Bottom Line
  &lt;/h1&gt;
  
  &lt;p&gt;
    Not that much I presented in this part, but you should consider upgrading your Python knowledge to Python 3.0 for the next time.&lt;br /&gt; And by the way, I&amp;#8217;m sorry, I&amp;#8217;ve betrayed you and learned a lot during the last month, I have also started creating GUI Applications using Python and Qt, so please forgive me 🙂&lt;br /&gt; Cheers.
  &lt;/p&gt;&lt;/div&gt;
</code></pre>]]></content:encoded>
    </item>
    <item>
      <title>iCommunity FOSS 09</title>
      <link>https://mpcabd.xyz/icommunity-foss-09/</link>
      <pubDate>Sun, 08 Feb 2009 00:50:09 +0000</pubDate>
      <guid>https://mpcabd.xyz/icommunity-foss-09/</guid>
      <description>&lt;p&gt;I mentioned many times before that I was planning to make a workshop about Free Open Source Software (FOSS) in Damascus, and thankfully I did 🙂&lt;/p&gt;
&lt;h1 id=&#34;the-idea&#34;&gt;The Idea&lt;/h1&gt;
&lt;p&gt;The idea was to spread the culture of FOSS between the interested people here in Damascus.&lt;/p&gt;
&lt;p&gt;What I noticed was that almost 99% of computer science students didn’t know what Free Software is and what Open Source software is!&lt;/p&gt;</description>
      <content:encoded><![CDATA[<p>I mentioned many times before that I was planning to make a workshop about Free Open Source Software (FOSS) in Damascus, and thankfully I did 🙂</p>
<h1 id="the-idea">The Idea</h1>
<p>The idea was to spread the culture of FOSS between the interested people here in Damascus.</p>
<p>What I noticed was that almost 99% of computer science students didn’t know what Free Software is and what Open Source software is!</p>
<h1 id="the-process">The Process</h1>
<p>So I started contacting engineers and people who I know that they’re capable of teaching this culture to our faculty students, and I managed to make 3 people agree on lecturing in the workshop.</p>
<p>After a while I realized that I can’t make the workshop as I thought, I won’t be able to make lectures inside the faculty because of some freaky stupid bureaucracy.</p>
<p>So the solution came with the idea of iCommunity, and thankfully it solve the problem.</p>
<h1 id="icommunity">iCommunity</h1>
<p>iCommunity is a committee inside <a href="http://www.scs-net.org/">SCS</a> – Syrian Computer Society, which is responsible of connecting the youth</p>
<p>computer science interested people with the SCS and other governmental offices.</p>
<p>It has the power that SCS gave to it, which is to think and prepare for projects that young people want to do and they can’t.</p>
<p>By having iCommunity we can achieve almost what we want with some powerful support from SCS.</p>
<p>And I’m one of the 6 managers of iCommunity, together we decieded that we will make this FOSS Workshop a reality.</p>
<h1 id="the-workshop">The Workshop</h1>
<p>The workshop took place in Damascus, Tishreen Park, SCS Center. From February 3rd to February 5th.</p>
<p>Everyday had lectures, coffee break and installation festival.</p>
<h2 id="the-first-day-03feb2009">The First Day 03/Feb/2009</h2>
<p>We had 3 lectures:</p>
<ol>
<li>What is Free Software? What is Open Source Software? and Why?_ <span style="text-decoration:underline;">Eng. Firas Kassem &amp; Eng. Humam Hawasly.</span>_</li>
<li>What are the licenses of Free and Open Source Software? <em><span style="text-decoration:underline;">Eng. Nada Al Benni.</span></em></li>
<li>What is Creative Commons? <em><span style="text-decoration:underline;">Eng. Zyiad Maraqa from Jordan.</span></em></li>
</ol>
<h2 id="the-second-day-04feb2009">The Second Day 04/Feb/2009</h2>
<p>We had 2 lectures:</p>
<ol>
<li>Arabic Free Open Source projects, and managing them. <a href="http://www.ar-php.org/">Php-ar</a> as an example. <em><span style="text-decoration:underline;">Eng. Khaled Al Shamaa.</span></em></li>
<li>Linux is a great choice for an operating system. <em><span style="text-decoration:underline;">Eng. Emad Mahayni.</span></em></li>
</ol>
<h2 id="the-third-day-05feb2009">The Third Day 05/Feb/2009</h2>
<p>We had 3 lectures:</p>
<ol>
<li>Building unified communication using IP-Telephoney by open source projects. <em><span style="text-decoration:underline;">Eng. Ahmad Osman.</span></em></li>
<li>Practical experiment with using Free Open Source Software in a daily life. <em><span style="text-decoration:underline;">Eng. Hani Al Safadi.</span></em></li>
<li>Finding Free Open Source alternatives to proprietary software. <em><span style="text-decoration:underline;">Abd Allah Diab.</span></em></li>
</ol>
<h2 id="the-installation-festivals">The Installation Festivals</h2>
<p>We told people to bring their laptops so we can teach them how to install Ubuntu 8.10 Intrepid Ibex on it.</p>
<p>There were many interested people so the festival was great.</p>
<p>My friends in the college helped us in the festival, I can’t find any way to thank them.</p>
<p>We also played <a href="http://www.collegehumor.com/video:1886349" target="_blank">this video</a>, that describes what would have happened if The Matrix was real and ran on Windows 🙂</p>
<h2 id="dvds">DVDs</h2>
<p>We distributed two DVD’s to the audience, the first one was Ubuntu 8.10 Desktop Edition DVD i386, and the other was an Open DVD which included a debian repository and free open source software for both operating systems Linux and Windows.</p>
<div>
  <p style="text-align:center;">
    <a href="http://phiras.files.wordpress.com/2009/02/opendvd.png" target="_blank" rel="lightbox[68]" title="iCommunity FOSS 09"><img class="aligncenter" border="0" style="max-width:800px;" src="http://phiras.files.wordpress.com/2009/02/opendvd.png" alt="iCommunity" width="300" height="300" /></a>
  </p>
</div>
<h2 id="media-coverage-and-articles">Media Coverage and Articles</h2>
<p><a href="http://creativecommons.org/weblog/entry/12290" target="_blank">Creative Commons</a> website wrote about Zyiad’s lecture in the worksop:</p>
<blockquote>
<p>Ziad Maraqa, co-Project Lead from CC Jordan, spoke yesterday in Damascus at the <a href="http://www.csc-sy.net/node/9574">iCommunity FOSS Workshop</a>, a notable gathering for the Syrian Free Software community.</p>
</blockquote>
<p>Al Watan Newspaper in Syria wrote about the workshop daily (Arabic):</p>
<p><a href="http://www.alwatan.sy/dindex.php?idn=50788" target="_blank"><a href="http://www.alwatan.sy/dindex.php?idn=50788">http://www.alwatan.sy/dindex.php?idn=50788</a></a></p>
<p><a href="http://www.alwatan.sy/dindex.php?idn=50843" target="_blank"><a href="http://www.alwatan.sy/dindex.php?idn=50843">http://www.alwatan.sy/dindex.php?idn=50843</a></a></p>
<p>eSyria, Syria blog website wrote about the workshop daily in its Damascus website (Arabic):</p>
<p><a href="http://www.edamascus.sy/_activities.php?filename=200902021845011" target="_blank"><a href="http://www.edamascus.sy/_activities.php?filename=200902021845011">http://www.edamascus.sy/_activities.php?filename=200902021845011</a></a></p>
<p><a href="http://www.edamascus.sy/_business.php?filename=200902031620011" target="_blank"><a href="http://www.edamascus.sy/_business.php?filename=200902031620011">http://www.edamascus.sy/_business.php?filename=200902031620011</a></a></p>
<p><a href="http://www.edamascus.sy/_news.php?filename=200902041650013">http://www.edamascus.sy/_news.php?filename=200902041650013</a></p>
<p><a href="http://www.edamascus.sy/_news.php?filename=200902060300011" target="_blank"><a href="http://www.edamascus.sy/_news.php?filename=200902060300011">http://www.edamascus.sy/_news.php?filename=200902060300011</a></a></p>
<h2 id="photos">Photos</h2>
<p>This is a photo of the iCommunity Managers:</p>
<div>
  <p style="text-align:center;">
    <a href="http://phiras.files.wordpress.com/2009/02/img_0055.jpg" target="_blank" rel="lightbox[68]" title="iCommunity FOSS 09"><img class="aligncenter" style="max-width:800px;" src="http://phiras.files.wordpress.com/2009/02/img_0055.jpg" border="0" alt="iCommunity" width="301" height="225" /></a>
  </p>
</div>
<p>This is a photo of the installation team, 4 iCommunity managers, and some students:</p>
<div>
  <p style="text-align:center;">
    <a href="http://magicpc.files.wordpress.com/2009/02/ubuntu.jpg" target="_blank" rel="lightbox[68]" title="iCommunity FOSS 09"><img class="aligncenter" border="0" style="max-width:800px;" src="http://magicpc.files.wordpress.com/2009/02/ubuntu.jpg" alt="" width="301" height="225" /></a>
  </p>
</div>
<p>I’m the one with the gray suit and glasses in the middle 8)</p>
<p>And this one is from above of more students, 5 iCommunity Managers (the 6th is the one behind the camera) and the installation team 🙂</p>
<div>
  <p style="text-align:center;">
    <a href="http://magicpc.files.wordpress.com/2009/02/foss-09-dam.jpg" target="_blank" rel="lightbox[68]" title="iCommunity FOSS 09"><img class="aligncenter" border="0" style="max-width:800px;" src="http://magicpc.files.wordpress.com/2009/02/foss-09-dam.jpg" alt="" width="299" height="224" /></a>
  </p>
</div>
<p>We had wonderful time, and we got great feedback of people attended the workshop.</p>]]></content:encoded>
    </item>
    <item>
      <title>And we’re back</title>
      <link>https://mpcabd.xyz/and-were-back/</link>
      <pubDate>Fri, 06 Feb 2009 13:12:54 +0000</pubDate>
      <guid>https://mpcabd.xyz/and-were-back/</guid>
      <description>&lt;p&gt;After a month of not blogging, I’m back to blogging for Python.&lt;/p&gt;
&lt;p&gt;This month had a lot in it:&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;Computer Science exams @ Damascus University, so I had to study a lot.&lt;/li&gt;
&lt;li&gt;Scientific Calculations Project, the project of this semester.&lt;/li&gt;
&lt;li&gt;FOSS Workshop, which my friends and I arranged to in Damascus, and it was more than wonderful.&lt;/li&gt;
&lt;/ul&gt;
&lt;p&gt;After finishing my Scientific Calculations Project I made the choice of removing Windows for good from my computer, I’m going to make Ubuntu my only operating system to use.&lt;/p&gt;</description>
      <content:encoded><![CDATA[<p>After a month of not blogging, I’m back to blogging for Python.</p>
<p>This month had a lot in it:</p>
<ul>
<li>Computer Science exams @ Damascus University, so I had to study a lot.</li>
<li>Scientific Calculations Project, the project of this semester.</li>
<li>FOSS Workshop, which my friends and I arranged to in Damascus, and it was more than wonderful.</li>
</ul>
<p>After finishing my Scientific Calculations Project I made the choice of removing Windows for good from my computer, I’m going to make Ubuntu my only operating system to use.</p>
<p>The workshop was more than I expected, I witnessed the great participation and work from my friends to make this workshop a successful story to be told.</p>
<p>You can see <a href="http://creativecommons.org/weblog/entry/12290" target="_blank">here</a> that the FOSS workshop was a notable event in Damascus and Syria.</p>
<blockquote>
<p>Ziad Maraqa, co-Project Lead from CC Jordan, spoke yesterday in Damascus at the <a href="http://www.csc-sy.net/node/9574">iCommunity FOSS Workshop</a>, a notable gathering for the Syrian Free Software community.</p>
</blockquote>
<p>And here are some articles about the event but they’re in Arabic:</p>
<p>Al Watan Newspaper:</p>
<p><a href="http://www.alwatan.sy/dindex.php?idn=50788">http://www.alwatan.sy/dindex.php?idn=50788</a></p>
<p><a href="http://www.alwatan.sy/dindex.php?idn=50843">http://www.alwatan.sy/dindex.php?idn=50843</a></p>
<p>eDamscus:</p>
<p><a href="http://www.edamascus.sy/_activities.php?filename=200902021845011">http://www.edamascus.sy/_activities.php?filename=200902021845011</a></p>
<p><a href="http://www.edamascus.sy/_business.php?filename=200902031620011">http://www.edamascus.sy/_business.php?filename=200902031620011</a></p>
<p><a href="http://www.edamascus.sy/_news.php?filename=200902041650013">http://www.edamascus.sy/_news.php?filename=200902041650013</a></p>
<p><a href="http://www.edamascus.sy/_news.php?filename=200902060300011">http://www.edamascus.sy/_news.php?filename=200902060300011</a></p>
<p>Thank you all for waiting a month 🙂</p>
<p>I’m Learning Python part 8 will be here soon.</p>]]></content:encoded>
    </item>
    <item>
      <title>FOSS Workshop</title>
      <link>https://mpcabd.xyz/foss-workshop/</link>
      <pubDate>Sat, 27 Dec 2008 23:04:45 +0000</pubDate>
      <guid>https://mpcabd.xyz/foss-workshop/</guid>
      <description>&lt;p dir=&#34;ltr&#34; style=&#34;direction: ltr; text-align: left;&#34;&gt;
  Hello, if you don&amp;#8217;t know already, I&amp;#8217;m a Computer Science student from Damascus University Syria.
&lt;/p&gt;
&lt;p dir=&#34;ltr&#34; style=&#34;direction: ltr; text-align: left;&#34;&gt;
  My friends and I are working on an Open Source Free Software workshop here at the faculty of Computer Science, the workshop will take place on February 2009, but we are gathering some resources and information from now.
&lt;/p&gt;
&lt;p dir=&#34;ltr&#34; style=&#34;direction: ltr; text-align: left;&#34;&gt;
  The workshop will have lectures about Open Source, Free Software, Licenses, Open Source Free alternative for Commercial Proprietary software, and of course Linux OS.
&lt;/p&gt;
&lt;p dir=&#34;ltr&#34; style=&#34;direction: ltr; text-align: left;&#34;&gt;
  The workshop will also contain an Installation Festival where we are going to install Ubuntu 8.10 Intrepid Ibex for students on their devices and teach them how to use it.
&lt;/p&gt;
&lt;p dir=&#34;ltr&#34; style=&#34;direction: ltr; text-align: left;&#34;&gt;
  I&amp;#8217;m gonna put some questions here and I&amp;#8217;ll ask you to answer it, whether you own an Open Source company or you work for one.
&lt;/p&gt;
&lt;p dir=&#34;ltr&#34; style=&#34;direction: ltr; text-align: left;&#34;&gt;
  I&amp;#8217;m neither a journalist nor an analyst seeker, but I want some answers from you to introduce you the way you want to students, please don&amp;#8217;t waste this message because I&amp;#8217;m not a journalist,  we want to spread the culture of Free Open Source Software here between students and contributing to the workshop would be very kind of you.
&lt;/p&gt;</description>
      <content:encoded><![CDATA[<p dir="ltr" style="direction: ltr; text-align: left;">
  Hello, if you don&#8217;t know already, I&#8217;m a Computer Science student from Damascus University Syria.
</p>
<p dir="ltr" style="direction: ltr; text-align: left;">
  My friends and I are working on an Open Source Free Software workshop here at the faculty of Computer Science, the workshop will take place on February 2009, but we are gathering some resources and information from now.
</p>
<p dir="ltr" style="direction: ltr; text-align: left;">
  The workshop will have lectures about Open Source, Free Software, Licenses, Open Source Free alternative for Commercial Proprietary software, and of course Linux OS.
</p>
<p dir="ltr" style="direction: ltr; text-align: left;">
  The workshop will also contain an Installation Festival where we are going to install Ubuntu 8.10 Intrepid Ibex for students on their devices and teach them how to use it.
</p>
<p dir="ltr" style="direction: ltr; text-align: left;">
  I&#8217;m gonna put some questions here and I&#8217;ll ask you to answer it, whether you own an Open Source company or you work for one.
</p>
<p dir="ltr" style="direction: ltr; text-align: left;">
  I&#8217;m neither a journalist nor an analyst seeker, but I want some answers from you to introduce you the way you want to students, please don&#8217;t waste this message because I&#8217;m not a journalist,  we want to spread the culture of Free Open Source Software here between students and contributing to the workshop would be very kind of you.
</p>
<p dir="ltr" style="direction: ltr; text-align: left;">
  Please allow me to ask you to answer the following questions:
</p>
<p dir="ltr" style="direction: ltr; text-indent: -18pt; text-align: left; margin: 0 0 10pt 36pt;">
  <strong>1.<span style="font: 7pt 'Times New Roman';">       </span></strong><strong>When did you start your company and who started it?</strong>
</p>
<p dir="ltr" style="direction: ltr; text-indent: -18pt; text-align: left; margin: 0 0 10pt 36pt;">
  <strong>2.<span style="font: 7pt 'Times New Roman';">       </span></strong><strong>How did you start your company?</strong>
</p>
<p dir="ltr" style="direction: ltr; text-indent: -18pt; text-align: left; margin: 0 0 10pt 36pt;">
  <strong>3.<span style="font: 7pt 'Times New Roman';">       </span></strong><strong>Why Free Open Source Software? What was the base idea of your company? Did you consider that offering Free Open Source Software might not give you much money? Or money wasn&#8217;t your concern at first?</strong>
</p>
<p dir="ltr" style="direction: ltr; text-indent: -18pt; text-align: left; margin: 0 0 10pt 36pt;">
  <strong>4.<span style="font: 7pt 'Times New Roman';">       </span></strong><strong>What problems did you have to go through till the first line of code was written?</strong>
</p>
<p dir="ltr" style="direction: ltr; text-indent: -18pt; text-align: left; margin: 0 0 10pt 36pt;">
  <strong>5.<span style="font: 7pt 'Times New Roman';">       </span></strong><strong>Most people ask; where and how do you make money? <em>This question needs to be fully described because in my humble opinion it is the most question people and especially students would care about.</em></strong>
</p>
<p dir="ltr" style="direction: ltr; text-indent: -18pt; text-align: left; margin: 0 0 10pt 36pt;">
  <strong>6.<span style="font: 7pt 'Times New Roman';">       </span></strong><strong>Starting a company needs a hard working faithful staff, how did you start collecting your staff? How did you convinced people to work with you knowing that you offer Free Open Source Software?</strong>
</p>
<p dir="ltr" style="direction: ltr; text-indent: -18pt; text-align: left; margin: 0 0 10pt 36pt;">
  <strong>7.<span style="font: 7pt 'Times New Roman';">       </span></strong><strong>After you finished your first prototype, how did you advertise it?</strong>
</p>
<p dir="ltr" style="direction: ltr; text-indent: -18pt; text-align: left; margin: 0 0 10pt 36pt;">
  <strong>8.<span style="font: 7pt 'Times New Roman';">       </span></strong><strong>What was the reaction of people who tested the first software of yours?</strong>
</p>
<p dir="ltr" style="direction: ltr; text-indent: -18pt; text-align: left; margin: 0 0 10pt 36pt;">
  <strong>9.<span style="font: 7pt 'Times New Roman';">       </span></strong><strong>How many people contributed to the first version of your product? And how many downloaded it and used it?</strong>
</p>
<p dir="ltr" style="direction: ltr; text-indent: -18pt; text-align: left; margin: 0 0 10pt 36pt;">
  <strong>10.<span style="font: 7pt 'Times New Roman';">   </span></strong><strong>You must have received thousands of feedback messages after your first product; do you remember the approximate count?</strong>
</p>
<p dir="ltr" style="direction: ltr; text-indent: -18pt; text-align: left; margin: 0 0 10pt 36pt;">
  <strong>11.<span style="font: 7pt 'Times New Roman';">   </span></strong><strong>Competition with know software is indeed hard, how did you manage to make your path between your competitors?</strong>
</p>
<p dir="ltr" style="direction: ltr; text-indent: -18pt; text-align: left; margin: 0 0 10pt 36pt;">
  <strong>12.<span style="font: 7pt 'Times New Roman';">   </span></strong><strong>What are the phases that your company had been in till now? What difficulties and problems did you face?</strong>
</p>
<p dir="ltr" style="direction: ltr; text-indent: -18pt; text-align: left; margin: 0 0 10pt 36pt;">
  <strong>13.<span style="font: 7pt 'Times New Roman';">   </span></strong><strong>How many people contributed to the second version of your product?</strong>
</p>
<p dir="ltr" style="direction: ltr; text-indent: -18pt; text-align: left; margin: 0 0 10pt 36pt;">
  <strong>14.<span style="font: 7pt 'Times New Roman';">   </span></strong><strong>How many people contributed to the last version of your product?</strong>
</p>
<p dir="ltr" style="direction: ltr; text-indent: -18pt; text-align: left; margin: 0 0 10pt 36pt;">
  <strong>15.<span style="font: 7pt 'Times New Roman';">   </span></strong><strong>How many people did you count using your software?</strong>
</p>
<p dir="ltr" style="direction: ltr; text-indent: -18pt; text-align: left; margin: 0 0 10pt 36pt;">
  <strong>16.<span style="font: 7pt 'Times New Roman';">   </span></strong><strong>Do you advice students to start their companies and follow your path, or do you advice them to look for jobs in companies like yours?</strong>
</p>
<p dir="ltr" style="direction: ltr; text-indent: -18pt; text-align: left; margin: 0 0 10pt 36pt;">
  <strong>17.<span style="font: 7pt 'Times New Roman';">   </span></strong><strong>What must the student of Computer Science study to be able to work for you? What techniques? Programming Languages? Tools? What do you seek in your workers to have and know?</strong>
</p>
<p dir="ltr" style="direction: ltr; text-indent: -18pt; text-align: left; margin: 0 0 10pt 36pt;">
  <p>
    <strong>18.<span style="font: 7pt 'Times New Roman';">   </span></strong><strong>If by any means you had the chance to talk to our students and give them a message, what would it be?</strong>
  </p>
  <p dir="ltr" style="direction: ltr; text-align: left;">
    You can of course answer as much as you want of the questions above, but I hope you answer all of them for the sake of Free Open Source Software and knowledge.
  </p>
  <p dir="ltr" style="direction: ltr; text-align: left;">
    Thank you from all my heart, and on behalf of my friends and colleagues I thank you, we appreciate your efforts and your contributions.
  </p>
  <p dir="ltr" style="direction: ltr; text-align: left;">
    <p dir="ltr" style="direction: ltr; text-align: left;">
      Abd Allah Diab
    </p>
<pre><code>&lt;p dir=&quot;ltr&quot; style=&quot;direction: ltr; text-align: left;&quot;&gt;
  Computer Science Faculty
&lt;/p&gt;

&lt;p dir=&quot;ltr&quot; style=&quot;direction: ltr; text-align: left;&quot;&gt;
  Damascus University
&lt;/p&gt;

&lt;p dir=&quot;ltr&quot; style=&quot;direction: ltr; text-align: left;&quot;&gt;
  Syria
&lt;/p&gt;
</code></pre>]]></content:encoded>
    </item>
    <item>
      <title>Just a month</title>
      <link>https://mpcabd.xyz/just-a-month/</link>
      <pubDate>Fri, 19 Dec 2008 21:43:21 +0000</pubDate>
      <guid>https://mpcabd.xyz/just-a-month/</guid>
      <description>&lt;p&gt;I’m sorry to announce that I won’t be able to post any posts until the end of January 2009, and that’s because of my university exams 🙂&lt;/p&gt;
&lt;p&gt;Thank you for visiting me, and see ya soon 😉&lt;/p&gt;
&lt;p&gt;P.S.&lt;/p&gt;
&lt;p&gt;Wish me luck and high marks 😀&lt;/p&gt;</description>
      <content:encoded><![CDATA[<p>I’m sorry to announce that I won’t be able to post any posts until the end of January 2009, and that’s because of my university exams 🙂</p>
<p>Thank you for visiting me, and see ya soon 😉</p>
<p>P.S.</p>
<p>Wish me luck and high marks 😀</p>
]]></content:encoded>
    </item>
    <item>
      <title>I’m Learning Python part 7</title>
      <link>https://mpcabd.xyz/im-learning-python-part-7/</link>
      <pubDate>Fri, 28 Nov 2008 23:35:36 +0000</pubDate>
      <guid>https://mpcabd.xyz/im-learning-python-part-7/</guid>
      <description>&lt;div dir=&#34;ltr&#34;&gt;
  &lt;div dir=&#34;ltr&#34; style=&#34;text-align: center;&#34;&gt;
    &lt;h1 style=&#34;font-size: 18pt; font-family: Verdana;&#34;&gt;
      I&amp;#8217;m Learning Python (part 7)
    &lt;/h1&gt;
&lt;pre&gt;&lt;code&gt;&amp;lt;p&amp;gt;
  &amp;lt;img title=&amp;quot;Python Logo&amp;quot; src=&amp;quot;http://www.python.org/images/python-logo.gif&amp;quot; alt=&amp;quot;Python Logo&amp;quot; /&amp;gt;
&amp;lt;/p&amp;gt;
&lt;/code&gt;&lt;/pre&gt;
  &lt;/div&gt;
  &lt;h1 style=&#34;font-family: Georgia;&#34;&gt;
    Apology:
  &lt;/h1&gt;
  &lt;p&gt;
    First of all I wanna apologize for being late with this part, I&amp;#8217;ve had busy days first during Shaam 2008 expo and second during some studies at the college and last busy time past launching Bawabaty project.&lt;br /&gt;</description>
      <content:encoded><![CDATA[<div dir="ltr">
  <div dir="ltr" style="text-align: center;">
    <h1 style="font-size: 18pt; font-family: Verdana;">
      I&#8217;m Learning Python (part 7)
    </h1>
<pre><code>&lt;p&gt;
  &lt;img title=&quot;Python Logo&quot; src=&quot;http://www.python.org/images/python-logo.gif&quot; alt=&quot;Python Logo&quot; /&gt;
&lt;/p&gt;
</code></pre>
  </div>
  <h1 style="font-family: Georgia;">
    Apology:
  </h1>
  <p>
    First of all I wanna apologize for being late with this part, I&#8217;ve had busy days first during Shaam 2008 expo and second during some studies at the college and last busy time past launching Bawabaty project.<br /> 
</p>
  <h1 style="font-family: Georgia;">
    Numbers:
  </h1>
  <p>
    Numbers in Python are divided into 5 sections:
  </p>
  <p>
    Integers:
  </p>
  <p>
    Such as: 1234, -1234, 0
  </p>
  <p>
    Long Integers (unlimited size):
  </p>
  <p>
    Such as: 71632487932648921735413278645238947231659821365213847L
  </p>
  <p>
    These numbers grow as long as your memory can hold, and it ends with a small or capital L but it is an optional literal, you can define:
  </p>
  <p>
    />>> TheLongVariable = 99999999999999999999999999
  </p>
  <p>
    />>> TheLongVariable
  </p>
  <p>
    99999999999999999999999999L
  </p>
  <p>
    Floating Point Numbers:
  </p>
  <p>
    Such as: 1.234, 3.14e-10, 4.01e+12
  </p>
  <p>
    You can define them using points, e or E.
  </p>
  <p>
    Octal and hex literals:
  </p>
  <p>
    Such as: 0172, 0x9fab, 0X3FBC
  </p>
  <p>
    Octal is defined by starting your number with a leading zero, while hexadecimal is defined by starting you number by a leading 0x or 0X.
  </p>
  <p>
    Complex Numbers:
  </p>
  <p>
    Such as: 3+4j, 3.0-5.1j, 3J
  </p>
  <p>
    Complex numbers are defined by a j or J at the end of the number, the number can consist of two parts, real and imaginary, so all the following are complex numbers:
  </p>
  <p>
    1 + 3j, 3j, 5J, -10.1j
  </p>
  <h1 style="font-family: Georgia;">
    Python has lots of built-in numeric tools:
  </h1>
  <p>
    Of course you can use +, -, *, /, <, >, ==, !=, <> as any other programming language, but Python has more:
  </p>
  <p>
    **: Power, 2 ** 3 is 8.
  </p>
  <p>
    //: Is truncated division, 5 // 2 is 2
  </p>
  <p>
    %: Remainder, 5 % 2 is 1
  </p>
  <p>
    You can use also bitwise operations:
  </p>
  <p>
    />>, << shift right and left, 5 << 2 is 20, 24 >> 3 is 3.
  </p>
  <p>
    |, & Or and And, 4 | 3 is 7, 7 & 2 is 2.
  </p>
  <p>
    Just as any other programming language, Python deals with expressions using operator precedence: 3 + 4 * 2 is 11 because * is done before +.
  </p>
  <p>
    Of course you can use parentheses to define the way you want to deal with the expression, (3+ 4) * 2 is 14.
  </p>
  <p>
    When mixing multiple types in an expressions, all types are converted up, 40 + 3.14 will be calculated as 40.0 + 3.14. The types are ordered like this:
  </p>
  <p>
    Integers < Long Integers < Floating Points < Complex Numbers.
  </p>
  <p>
    The type of the result of a mixed expression is the type of the higher type, so 40 + 3.14 is a floating point, but you can force it into an integer using: int(40 + 3.14).
  </p>
  <h1 style="font-family: Georgia;">
    Variables:
  </h1>
  <p>
    During our trip in Python till now we used variables but we haven&#8217;t talked about them:
  </p>
  <p>
    Variables are created once they are assigned a value.
  </p>
  <p>
    Variables are replaced with their values in expressions.
  </p>
  <p>
    You can&#8217;t use an unassigned variable, because simply you don&#8217;t have the variable yet.
  </p>
  <p>
    Variables are references to objects.
  </p>
  <h1 style="font-family: Georgia;">
    repr & str:
  </h1>
  <p>
    Try this
  </p>
  <p>
    />>> a = 3
  </p>
  <p>
    />>> b = 4
  </p>
  <p>
    />>> b / (2.0 + a)
  </p>
  <p>
    0.80000000000000004
  </p>
  <p>
    />>> print b / (2.0 + a)
  </p>
  <p>
    0.8
  </p>
  <p>
    We&#8217;ve seen something like this before, and we discussed it, the difference between the two methods is that each one uses a specified function, the first uses a function called repr which prints the value as it is in your memory, while the other uses a function called str which prints the value in a user friendly way.
  </p>
  <h1 style="font-family: Georgia;">
    More Functions:
  </h1>
  <p>
    Python provides functions for Octal and Hex conversion:
  </p>
  <p>
    />>> oct(64)
  </p>
  <p>
    &#8216;0100&#8217;
  </p>
  <p>
    />>> oct(8 )
  </p>
  <p>
    &#8216;010&#8217;
  </p>
  <p>
    />>> hex(255)
  </p>
  <p>
    &#8216;0xff&#8217;
  </p>
  <p>
    And vice versa, Python provides functions for retrieving integers out of Hex and Oct:
  </p>
  <p>
    />>> int(&#8216;0234&#8217;)
  </p>
  <p>
    234
  </p>
  <p>
    />>> int(&#8216;0234&#8217;, 8 )
  </p>
  <p>
    256
  </p>
  <p>
    />>> int(&#8216;0234&#8242;, 16)
  </p>
  <p>
    564
  </p>
  <p>
    And it also provides a way to format numbers in strings, which we will cover in another part, but a small example won&#8217;t hurt:
  </p>
  <p>
    />>> &#8220;%o %x&#8221; % (25, 21)
  </p>
  <p>
    &#8217;31 15&#8217;
  </p>
  <p>
    Other built-in functions and methods are in math module, which you can import and use:
  </p>
  <p>
    />>> import math
  </p>
  <p>
    />>> math.pi, math.e
  </p>
  <p>
    (3.1415926535897931, 2.7182818284590451)
  </p>
  <p>
    />>> math.sin(math.pi / 2)
  </p>
  <p>
    1.0
  </p>
</div>
<div dir="ltr">
  The result shown in parentheses is a tuple (which we covered last part), it is shown in a tuple because we put a column between math.pi and math.e</p> 
  <h1 style="font-family: Georgia;">
    Bottom Line:
  </h1>
  <p>
    Thank you for waiting for this part, and until I meet you on another part try to read more about numbers from the online documentation of Python.
  </p>
  <p>
    Cheers.
  </p>
</div>
<p> </p>]]></content:encoded>
    </item>
    <item>
      <title>I’m Learning Python part 6</title>
      <link>https://mpcabd.xyz/im-learning-python-part-6/</link>
      <pubDate>Fri, 07 Nov 2008 21:36:29 +0000</pubDate>
      <guid>https://mpcabd.xyz/im-learning-python-part-6/</guid>
      <description>&lt;div dir=&#34;ltr&#34;&gt;
  &lt;div style=&#34;text-align: center;&#34;&gt;
    &lt;h1 style=&#34;font-size: 18pt; font-family: Verdana;&#34;&gt;
      I&amp;#8217;m Learning Python (part 6)
    &lt;/h1&gt;
&lt;pre&gt;&lt;code&gt;&amp;lt;p&amp;gt;
  &amp;lt;img title=&amp;quot;Python Logo&amp;quot; src=&amp;quot;http://www.python.org/images/python-logo.gif&amp;quot; alt=&amp;quot;Python Logo&amp;quot; /&amp;gt;
&amp;lt;/p&amp;gt;
&lt;/code&gt;&lt;/pre&gt;
  &lt;/div&gt;
  &lt;h1 style=&#34;font-family: Georgia;&#34;&gt;
    Dictionaries
  &lt;/h1&gt;
  &lt;div dir=&#34;ltr&#34;&gt;
    Dictionaries in Python are like dictionaries in life, they consist of key-value pairs, each key maps a value, values can be any object type, and keys also. Keys must be unique, I mean that we can&amp;#8217;t have two identical keys with different values.
  &lt;/div&gt;
  &lt;p&gt;</description>
      <content:encoded><![CDATA[<div dir="ltr">
  <div style="text-align: center;">
    <h1 style="font-size: 18pt; font-family: Verdana;">
      I&#8217;m Learning Python (part 6)
    </h1>
<pre><code>&lt;p&gt;
  &lt;img title=&quot;Python Logo&quot; src=&quot;http://www.python.org/images/python-logo.gif&quot; alt=&quot;Python Logo&quot; /&gt;
&lt;/p&gt;
</code></pre>
  </div>
  <h1 style="font-family: Georgia;">
    Dictionaries
  </h1>
  <div dir="ltr">
    Dictionaries in Python are like dictionaries in life, they consist of key-value pairs, each key maps a value, values can be any object type, and keys also. Keys must be unique, I mean that we can&#8217;t have two identical keys with different values.
  </div>
  <p>
</p>
  <div dir="ltr">
    Dictionaries are defined using curly braces { and } as the following:
  </div>
  <div dir="ltr">
    <em>>>> D = {&#8216;name&#8217; : &#8216;Abd Allah Diab&#8217;, &#8216;age&#8217; : 19, &#8216;job&#8217; : &#8216;Web Developer&#8217;}</em>
  </div>
  <div dir="ltr">
    Now we can access any of the pairs using only the key:
  </div>
  <div dir="ltr">
    <em>>>> D[&#8216;age&#8217;]</em>
  </div>
  <div dir="ltr">
    <em>19</em>
  </div>
  <div dir="ltr">
    Dictionaries are mutable objects, which means we can change their values in place:
  </div>
  <div dir="ltr">
    <em>>>> D[&#8216;age&#8217;] += 1</em>
  </div>
  <div dir="ltr">
    <em>>>> D[&#8216;age&#8217;]</em>
  </div>
  <div dir="ltr">
    <em>20</em>
  </div>
  <div dir="ltr">
    We can add new pairs also easily:
  </div>
  <div dir="ltr">
    <em>>>> D[&#8216;eyes&#8217;] = &#8216;brown&#8217;</em>
  </div>
  <div dir="ltr">
    <em>>>> D</em>
  </div>
  <div dir="ltr">
    <em>{&#8216;job&#8217; : &#8216;Web Developer&#8217;, &#8216;age&#8217; : 20&#8242;, &#8216;eyes&#8217; : &#8216;brown&#8217;, &#8216;name&#8217; : &#8216;Abd Allah Diab&#8217;}</em>
  </div>
  <div dir="ltr">
    As you can see, the dictionary is not sorted, we entered the name first then the age and job, and at last we added the eyes, but it prints in a different order.<br /> To sort a dictionary you should sort its keys and then print the values of the keys after sorting like the following:
  </div>
  <div dir="ltr">
    <em>>>> keys = D.keys()</em>
  </div>
  <div dir="ltr">
    <em>>>> keys [&#8216;job&#8217;, &#8216;age&#8217;, &#8216;eyes&#8217;, &#8216;name&#8217;]</em>
  </div>
  <div dir="ltr">
    <em>>>> keys.sort()</em>
  </div>
  <div dir="ltr">
    <em>>>> keys</em>
  </div>
  <div dir="ltr">
    <em>[&#8216;age&#8217;, &#8216;eyes&#8217;, &#8216;job&#8217;, &#8216;name&#8217;]</em>
  </div>
  <div dir="ltr">
    <em>>>> for key in keys:</em>
  </div>
  <div dir="ltr">
    <em> print key, &#8216;=>&#8217;, D[key]</em>
  </div>
  <div dir="ltr">
    <em>age => 20</em>
  </div>
  <div dir="ltr">
    <em>eyes => brown</em>
  </div>
  <div dir="ltr">
    <em>job => Web Developer</em>
  </div>
  <div dir="ltr">
    <em>name => Abd Allah Diab</em>
  </div>
  <div dir="ltr">
    Here we used a for loop which I haven&#8217;t covered, but it is just like list comprehensions, it will do what follows its declaration for each member of the set (here keys).
  </div>
  <div dir="ltr">
    Please notice the <strong>indentation</strong>, after the for declaration you must hit the &#8216;tab&#8217; for each line inside the for loop, and to exit the loop just don&#8217;t hit the &#8216;tab&#8217; (press &#8216;enter&#8217; in interactive mode).
  </div>
  <div dir="ltr">
    You can make use of a new method called &#8216;sorted&#8217; which takes any iteratable object (like a sequence or a string etc):
  </div>
  <div dir="ltr">
    <em>>>> for key in sorted(D)</em>
  </div>
  <div dir="ltr">
    <em> print key, &#8216;=>&#8217;, D[key]</em>
  </div>
  <div dir="ltr">
    <em>age => 20</em>
  </div>
  <div dir="ltr">
    <em>eyes => brown</em>
  </div>
  <div dir="ltr">
    <em>job => Web Developer</em>
  </div>
  <div dir="ltr">
    <em>name => Abd Allah Diab </em>
  </div>
  <h1 style="font-family: Georgia;">
    Nesting
  </h1>
  <div dir="ltr">
    As I told you @ first, the values can be any object, so we can nest anything inside dictionaries, for example if I want to store the first name and last name inside the &#8216;name&#8217; in the dictionary, and to save a list of jobs inside the &#8216;job&#8217; in the dictionary, I&#8217;d do that just like I nested matrices last time:
  </div>
  <div dir="ltr">
    <em>>>> D = {&#8216;name&#8217; : {&#8216;first&#8217; : &#8216;Abd Allah&#8217;, &#8216;last&#8217; : &#8216;Diab&#8217;}, &#8216;age&#8217; : 19, &#8216;job&#8217; : [&#8216;Web Developer&#8217;, &#8216;Teacher&#8217;, &#8216;Student&#8217;]}</em>
  </div>
  <div dir="ltr">
    Now let&#8217;s see how we can access what we&#8217;ve built:
  </div>
  <div dir="ltr">
    <em>>>> D[&#8216;name&#8217;]</em>
  </div>
  <div dir="ltr">
    <em>{&#8216;first&#8217; : &#8216;Abd Allah&#8217;, &#8216;last&#8217; : &#8216;Diab&#8217;}</em>
  </div>
  <div dir="ltr">
    <em>>>> D[&#8216;name&#8217;][&#8216;first&#8217;]</em>
  </div>
  <div dir="ltr">
    <em>&#8216;Abd Allah&#8217;</em>
  </div>
  <div dir="ltr">
    <em>>>> D[&#8216;name&#8217;][&#8216;last&#8217;]</em>
  </div>
  <div dir="ltr">
    <em>&#8216;Diab&#8217;</em>
  </div>
  <div dir="ltr">
    <em>>>> D[&#8216;job&#8217;]</em>
  </div>
  <div dir="ltr">
    <em>[&#8216;Web Developer&#8217;, &#8216;Teacher&#8217;, &#8216;Student&#8217;]</em>
  </div>
  <div dir="ltr">
    <em>>>> D[&#8216;job&#8217;][0]</em>
  </div>
  <div dir="ltr">
    <em>&#8216;Web Developer&#8217;</em>
  </div>
  <div dir="ltr">
    <em>>>> D[&#8216;job&#8217;][-1]</em>
  </div>
  <div dir="ltr">
    <em>&#8216;Student&#8217;</em>
  </div>
  <div dir="ltr">
  </div>
  <div dir="ltr">
    Pretty easy right? 🙂
  </div>
  <h1 style="font-family: Georgia;">
    Memory issue
  </h1>
  <div dir="ltr">
    Did you ask yourself where did the old D dictionary go?
  </div>
  <div dir="ltr">
    In C, C++ and many other old languages you had to manage memory by hand, but in advanced languages like Java, .NET and Python there exists a garbage collector which handles this process for you, whenever you an object has no references the garbage collector will deallocate its space.
  </div>
  <h1 style="font-family: Georgia;">
    Missing keys
  </h1>
  <div dir="ltr">
    When accessing a dictionary you should be careful to missing keys, especially when the dictionary is filled dynamically.
  </div>
  <div dir="ltr">
    Accessing a missing key will be a mistake:
  </div>
  <div dir="ltr">
    <em>>>> D[&#8216;FFF&#8217;] #Will give you a key error.</em><br /> To avoid this mistake you can ask the dictionary if it has the key then you can access it:
  </div>
  <div dir="ltr">
    <em>>>> if not D.has_key(&#8216;fff&#8217;):</em>
  </div>
  <div dir="ltr">
    <em> print &#8216;MISS&#8217;</em>
  </div>
  <div dir="ltr">
    <em>MISS</em>
  </div>
  <div dir="ltr">
    Here we used the if control, which takes this form:
  </div>
  <div dir="ltr">
    if <Condition1>:
  </div>
  <div dir="ltr">
    Block1
  </div>
  <div dir="ltr">
    elif <Condition2>:
  </div>
  <div dir="ltr">
    Block2
  </div>
  <div dir="ltr">
    .<br /> .
  </div>
  <div dir="ltr">
    elif <ConditionN>:
  </div>
  <div dir="ltr">
    BlockN
  </div>
  <div dir="ltr">
    else:
  </div>
  <div dir="ltr">
    Block
  </div>
  <div dir="ltr">
    Notice the <strong>indentation</strong>, &#8216;cuz in Python the scope is defined using indention not curly braces or Begin and End.
  </div>
  <div dir="ltr">
  </div>
  <h1 style="font-family: Georgia;">
    For Loops, List Comprehensions and Performance
  </h1>
  <div dir="ltr">
    Every list comprehension can be done using a for loop instead:
  </div>
  <div dir="ltr">
    <em>>>> squares = [x ** 2 for x in [1, 2, 3, 4, 5]]</em>
  </div>
  <div dir="ltr">
    <em>>>> squares</em>
  </div>
  <div dir="ltr">
    <em>[1, 4, 9, 16, 25]</em>
  </div>
  <div dir="ltr">
    Can be done:
  </div>
  <div dir="ltr">
    <em>>>> squares = []</em>
  </div>
  <div dir="ltr">
    <em>>>> for x in [1, 2, 3, 4, 5]</em>
  </div>
  <div dir="ltr">
    <em> squares.append(x ** 2)</em>
  </div>
  <div dir="ltr">
    <em>>>> squares</em>
  </div>
  <div dir="ltr">
    <em>[1, 4, 9, 16, 25]</em>
  </div>
  <div dir="ltr">
    But the former is faster than the latter (sometimes it is twice faster), that&#8217;s because Python is optimized, and every new version is faster and optimized more than old ones.
  </div>
  <div dir="ltr">
    So the rule in Python is &#8220;Code for simplicity and readability firs, and worry about performance later&#8221; but in most cases you will stop after writing a readable program, &#8216;cuz Python is optimized by itself.
  </div>
  <h1 style="font-family: Georgia;">
    Tuples
  </h1>
  <div dir="ltr">
    Tuples (pronounced &#8216;tooples&#8217;) are just like lists but they are immutable, which mean that they can&#8217;t be changed once the are created, but like strings support type methods (split, len, &#8230;) and nesting and sequence operations.
  </div>
  <div dir="ltr">
    Tuples are defined in parentheses ( ):
  </div>
  <div dir="ltr">
    <em>>>> T = (1, 2, 3, 4)</em>
  </div>
  <div dir="ltr">
    <em>>>> T</em>
  </div>
  <div dir="ltr">
    <em>(1, 2, 3, 4)</em>
  </div>
  <div dir="ltr">
    <em>>>> T[2]</em>
  </div>
  <div dir="ltr">
    <em>3</em>
  </div>
  <div dir="ltr">
    <em>>>> T[-1]</em>
  </div>
  <div dir="ltr">
    <em>4</em>
  </div>
  <div dir="ltr">
    <em>>>> T = T + (5, 6, 7)</em>
  </div>
  <div dir="ltr">
    <em>>>> T</em>
  </div>
  <div dir="ltr">
    <em>(1, 2, 3, 4, 5, 7)</em>
  </div>
  <div dir="ltr">
    You might wonder, why would I use an immutable list when I can use a list? The answer is that sometimes you might want to call a method with a list parameter which you don&#8217;t want it to be changed, or when you send lists through your program and you don&#8217;t want them to be changed, you&#8217;ll use tuples then.
  </div>
  <h1 style="font-family: Georgia;">
    Other File Types
  </h1>
  <div dir="ltr">
    Those types we discussed aren&#8217;t the only types, there exist more types, such as sets, which are like mathematical sets (a container for a list of objects):
  </div>
  <div dir="ltr">
    <em>>>> X = set([1, 2, 3, 4])</em>
  </div>
  <div dir="ltr">
    <em>>>> X set([1, 2, 3, 4])</em>
  </div>
  <div dir="ltr">
    <em>>>> X.add(5)</em>
  </div>
  <div dir="ltr">
    <em>>>> X</em>
  </div>
  <div dir="ltr">
    <em>set([1, 2, 3, 4, 5])</em>
  </div>
  <div dir="ltr">
    <em>>>> Y = set([1, 6, 3])</em>
  </div>
  <div dir="ltr">
    <em>>>> X & Y #Intersection</em>
  </div>
  <div dir="ltr">
    <em>set([1, 3])</em>
  </div>
  <div dir="ltr">
    <em>>>> X | Y #Union</em>
  </div>
  <div dir="ltr">
    <em>set([1, 2, 3, 4, 5, 6])</em>
  </div>
  <div dir="ltr">
    <em>>>> X &#8211; Y #Difference<br /> </em>
  </div>
  <div dir="ltr">
    <em>set([2, 4, 5])</em>
  </div>
  <div dir="ltr">
    Python also supports lots of types, but we won&#8217;t cover them all here (or at least now :)).
  </div>
  <h1 style="font-family: Georgia;">
    User-defined Types
  </h1>
  <div dir="ltr">
    You can build your own classes in Python:
  </div>
  <div dir="ltr">
    <em>>>> class Man:</em>
  </div>
  <div dir="ltr">
    <em> def __intit__(self, name, age): #Constructor which takes two parameters and saves them</em>
  </div>
  <div dir="ltr">
    <em> self.name = name #self is the object that we&#8217;re calling the method on.</em>
  </div>
  <div dir="ltr">
    <em> self.age = age</em>
  </div>
  <div dir="ltr">
    <em> def lastname(self): #A method to get the last name of the man.</em>
  </div>
  <div dir="ltr">
    <em> return self.name.split(&#8216; &#8216;)[-1]</em>
  </div>
  <div dir="ltr">
    Now you can use your class:
  </div>
  <div dir="ltr">
    <em>>>> me = Man(&#8216;Abd Allah Diab&#8217;, 19) #Initialize a new instance of Man </em>
  </div>
  <div dir="ltr">
    <em>>>> me.lastname()</em>
  </div>
  <div dir="ltr">
    <em>&#8216;Diab&#8217;</em>
  </div>
  <div dir="ltr">
    <em>>>> me.age</em>
  </div>
  <div dir="ltr">
    <em>19</em>
  </div>
  <div dir="ltr">
    We won&#8217;t discuss classes and objects here, but I wanted to show you that you can have your own type easily.
  </div>
  <h1 style="font-family: Georgia;">
    Bottom Line
  </h1>
</div>
<div dir="ltr">
  Here we come to the end of our tour on built in primitive types of Python, Next time we&#8217;ll start our detailed trip to Numbers 🙂
</div>
<div dir="ltr">
  Until then keep coding and make mistakes, and don&#8217;t forget to learn of your mistakes 😀
</div>
<div dir="ltr">
</div>
<div dir="ltr">
  Cheers.
</div>]]></content:encoded>
    </item>
    <item>
      <title>I’m Learning Python (part 5)</title>
      <link>https://mpcabd.xyz/im-learning-python-part-5/</link>
      <pubDate>Wed, 29 Oct 2008 15:34:38 +0000</pubDate>
      <guid>https://mpcabd.xyz/im-learning-python-part-5/</guid>
      <description>&lt;div dir=&#34;ltr&#34;&gt;
  &lt;div style=&#34;text-align: center;&#34;&gt;
    &lt;h1 style=&#34;font-size: 18pt; font-family: Verdana;&#34;&gt;
      I&amp;#8217;m Learning Python (part 5)
    &lt;/h1&gt;
&lt;pre&gt;&lt;code&gt;&amp;lt;p&amp;gt;
  &amp;lt;img title=&amp;quot;Python Logo&amp;quot; src=&amp;quot;http://www.python.org/images/python-logo.gif&amp;quot; alt=&amp;quot;Python Logo&amp;quot; /&amp;gt;
&amp;lt;/p&amp;gt;
&lt;/code&gt;&lt;/pre&gt;
  &lt;/div&gt;
  &lt;h1 style=&#34;font-family: Georgia;&#34;&gt;
    String Is Immutable?
  &lt;/h1&gt;
  &lt;p&gt;
    Last time I told you to try to change a specified character, you must have failed if you tried:&lt;br /&gt; &lt;em&gt;&gt;&gt;&gt; s[0] = &amp;#8216;c&amp;#8217;&lt;/em&gt;&lt;br /&gt; The error you&amp;#8217;d get is:&lt;br /&gt; &lt;em&gt;TypeError: &amp;#8216;str&amp;#8217; object does not support item assignment&lt;br /&gt; &lt;/em&gt;This means that strings are immutable, so are core-types, numbers and tuples, they can’t be changed, while lists and dictionaries can be changed freely.&lt;br /&gt;</description>
      <content:encoded><![CDATA[<div dir="ltr">
  <div style="text-align: center;">
    <h1 style="font-size: 18pt; font-family: Verdana;">
      I&#8217;m Learning Python (part 5)
    </h1>
<pre><code>&lt;p&gt;
  &lt;img title=&quot;Python Logo&quot; src=&quot;http://www.python.org/images/python-logo.gif&quot; alt=&quot;Python Logo&quot; /&gt;
&lt;/p&gt;
</code></pre>
  </div>
  <h1 style="font-family: Georgia;">
    String Is Immutable?
  </h1>
  <p>
    Last time I told you to try to change a specified character, you must have failed if you tried:<br /> <em>>>> s[0] = &#8216;c&#8217;</em><br /> The error you&#8217;d get is:<br /> <em>TypeError: &#8216;str&#8217; object does not support item assignment<br /> </em>This means that strings are immutable, so are core-types, numbers and tuples, they can’t be changed, while lists and dictionaries can be changed freely.<br /> 
</p>
  <h1 style="font-family: Georgia;">
    More Methods?
  </h1>
  <p>
    All the previous methods and operations are sequence operations, but strings have more methods:<br /> <em>>>> s = &#8216;My Text&#8217;<br /> >>> s.find(&#8216;Tex&#8217; ) #returns the index of the first occurrence of the parameter<br /> </em>3<em><br /> >>> s.find(&#8216;abc&#8217; ) #if the parameter wasn&#8217;t found it will return -1<br /> -1<br /> >>> s.replace(&#8216;Text&#8217;, &#8216;Code&#8217; ) #replaces every occurrence of the first parameter with the second one &#8216;My Code&#8217; >>> s #notice that the string hasn&#8217;t changed<br /> &#8216;My Text&#8217;<br /> >>> s = &#8216;aa,bb,cc,dd&#8217;<br /> >>> s.split(&#8216;,&#8217; ) #splits the string into a list of values separated with the parameter<br /> [&#8216;aa&#8217;, &#8216;bb&#8217;, &#8216;cc&#8217;, &#8216;dd&#8217;]<br /> >>> s =&#8217;My Text\n&#8217;<br /> >>> s.rstrip() #removes white space characters from the right of the string<br /> &#8216;My Text&#8217;<br /> >>> s #don&#8217;t forget that the string hasn’t changed 😉<br /> &#8216;My Text\n&#8217;<br /> >>> len(s) #returns the length of the string<br /> </em>8<em><br /> >>> ord(&#8216;\n&#8217; ) #returns the ASCII code for the given character<br /> 10<br /> >>> s = &#8216;MyTextA&#8217; # is the null character though it doesn&#8217;t terminate the string ?<br /> >>> len(s)<br /> </em>9<em><br /> >>> s<br /> &#8216;MyTextA&#8217;<br /> </em>
  </p>
  <h1 style="font-family: Georgia;">
    Wanna Get More?
  </h1>
  <p>
    Of course I can&#8217;t talk about every method for every type, but I&#8217;ll give you a simple way to get more, in Python there is a method called &#8220;dir&#8221; which lists the object&#8217;s methods and properties:<br /> <em>>>> dir(s)<br /> [&#8216;__add__&#8217;, &#8216;__class__&#8217;, &#8216;__contains__&#8217;, &#8216;__delattr__&#8217;, &#8216;__doc__&#8217;, &#8216;__eq__&#8217;, &#8216;__format__&#8217;, __ge__&#8217;, &#8216;__getattribute__&#8217;, &#8216;__getitem__&#8217;, &#8216;__getnewargs__&#8217;, &#8216;__getslice__&#8217;, &#8216;__gt__&#8217;, __hash__&#8217;, &#8216;__init__&#8217;, &#8216;__le__&#8217;, &#8216;__len__&#8217;, &#8216;__lt__&#8217;, &#8216;__mod__&#8217;, &#8216;__mul__&#8217;, &#8216;__ne__&#8217;, &#8216;__new__&#8217;, __reduce__&#8217;, &#8216;__reduce_ex__&#8217;, &#8216;__repr__&#8217;, &#8216;__rmod__&#8217;, &#8216;__rmul__&#8217;, &#8216;__setattr__&#8217;, __sizeof__&#8217;, __str__&#8217;, &#8216;__subclasshook__&#8217;, &#8216;_formatter_field_name_split&#8217;, &#8216;_formatter_parser&#8217;, &#8216;capitalize&#8217;, center&#8217;, &#8216;count&#8217;, &#8216;decode&#8217;, &#8216;encode&#8217;, &#8216;endswith&#8217;, &#8216;expandtabs&#8217;, &#8216;find&#8217;, &#8216;format&#8217;, &#8216;index&#8217;, isalnum&#8217;, isalpha&#8217;, &#8216;isdigit&#8217;, &#8216;islower&#8217;, &#8216;isspace&#8217;, &#8216;istitle&#8217;, &#8216;isupper&#8217;,&#8217;join&#8217;, &#8216;ljust&#8217;, &#8216;lower&#8217;, &#8216;lstrip&#8217;, &#8216;partition&#8217;, replace&#8217;, &#8216;rfind&#8217;, &#8216;rindex&#8217;, &#8216;rjust&#8217;, &#8216;rpartition&#8217;, &#8216;rsplit&#8217;, &#8216;rstrip&#8217;, &#8216;split&#8217;, &#8216;splitlines&#8217;, &#8216;startswith&#8217;, &#8216;strip&#8217;, &#8216;swapcase&#8217;, &#8216;title&#8217;, &#8216;translate&#8217;, &#8216;upper&#8217;, &#8216;zfill&#8217;]<br /> </em>Don&#8217;t care about those who has underscores, but the rest are methods.<br /> Now to know more about a specified method you can use the &#8220;help&#8221; method:<br /> <em>>>> help(s.count)<br /> Help on built-in function count:<br /> count(&#8230;)<br /> </em><em>S.count(sub[, start[, end]]) -> int<br /> Return the number of non-overlapping occurrences of substring sub in string S[start:end].<br /> Optional arguments start and end are interpreted as in slice notation.<br /> </em>
  </p>
  <h1 style="font-family: Georgia;">
    What About Regular Expressions?
  </h1>
  <p>
    Users with a background about regular expressions will definitely ask about it, and the answer is yes you can use them with strings:<br /> <em>>>> import re<br /> >>> match = re.match(&#8216;Hello[ \t]*(.*)world&#8217;, &#8216;Hello Python world&#8217; )<br /> >>> match.group(1)<br /> &#8216;Python&#8217;<br /> >>> match = re.match(&#8216;/(.*)/(.*)/(.*)/&#8217;, &#8216;/usr/lib/bin/&#8217; )<br /> >>> match.groups()<br /> (&#8216;usr&#8217;, &#8216;lib&#8217;, &#8216;bin&#8217; )<br /> </em>Of course you can do more as you know with regular expressions like replacing and splitting, try &#8220;dir&#8221; and &#8220;help&#8221; for more 😉
  </p>
  <h1 style="font-family: Georgia;">
    What Is The Difference Between &#8216;Text&#8217; And &#8220;Text&#8221;?
  </h1>
  <p>
    There is no difference at all, but there is a third way to write strings:<br /> <em>>>> s = &#8220;&#8221;&#8221;Text&#8221;&#8221;&#8221;</em><br /> This way preserves the text formatting, which means you can write:<br /> <em>>>> s = &#8220;&#8221;&#8221;<br /> <html><br /> <head></head><br /> <body><br /> <b>&#8217;I Love &#8220;Python&#8221;&#8216;</b><br /> </body><br /> </html><br /> &#8220;&#8221;&#8221;<br /> >>> s<br /> &#8216;\n<html>\n<head></head>\n<body>\n<b>&#8217;I Love &#8220;Python&#8221;&#8216;</b>\n</body>\n</html>\n&#8217;<br /> </em>You can use this way to write pre-formatted text just like XML and HTML.
  </p>
  <h1 style="font-family: Georgia;">
    Lists And Sequences:
  </h1>
  <p>
    Lists are sequences like strings and they support every thing we talked about when discussed strings methods but the difference is that the results of methods are lists instead of strings, and that lists are changeable objects which means they support changing in place:<br /> <em>>>> L = [123, &#8216;mpcabd&#8217;, 1.23] #lists support multi-types 🙂<br /> >>> len(L)<br /> </em>3<em><br /> >>> L[0]<br /> 123<br /> >>> L[-1]<br /> 1.23<br /> >>> L[:-1]<br /> [123, &#8216;mpcabd&#8217;]<br /> >>> L + [4, 5, 6]<br /> [123, &#8216;mpcabd&#8217;, 1.23, 4, 5, 6]<br /> >>> L<br /> [123, &#8216;mpcabd&#8217;, 1.23]<br /> </em>Lists are so much like arrays but they have no fixed size, so you can append to them and delete from them:<br /> <em>>>> L.append(111)<br /> >>> L<br /> [123, &#8216;mpcabd&#8217;, 1.23, 111]<br /> >>> L.pop(0)<br /> [&#8216;mpcabd, 1.23, 111]<br /> </em>You can even sort and reverse them:<br /> <em>>>> L = [&#8216;a&#8217;, &#8216;z&#8217;, &#8216;c&#8217;]<br /> >>> L.sort()<br /> >>> L<br /> [&#8216;a&#8217;, &#8216;c&#8217;, &#8216;z&#8217;]<br /> >>> L.reverse()<br /> [&#8216;z&#8217;, &#8216;c&#8217;, &#8216;a&#8217;]<br /> </em>To find more try &#8220;dir&#8221; and &#8220;help&#8221; 🙂
  </p>
  <h1 style="font-family: Georgia;">
    What abound boundaries?
  </h1>
  <p>
    Try the following and you&#8217;d see an error:<br /> <em>>>> L = [&#8216;a&#8217;, &#8216;b&#8217;, &#8216;c&#8217;]<br /> >>> L[9]<br /> </em><em>IndexError: list index out of range<br /> </em>This means that Python checks for boundaries not like C and C++.
  </p>
  <h1 style="font-family: Georgia;">
    Can I Nest Lists?
  </h1>
  <p>
    Yes 😀<br /> <em>>>> M = [<br /> [ 1, 2, 3 ], [ 4, 5, 6 ],<br /> [ 7, 8, 9 ] </em>]<em><br /> >>> M<br /> [ [1, 2, 3], [4, 5, 6], [7, 8, 9] ]<br /> >>> M[1] [4, 5, 6]<br /> >>> M[1][2]<br /> </em>6<em><br /> </em>This is a good way to define matrices, but I advise you to use NumPy for mathematical operations, &#8216;cuz it is optimized for fast use.
  </p>
  <h1 style="font-family: Georgia;">
    What Are List Comprehensions?
  </h1>
  <p>
    Python includes along with what we&#8217;ve discussed a powerful methods called &#8220;List Comprehension Expressions&#8221;, suppose we wanna extract the second column of our previous matrix (M), what would you do? Python provides a good way:<br /> <em>>>> col2 = [row[1] for row in M]<br /> >>> col2<br /> [2, 5, 8]<br /> </em>Not good enough? Take this:<br /> <em>>>> [row[1] + 1 for row in M]<br /> [3, 6, 9]<br /> >>> [row[1] for row in M if row[1] % 2 == 0]<br /> [2, 8]<br /> </em>Not enough yet? Take this one and take a nap 🙂<br /> <em>>>> [M[i][i] for i in [0, 1, 2]]<br /> [1, 5, 9]<br /> </em>Not enough? I&#8217;ll kill you then 😈<br /> For more wait for me to study 🙂
  </p>
  <h1 style="font-family: Georgia;">
    Bottom Line:
  </h1>
  <p>
    I&#8217;m sorry I was late this time but I&#8217;m really having a busy phase @ work, please wait for more and don&#8217;t get bored.
  </p>
  <p>
    Cheers.
  </p>
</div>]]></content:encoded>
    </item>
    <item>
      <title>I’m Learning Python part 4</title>
      <link>https://mpcabd.xyz/im-learning-python-part-4/</link>
      <pubDate>Wed, 15 Oct 2008 15:45:55 +0000</pubDate>
      <guid>https://mpcabd.xyz/im-learning-python-part-4/</guid>
      <description>&lt;div dir=&#34;ltr&#34;&gt;
  &lt;div style=&#34;text-align: center;&#34;&gt;
    &lt;h1 style=&#34;font-size: 18pt; font-family: Verdana;&#34;&gt;
      I&amp;#8217;m Learning Python (part 4)
    &lt;/h1&gt;
&lt;pre&gt;&lt;code&gt;&amp;lt;p&amp;gt;
  &amp;lt;img title=&amp;quot;Python Logo&amp;quot; src=&amp;quot;http://www.python.org/images/python-logo.gif&amp;quot; alt=&amp;quot;Python Logo&amp;quot; /&amp;gt;
&amp;lt;/p&amp;gt;
&lt;/code&gt;&lt;/pre&gt;
  &lt;/div&gt;
  &lt;h1 style=&#34;font-family: Georgia;&#34;&gt;
    Why Use Built-In Types?
  &lt;/h1&gt;
  &lt;p&gt;
    Most of the time in programming you&amp;#8217;ll use lists, stacks, arrays, queues and dictionaries, so instead of constructing them, Python gives you a bunch of built-in types to use. The built-in types implement the semantic of the type ADT (Abstract Data Type), and they are fast, &amp;#8216;cuz some of them are written in C and C++.&lt;br /&gt;</description>
      <content:encoded><![CDATA[<div dir="ltr">
  <div style="text-align: center;">
    <h1 style="font-size: 18pt; font-family: Verdana;">
      I&#8217;m Learning Python (part 4)
    </h1>
<pre><code>&lt;p&gt;
  &lt;img title=&quot;Python Logo&quot; src=&quot;http://www.python.org/images/python-logo.gif&quot; alt=&quot;Python Logo&quot; /&gt;
&lt;/p&gt;
</code></pre>
  </div>
  <h1 style="font-family: Georgia;">
    Why Use Built-In Types?
  </h1>
  <p>
    Most of the time in programming you&#8217;ll use lists, stacks, arrays, queues and dictionaries, so instead of constructing them, Python gives you a bunch of built-in types to use. The built-in types implement the semantic of the type ADT (Abstract Data Type), and they are fast, &#8216;cuz some of them are written in C and C++.<br /> 
</p>
  <h1 style="font-family: Georgia;">
    What Core Data Types Does Python Provide?
  </h1>
  <p>
    As in any language, Python provides the usual list of types besides other data types:
  </p>
  <ul>
    <li>
      Numbers: 1234, 3.1415, 999L, 3+4j, Decimal
    </li>
    <li>
      String: &#8216;Some text&#8217;, &#8220;a Text&#8221;
    </li>
    <li>
      Lists: [1, [2, &#8216;Three&#8217;], 4]
    </li>
    <li>
      Dictionaries: {&#8216;food&#8217; : &#8216;Lemon&#8217;, &#8216;taste&#8217; : &#8216;Yummy!&#8217; }
    </li>
    <li>
      Tuples: (1, &#8216;Name&#8217;, 5, &#8216;u&#8217; )
    </li>
    <li>
      Files: myFile = open(&#8216;someFile&#8217;, &#8216;r&#8217; )
    </li>
    <li>
      Other Types: Sets, Types, Boolean, Object, None
    </li>
  </ul>
  <p>
    And don&#8217;t forget that everything is an object at the end 😉<br /> Although Python has no variable declaration – you just assign the value to a variable name and it will be declared automatically -, it keeps track of your variables dynamically, so when you assign a string value to a variable you can use string operations only on it, and so on.<br /> Now let&#8217;s discuss the types in a glance &#8216;cuz we&#8217;ll talk about them in depth later.
  </p>
  <h1 style="font-family: Georgia;">
    Numbers:
  </h1>
  <p>
    Python provides: integers (1234), floating point (3.1415), unlimited precision long (43251278364218357642386321984621734982137469321856412L), complex numbers (4568 + 789j), fixed precision decimals and sets.<br /> Python also provides the simple operations:<br /> + is used for addition, &#8211; for subtraction, * for multiplication, ** for exponents, / for division.<br /> You can calculate whatever you want (2 ** 1000000, but you don&#8217;t wanna print 300000 digit ;)).<br /> When printing numbers there are two methods of printing, the first one is called &#8216;repr&#8217; (object as code) and it prints the number with full precision, the second one is called &#8216;str&#8217; which prints the number in a user-friendly way:<br /> >>> 3.1415000000000002 * 2 <em>#repr</em><br /> 6.2830000000000004<br /> >>> print 3.1415000000000002 * 2 <em>#str</em><br /> 6.283<br /> We&#8217;ll discuss this method later when we introduce classes 🙂<br /> Besides basic operations Python provides a module called &#8216;math&#8217; which has useful methods and variables:<br /> <em>>>> import math<br /> >>> math.pi<br /> 3.1415926535897931<br /> >>> math.sqrt(123)<br /> 11.090536506409418</em><br /> And it also provides a module called &#8216;random&#8217; which generates random numbers:<br /> <em>>>> import random<br /> >>> random.random()<br /> 0.8591504308650737 #You might get another value 😉</em><br /> <em>>>> random.choice([1, 2, 3, 4])<br /> 4 #You might also get another value 😉</em><br /> We&#8217;ll discuss more numbers types soon, but now let&#8217;s move to another type.
  </p>
  <h1 style="font-family: Georgia;">
    Strings:
  </h1>
  <p>
    Strings as you might all now are arrays of characters (in Python we call the array a sequence).<br /> Some of the sequence operations:<br /> <em>>>> s = &#8216;My Text&#8217;<br /> >>> len(s)<br /> </em>7<em><br /> >>> s[0]<br /> &#8216;M&#8217;<br /> >>> s[3]<br /> &#8216;T&#8217;</em><br /> A good indexing way is the negative indexing, which starts from left to right:<br /> <em>>>> s[-1] #Equivalent to s[len(s) – 1]<br /> &#8216;t&#8217;<br /> >>> s[-2] #Equivalent to s[len(s) – 2]<br /> &#8216;x&#8217;</em><br /> Slicing is another way of indexing in sequences, and it is used to extract a portion of the sequence:<br /> <em>>>> s[3:6] #A slice starts from 3 and ends at 5 not 6<br /> &#8216;Tex&#8217;</em><br /> In slicing the left parameter&#8217;s default value is 0, and the right&#8217;s is the length of the sequence, which leads to some other slicing operations:<br /> <em>>>> s[:]<br /> &#8216;My Text&#8217;<br /> >>> s[1:]<br /> &#8216;y Text&#8217;<br /> >>> s[1:len(s)] #Same as s[1:]<br /> &#8216;y Text&#8217;<br /> >>> s #Notice that s hasn&#8217;t changed, we were given new objects.<br /> &#8216;My Text&#8217;<br /> >>>s[:-1] #Everything but the last character 😉<br /> &#8216;My Tex&#8217;</em><br /> As you have noticed we were given new objects, which leads to the fact that slicing using [:] will copy the sequence into another new sequence, which is a great way to copy lists and other sequences.<br /> As sequences, strings support concatenation and repetition:<br /> <em>>>> s + &#8216; Is Beautiful&#8217;<br /> &#8216;My Text Is Beautiful&#8217;<br /> >>> s #s hasn&#8217;t changed<br /> &#8216;My Text&#8217;<br /> >>> s * 5<br /> &#8216; My TextMy TextMy TextMy TextMy Text&#8217;</em><br /> You see, + is used here for concatenation while in numbers it is used for addition, this is called operator overloading in other languages.
  </p>
  <h1 style="font-family: Georgia;">
    Bottom Line:
  </h1>
  <p>
    We&#8217;ll continue talking about types next time, until then create numbers and strings. Try to set a value to specified index of a string, what would you get?<br /> Cheers.
  </p>
</div>]]></content:encoded>
    </item>
    <item>
      <title>I’m Learning Python part 3</title>
      <link>https://mpcabd.xyz/im-learning-python-part-3/</link>
      <pubDate>Fri, 10 Oct 2008 21:16:19 +0000</pubDate>
      <guid>https://mpcabd.xyz/im-learning-python-part-3/</guid>
      <description>&lt;div dir=&#34;ltr&#34;&gt;
  &lt;div style=&#34;text-align: center;&#34; align=&#34;center&#34;&gt;
    &lt;h1 style=&#34;font-size: 18pt; font-family: Verdana;&#34;&gt;
      I&amp;#8217;m Learning Python (part 3)
    &lt;/h1&gt;
&lt;pre&gt;&lt;code&gt;&amp;lt;p&amp;gt;
  &amp;lt;img title=&amp;quot;Python Logo&amp;quot; src=&amp;quot;http://www.python.org/images/python-logo.gif&amp;quot; alt=&amp;quot;Python Logo&amp;quot; /&amp;gt;&amp;lt;/div&amp;gt; 
  
  &amp;lt;h1 style=&amp;quot;font-family: Georgia;&amp;quot;&amp;gt;
    What Is Interactive Mode?
  &amp;lt;/h1&amp;gt;
  
  &amp;lt;p&amp;gt;
    When you install Python on your platform you&amp;amp;#8217;ll find an executable called &amp;amp;#8216;python&amp;amp;#8217;, when you run it you&amp;amp;#8217;ll find a terminal and you&amp;amp;#8217;ll see something like the following:&amp;lt;br /&amp;gt; &amp;lt;em&amp;gt;Python 2.6 (r26:66721, Oct 2 2008, 11:35:03) [MSC v.1500 32 bit (Intel)] on win32&amp;lt;br /&amp;gt; Type &amp;amp;#8220;help&amp;amp;#8221;, &amp;amp;#8220;copyright&amp;amp;#8221;, &amp;amp;#8220;credits&amp;amp;#8221; or &amp;amp;#8220;license&amp;amp;#8221; for more information.&amp;lt;br /&amp;gt; &amp;gt;&amp;gt;&amp;gt;&amp;lt;/em&amp;gt;&amp;lt;br /&amp;gt; This is called interactive coding (or interactive mode), here you can write Python statements and the interpreter will execute them directly, let&amp;amp;#8217;s try:&amp;lt;br /&amp;gt; &amp;lt;em&amp;gt;&amp;gt;&amp;gt;&amp;gt; print &amp;amp;#8220;I Love Python&amp;amp;#8221;&amp;lt;br /&amp;gt; I Love Python&amp;lt;br /&amp;gt; &amp;gt;&amp;gt;&amp;gt; print 2 ** 10&amp;lt;br /&amp;gt; 1024&amp;lt;br /&amp;gt; &amp;gt;&amp;gt;&amp;gt;&amp;lt;/em&amp;gt;&amp;lt;br /&amp;gt; 
&lt;/code&gt;&lt;/pre&gt;</description>
      <content:encoded><![CDATA[<div dir="ltr">
  <div style="text-align: center;" align="center">
    <h1 style="font-size: 18pt; font-family: Verdana;">
      I&#8217;m Learning Python (part 3)
    </h1>
<pre><code>&lt;p&gt;
  &lt;img title=&quot;Python Logo&quot; src=&quot;http://www.python.org/images/python-logo.gif&quot; alt=&quot;Python Logo&quot; /&gt;&lt;/div&gt; 
  
  &lt;h1 style=&quot;font-family: Georgia;&quot;&gt;
    What Is Interactive Mode?
  &lt;/h1&gt;
  
  &lt;p&gt;
    When you install Python on your platform you&amp;#8217;ll find an executable called &amp;#8216;python&amp;#8217;, when you run it you&amp;#8217;ll find a terminal and you&amp;#8217;ll see something like the following:&lt;br /&gt; &lt;em&gt;Python 2.6 (r26:66721, Oct 2 2008, 11:35:03) [MSC v.1500 32 bit (Intel)] on win32&lt;br /&gt; Type &amp;#8220;help&amp;#8221;, &amp;#8220;copyright&amp;#8221;, &amp;#8220;credits&amp;#8221; or &amp;#8220;license&amp;#8221; for more information.&lt;br /&gt; &gt;&gt;&gt;&lt;/em&gt;&lt;br /&gt; This is called interactive coding (or interactive mode), here you can write Python statements and the interpreter will execute them directly, let&amp;#8217;s try:&lt;br /&gt; &lt;em&gt;&gt;&gt;&gt; print &amp;#8220;I Love Python&amp;#8221;&lt;br /&gt; I Love Python&lt;br /&gt; &gt;&gt;&gt; print 2 ** 10&lt;br /&gt; 1024&lt;br /&gt; &gt;&gt;&gt;&lt;/em&gt;&lt;br /&gt; 
</code></pre>
<p><br /> You can write any statement here (even those who are more than on line as we’ll see later).<br /> If you remember we said that the Python compiler and interpreter are always in present at runtime, so that’s why you can execute the statements directly here. Another benefit you get from the presence of the compiler and interpreter at runtime that you can let your program execute Python code written by the user, and that’s what some programs do, they let the user manipulate the program’s behavior by writing his/her code inside the program.<br /> To do so you can run the “exec” statement like this:<br /> <em>&raquo;&gt; exec “print &amp;#8221;I Love Python&amp;#8221;”<br /> I Love Python<br /> &raquo;&gt;</em><br /> Here we invoked a method called “exec” and it takes a string parameter, this string contains Python code, and the interpreter will run it, so you can simply read code from the user and run it for him/her. This method is available anywhere (not just in the interactive mode).<br /> You must have noticed using the escape character &amp;#8221; in the text, and that is to tell the interpreter that this is not the end of the string and it is a double quotation inside the string, there are more escape characters that we’ll find more in the upcoming parts.<br /> Another feature to talk about in the interactive mode that you don’t have to write print every time, so the next statement will run without errors:<br /> <em>&raquo;&gt; “I Love Python”<br /> ‘I Love Python’<br /> &raquo;&gt;</em><br /> But beware, you <strong>must</strong> use print in any other mode, interactive mode is the only mode which doesn’t need the print statement, that’s ‘cuz it is made to print the results.<br /> You might ask, what about statements that don’t return values, what would the interactive mode print for them? The answer is: simply nothing 🙂<br /> <em>&raquo;&gt; text = “I Love Python”<br /> &raquo;&gt;</em><br /> The previous statement is an assignment statement, which declares a string called “text” and has the value of “I Love Python”.<br /> To exit the interactive code you use the break character (Ctrl+Z in Windows, Ctrl+D in Linux) and hit return.
</p></p>
<pre><code>  &lt;h1 style=&quot;font-family: Georgia;&quot;&gt;
    What Are Modules?
  &lt;/h1&gt;
  
  &lt;p&gt;
    Let&amp;#8217;s here explain the Python program hierarchy:&lt;br /&gt; Each program consists of modules -&gt; Each module consists of statements -&gt; Each statement consists of expressions -&gt; Each expression creates and processes objects -&gt; Objects are the raw materials you&amp;#8217;ll use 🙂&lt;br /&gt; When you write a Python program you write it in files, these files usually called modules, the module is a namespace, so each module has its own variables and methods. You can have two variables with the same name, but you must put each one in a module.&lt;br /&gt; We&amp;#8217;ll use modules (for now) to run our code multiple times without the need of re-typing it again.&lt;br /&gt; You can access another module using &amp;#8220;import&amp;#8221; statement, so let&amp;#8217;s try something:
  &lt;/p&gt;
  
  &lt;ul&gt;
    &lt;li&gt;
      Open your editor and write the following in it:&lt;br /&gt; text = &amp;#8220;I Love Python&amp;#8221;&lt;br /&gt; print text
    &lt;/li&gt;
    &lt;li&gt;
      Save the file somewhere with the name &amp;#8220;module1.py&amp;#8221;
    &lt;/li&gt;
    &lt;li&gt;
      Now start a new file and write the following in it:&lt;br /&gt; import module1&lt;br /&gt; module1.text = &amp;#8220;You Know I Love Python&amp;#8221;&lt;br /&gt; print module1.text
    &lt;/li&gt;
    &lt;li&gt;
      Save the file in the same folder which has &amp;#8220;module1.py&amp;#8221; with the name &amp;#8220;module2.py&amp;#8221;
    &lt;/li&gt;
    &lt;li&gt;
      Now let the Python interpreter run your module2 file:&lt;br /&gt; python [SOME FOLDER]/module2.py
    &lt;/li&gt;
    &lt;li&gt;
      You must see the following:&lt;br /&gt; I Love Python&lt;br /&gt; You Know I Love Python
    &lt;/li&gt;
  &lt;/ul&gt;
  
  &lt;p&gt;
    What happened here? In module2 I only printed the variable after editing it, why was it printed before it was edited?&lt;br /&gt; When you import a module, you&amp;#8217;re simply running it, so the Python interpreter ran module1, and executed the print statement so you see &amp;#8220;I Love Python&amp;#8221;, then it executed module2, it edited the value of the variable in module1, then executed the print statement in module2, and you see &amp;#8220;You Know I Love Python&amp;#8221;.&lt;br /&gt; So importing means running, but what if I needed to run the code again? Knowing that you can&amp;#8217;t import a module more than one, what should we do?&lt;br /&gt; There is another statement &amp;#8220;reload&amp;#8221; which is a method and takes a string with the name of the module to re-run it again, but it should be imported before.&lt;br /&gt; Try adding this line to your code in module2.py:&lt;br /&gt; reload(module1)&lt;br /&gt; Re-run your module2 and you must see:&lt;br /&gt; I Love Python&lt;br /&gt; You Know I Love Python&lt;br /&gt; I Love Python&lt;br /&gt; The third line is actually the print statement in module1 file.
  &lt;/p&gt;
  
  &lt;h1 style=&quot;font-family: Georgia;&quot;&gt;
    What Is The Difference Between &amp;#8220;import [MODULE]&amp;#8221; And &amp;#8220;from [MODULE] import&amp;#8221;?
  &lt;/h1&gt;
  
  &lt;p&gt;
    The first – import [MODULE] – imports and runs the module, but when you want to access its variables you should write: [MODULE].[VARIABLE], so each time you want to use the variable you should write the module&amp;#8217;s name followed by a period before the variable&amp;#8217;s name.&lt;br /&gt; The second – from [MODULE] import – imports the specified variables from the module, so to import the &amp;#8220;text&amp;#8221; variable from &amp;#8220;module1&amp;#8221; in the previous example you write:&lt;br /&gt; from module1 import text&lt;br /&gt; To import more than one variable separate them with columns:&lt;br /&gt; from [MODULE] impor [VAR1], [VAR2], …, [VARN]&lt;br /&gt; Notice that importing a variable lets you use the variable without the need to write the module&amp;#8217;s name before it, you can simply use the &amp;#8220;text&amp;#8221; variable in module2 after importing it without writing module1.text.&lt;br /&gt; Beware that importing a variable that has the same name of a local variable will replace the local one, for instance:&lt;br /&gt; in module1.py write:&lt;br /&gt; text = &amp;#8220;I Love Python&amp;#8221;&lt;br /&gt; in module2.py write:&lt;br /&gt; text = &amp;#8220;You Know I Love Python&amp;#8221;&lt;br /&gt; from module1 import text&lt;br /&gt; print text
  &lt;/p&gt;
  
  &lt;p&gt;
    Executing module2 will give you: I Love Python.
  &lt;/p&gt;
  
  &lt;h1 style=&quot;font-family: Georgia;&quot;&gt;
    How can I write hints and comments in Python?
  &lt;/h1&gt;
  
  &lt;p&gt;
    Using the sharp &amp;#8211; # &amp;#8211; character will hint the following text until the end of the line:&lt;br /&gt; text = &amp;#8220;I Love Python&amp;#8221; &lt;em&gt;#a declaration of a variable named text&lt;/em&gt;
  &lt;/p&gt;
  
  &lt;h1 style=&quot;font-family: Georgia;&quot;&gt;
    Bottom Line:
  &lt;/h1&gt;
  
  &lt;p&gt;
    Next time we&amp;#8217;ll learn about built-in types in Python, till then try to create and import and print modules and variables, try that in both files and interactive mode, try to make syntax errors, try to divide by zero.
  &lt;/p&gt;
  
  &lt;p&gt;
    Cheers.
  &lt;/p&gt;&lt;/div&gt;
</code></pre>]]></content:encoded>
    </item>
    <item>
      <title>I’m Learning Python part 2</title>
      <link>https://mpcabd.xyz/i%E2%80%99m-learning-python-part-2/</link>
      <pubDate>Tue, 07 Oct 2008 07:02:03 +0000</pubDate>
      <guid>https://mpcabd.xyz/i%E2%80%99m-learning-python-part-2/</guid>
      <description>&lt;div dir=&#34;ltr&#34;&gt;
  &lt;div style=&#34;text-align: center;&#34;&gt;
    &lt;p&gt;
      &lt;span style=&#34;font-size: large; font-family: georgia,palatino;&#34;&gt;I&amp;#8217;m Learning Python (part 2)&lt;/span&gt;
    &lt;/p&gt;
&lt;pre&gt;&lt;code&gt;&amp;lt;p&amp;gt;
  &amp;lt;img title=&amp;quot;Python Logo&amp;quot; src=&amp;quot;http://www.python.org/images/python-logo.gif&amp;quot; alt=&amp;quot;Python Logo&amp;quot; /&amp;gt;
&amp;lt;/p&amp;gt;
&lt;/code&gt;&lt;/pre&gt;
  &lt;/div&gt;
  &lt;h1 style=&#34;font-family: Georgia;&#34;&gt;
    Who Uses Python?
  &lt;/h1&gt;
  &lt;p&gt;
    In the world there are more than 1 million Python user, that&amp;#8217;s because it&amp;#8217;s&lt;br /&gt; open source, and because it is implemented for every platform, and it comes&lt;br /&gt; included within Linux distributions and Macintosh computers and more.
  &lt;/p&gt;
  &lt;ol&gt;
    &lt;li&gt;
      Google uses Python in its web search system, and it employs the Python&amp;#8217;s&lt;br /&gt; creator.
    &lt;/li&gt;
    &lt;li&gt;
      YouTube is largely written in Python.
    &lt;/li&gt;
    &lt;li&gt;
      BitTorrent file sharing system is a Python program.
    &lt;/li&gt;
    &lt;li&gt;
      Intel, Cisco, HP, Seagate, Qualcomm and IB&lt; use Python for hardware&lt;br /&gt; testing.
    &lt;/li&gt;
    &lt;li&gt;
      Industrial Light &amp; Magic, Pixar, and others use Python in the production&lt;br /&gt; of movie animation.
    &lt;/li&gt;
    &lt;li&gt;
      NASA, Los Alamos, Fermilab, JPL, and others use Python for scientific&lt;br /&gt; programming.
    &lt;/li&gt;
    &lt;li&gt;
      iRobot uses Python to develop commercial robotic vacuum cleaners 🙂
    &lt;/li&gt;
    &lt;li&gt;
      NSA uses Python for cryptography and intelligence analysis.
    &lt;/li&gt;
  &lt;/ol&gt;
  &lt;p&gt;
    See Python website for more.&lt;br /&gt;</description>
      <content:encoded><![CDATA[<div dir="ltr">
  <div style="text-align: center;">
    <p>
      <span style="font-size: large; font-family: georgia,palatino;">I&#8217;m Learning Python (part 2)</span>
    </p>
<pre><code>&lt;p&gt;
  &lt;img title=&quot;Python Logo&quot; src=&quot;http://www.python.org/images/python-logo.gif&quot; alt=&quot;Python Logo&quot; /&gt;
&lt;/p&gt;
</code></pre>
  </div>
  <h1 style="font-family: Georgia;">
    Who Uses Python?
  </h1>
  <p>
    In the world there are more than 1 million Python user, that&#8217;s because it&#8217;s<br /> open source, and because it is implemented for every platform, and it comes<br /> included within Linux distributions and Macintosh computers and more.
  </p>
  <ol>
    <li>
      Google uses Python in its web search system, and it employs the Python&#8217;s<br /> creator.
    </li>
    <li>
      YouTube is largely written in Python.
    </li>
    <li>
      BitTorrent file sharing system is a Python program.
    </li>
    <li>
      Intel, Cisco, HP, Seagate, Qualcomm and IB< use Python for hardware<br /> testing.
    </li>
    <li>
      Industrial Light & Magic, Pixar, and others use Python in the production<br /> of movie animation.
    </li>
    <li>
      NASA, Los Alamos, Fermilab, JPL, and others use Python for scientific<br /> programming.
    </li>
    <li>
      iRobot uses Python to develop commercial robotic vacuum cleaners 🙂
    </li>
    <li>
      NSA uses Python for cryptography and intelligence analysis.
    </li>
  </ol>
  <p>
    See Python website for more.<br /> 
</p>
  <h1 style="font-family: Georgia;">
    How Does Python work?
  </h1>
  <p>
    Python is not compiled (almost), it is interpreted. So when you run the program<br /> the interpreter will run it line by line without compilation.
  </p>
  <p>
    You might say &#8220;Why did you say almost?&#8221;, the answer is, Python as described<br /> before can be compiled into byte code, so it&#8217;ll be faster for the interpreter<br /> to execute it than the source code, just like Java&#8217;s byte code and .NET&#8217;s MSIL.
  </p>
  <p>
    Python files have a .py extension normally, so when you write Python code you<br /> should save it with a .py extension.
  </p>
  <p>
    Let&#8217;s try and write our first Hello World Python program:
  </p>
  <ol>
    <li>
      Open the editor you use (Emacs, Notepad, Notepad++, …).
    </li>
    <li>
      Write this line inside it:
    </li>
    <li>
      print &#8220;Hello World, It&#8217;s My First Python Program&#8221;
    </li>
    <li>
      Save the file as .py file.
    </li>
    <li>
      Now you should tell the Python interpreter to run your file, depending<br /> on your platform you should have the Python interpreter in (&#8220;<em>C:\Python[VER]\</em>&#8221;<br /> in Windows where [VER] is the version of the Python release you have [24,<br /> 25, 26,…]) or in (&#8220;<em>/usr/bin/</em>&#8221; in Linux).
    </li>
    <li>
      In Windows open a command prompt and guide it to the location of your<br /> Python.
    </li>
    <li>
      In Linux open a terminal and go to the location of your Python interpreter.
    </li>
    <li>
      Now you can execute the following command on both platforms:<em>python [FILE]</em>Where [File] is the location of your .py file.
    </li>
    <li>
      Now you should see some thing like this:<em>python [FILE]</em>Hello World, It&#8217;s My First Python Program
    </li>
  </ol>
  <p>
    Very easy, right?
  </p>
  <p>
    Although it is not that big program but you can run your files this way :).
  </p>
  <p>
    Now let&#8217;s understand what happened:
  </p>
  <p>
    The Python interpreter was given a file to run.
  </p>
  <p>
    If it has write privileges it&#8217;ll compile it into byte code and you&#8217;ll see that<br /> a new file was created next to your file with a .pyc extension, if it doesn&#8217;t<br /> it&#8217;ll run it as source code.
  </p>
  <p>
    It reads the first line (which is a print statement) and runs it and you see<br /> the result, the execution takes place inside the PVM – Python Virtual Machine,<br /> which handles the execution of Python byte code and source code to run on more<br /> than one platform without change in code.
  </p>
  <div style="text-align: center;">
    <img src="http://i146.photobucket.com/albums/r257/mpcabd/ILP/ILP2-01.gif" alt="" />
  </div>
  <p>
    If you have a background in C or C++ you might find a change in the way of running<br /> and compiling code, &#8216;cuz there is no making and linking in Python, and it is<br /> not compiled into machine code (binary file), instead it runs inside a virtual<br /> machine, that&#8217;s why some Python code will run faster in C++ and C.
  </p>
  <p>
    But don&#8217;t be afraid, 90% of the time you&#8217;ll be running your programs as if they<br /> were written in C or C++, there won&#8217;t be any difference in the time of execution,<br /> and that’s because of the Python simplicity which makes the program in Python<br /> shorter and simpler than C or C++, and because it&#8217;s optimization which we&#8217;ll<br /> describe later.
  </p>
  <p>
    In Python you&#8217;ll notice that the compiler and the execution environment are<br /> one thing, the compiler always present in runtime, and that leads to rapid development<br /> cycle, with no linking and making stage.
  </p>
  <p>
    CPython runs inside the PVM, while Jython runs inside the JVM and IronPython<br /> .NET runs inside .NET Framework or Mono.
  </p>
  <p>
    Jython and IronPython .NET allows the Python program to use Java and .NET classes<br /> respectively.
  </p>
  <p>
    If you don&#8217;t wanna use Java or .NET classes you should use CPython, &#8216;cuz it&#8217;s<br /> faster and the most complete, CPython runs like C and C++ so it is the fastest.
  </p>
  <p>
    In Jython the Python byte code is translated into Java byte code to be run inside<br /> the JVM, while in .NET it is translated to MSIL.
  </p>
  <h1 style="font-family: Georgia;">
    What Are The Frozen Binaries?
  </h1>
  <p>
    Python has something called Frozen Binaries, which are the executables, if you<br /> chose to create a frozen binary for your program, you&#8217;d end up with an executable<br /> that runs on a specified platform (exe for Windows).
  </p>
  <p>
    This executable has a great feature; it includes your program along with its<br /> dependencies and the Python interpreter. Yes you don&#8217;t have to tell the user<br /> to install a Python interpreter to be able to use your program, he/she doesn&#8217;t<br /> have to know that your program is a Python program.
  </p>
  <p>
    You can use Py2Exe to get an exe of your program (Which runs only in Windows),<br /> or PyInstaller which gives you the ability to create a frozen binary for Windows,<br /> Linux or UNIX. And you can use Freeze the original one. Those are available<br /> free of charge, you can check Python website or Vaults of Parnassus (http://www.vex.net/parnassus).
  </p>
  <h1 style="font-family: Georgia;">
    What IDE&#8217;s To Use With Python?
  </h1>
  <p>
    Python comes with a simple IDE called IDLE you can use it, or you can use Emacs, but IMHO<br /> Eclipse with PyDev make a great IDE for you and Python.
  </p>
  <h1 style="font-family: Georgia;">
    Bottom Line:
  </h1>
  <p>
    Today it was just a description on how Python runs your program, and we wrote<br /> our Hello World program.
  </p>
  <p>
    For the next part, try to use the ** operator &#8211; which is the power operator<br /> in Python – to see how much you can do in Python, e.g.:
  </p>
  <p>
    print 2 ** 10
  </p>
  <p>
    1024
  </p>
  <p>
    Try huge numbers and see 😉
  </p>
  <p>
    Cheers.
  </p>
</div>]]></content:encoded>
    </item>
    <item>
      <title>I’m Learning Python part 1</title>
      <link>https://mpcabd.xyz/im-learning-python-part-1/</link>
      <pubDate>Sat, 04 Oct 2008 20:25:51 +0000</pubDate>
      <guid>https://mpcabd.xyz/im-learning-python-part-1/</guid>
      <description>&lt;div style=&#34;text-align: center;&#34;&gt;
  &lt;span style=&#34;font-family: georgia,palatino; font-size: large;&#34;&gt; I&amp;#8217;m Learning Python &lt;/span&gt;&lt;br /&gt; &lt;img title=&#34;Python Logo&#34; src=&#34;http://www.python.org/images/python-logo.gif&#34; alt=&#34;Python Logo&#34; width=&#34;211&#34; height=&#34;71&#34; border=&#34;0&#34; /&gt;
&lt;/div&gt;
&lt;p&gt;I’ll start posting this series of blogs on &lt;a title=&#34;Magic PC On WordPress&#34; href=&#34;http://magicpc.wordpress.com&#34; target=&#34;_blank&#34;&gt;WordPress&lt;/a&gt; and &lt;a title=&#34;mpcabd&#39;s Bolg On CSC&#34; href=&#34;https://mpcabd.xyz/blog/2300&#34; target=&#34;_blank&#34;&gt;CSC&lt;/a&gt;, here I’ll write what I’m gonna learn on my way to learning Python.&lt;/p&gt;
&lt;p&gt;If you don’t know what Python is, or you’ve heard about it but you’re not sure what it is, my first blog will cover it for you.&lt;/p&gt;</description>
      <content:encoded><![CDATA[<div style="text-align: center;">
  <span style="font-family: georgia,palatino; font-size: large;"> I&#8217;m Learning Python </span><br /> <img title="Python Logo" src="http://www.python.org/images/python-logo.gif" alt="Python Logo" width="211" height="71" border="0" />
</div>
<p>I’ll start posting this series of blogs on <a title="Magic PC On WordPress" href="http://magicpc.wordpress.com" target="_blank">WordPress</a> and <a title="mpcabd's Bolg On CSC" href="/blog/2300" target="_blank">CSC</a>, here I’ll write what I’m gonna learn on my way to learning Python.</p>
<p>If you don’t know what Python is, or you’ve heard about it but you’re not sure what it is, my first blog will cover it for you.</p>
<h1 id="what-is-python"><span style="font-family: georgia,palatino;">What is Python? </span></h1>
<p>Python is a <a href="http://en.wikipedia.org/wiki/Programming_Language" target="_blank">programming language</a>, this programming language was created in 1990, this programming language has proved its power through the last 18 years she’s been with us.</p>
<h1 id="why-should-i-be-interested-in-learning-a-new-language"><span style="font-family: georgia,palatino;">Why should I be interested in learning a new language? </span></h1>
<p>The most points that will catch your interest in this language are:</p>
<ul>
<li>
<p>It’s <a href="http://en.wikipedia.org/wiki/Object-oriented_programming" target="_blank">Object Oriented</a>:</p>
<p>Python supports classes, inheritance, multiple inheritance, polymorphism, operator overloading and more.</p>
<p>Python is OOP from ground up, besides it’s like C++ supports both object oriented and procedural programming, so it may be used for scripting applications.</p>
</li>
<li>
<p>It’s <a href="http://en.wikipedia.org/wiki/Free_Software" target="_blank">Free</a>:</p>
<p>Python is completely free to use and redistribute, it is also widely supported through web portals where millions of users world-wide can help you find solutions for your problems.</p>
</li>
<li>
<p>It’s <a href="http://en.wikipedia.org/wiki/Cross_platform" target="_blank">Portable</a>:</p>
<p>Python first was written in C, and because of that it can be run on almost every platform, you can run it on (Windows, Linux, Mac OS, BeOS, PDAs, Cell Phones, Gaming Consoles, …).</p>
<p>Everything is portable, that’s because Python code is compiled into <a href="http://en.wikipedia.org/wiki/Bytecode" target="_blank">byte-code</a> (Like .NET and Java), and so it can be run on any platform with a Python interpreter.</p>
</li>
<li>
<p>It’s Powerful:</p>
<p>Python sits on the chair along with Perl, Tcl and Scheme as a powerful scripting language, while also it sits on the chair with Java and .NET as a powerful Pure OOP language, and of course it shares the chair with C and C++ as a powerful programming language that is capable of doing everything.</p>
<p>While sitting on more than one chair at the same time, Python provides the simplicity in writing a fully readable code.</p>
<p>From its most powerful features I’ll write some and I’ll explain them deeply when I understand them 😀</p></p>
<ol>
<li>Dynamic Typing.</li>
<li>Automatic Memory Management:</li>
</ol>
<pre><code>This one I already know from .NET, Python has its own garbage collector which runs automatically and deallocates space from unused objects in the memory.
</code></pre>
<ol start="3">
<li>Programming for large systems using OOP allows you to develop components and systems so you can reuse them in most of your applications.</li>
<li>Built-in tools used for manipulating built-in types such as lists and collections.</li>
<li>Libraries from regular expressions to networking, all libraries can be used easily.</li>
<li>Third-party utilities: since Python is open source developers from around the globe can build their tools and libraries and everybody can use them.</li>
</ol>
</li>
<li>
<p>It’s Mixable:</p>
<p>You can use Python and call your programs and methods from inside C and C++ and even Java and .NET, you can also call C and C++ methods and tools from Python along with Java and .NET.</p>
</li>
<li>
<p>It’s easy to use and learn:</p>
<p>You’ll notice just like I have that Python is an easy yet powerful language which can be used in every technical field without losing it simplicity.</p>
</li>
</ul>
<h1 id="what-can-i-do-with-python"><span style="font-family: georgia,palatino;">What can I do with Python? </span></h1>
<p>Here I’ll tell you what fields you can use Python in, but in a glance ‘cuz I don’t know how to use it yet.</p>
<ul>
<li>
<p>System Programming:</p>
<p>Because it can be used as scripting language, Python can be used to develop shell tools, which can communicate with system shell and provide a layer for you to search files and folders, launch applications and even do parallel processing using processes and threads.</p>
</li>
<li>
<p>GUIs:</p>
<p>Using Tk GUI, Qt, GTK, MFC and Swing you can make your application have a GUI, but not any GUI, your GUI is cross-platform and you’d be able to run your application on any platform.</p>
</li>
<li>
<p>Internet Scripting:</p>
<p>You can develop web applications using Python, you can do Server scripting, Server-Client Scripting and Client Scripting.</p>
<p>A lot of websites already use Python now.</p>
<p>You can use FTP to transfer files, parse XML files, parse HTML and you can generate HTML based on Python code.</p>
</li>
<li>
<p>Gluing:</p>
<p>Python can be glued to C, C++, .NET and Java applications.</p>
<p>Python now has 3 major implementations: CPython which is the base implementation, Jython which can be run inside the JVM (Java Virtual Machine), and IronPython .NET which can be run inside .NET Framework.</p>
</li>
<li>
<p>Database Applications:</p>
<p>Python can use Sybase, Oracle, Informix, ODBC, MySql, PostgreSQL, SQLite and more.</p>
<p>Python even has a built in database API which can be used with any database system, you can easily change it from anyone to anyone by just switching the used interface.</p>
</li>
<li>
<p>Numeric and Scientific Programming:</p>
<p>Python can be used easily to create scientific applications, there is an extension called NumPy which can do more than Matlab!</p>
<p>You can calculate 2<sup>2000</sup> in milliseconds:</p>
<p>114813069527425452423283320117768198402231770208869</p>
<p>520047764273682576626139237031385665948631650626991</p>
<p>844596463898746277344711896086305533142593135616665</p>
<p>318539129989145312280000688779148240044871428926990</p>
<p>063486244781615463646388363947317026040466353970904</p>
<p>996558162398808944629605623311649536164221970332681</p>
<p>344168908984458505602379484807914058900934776500429</p>
<p>002716706625830522008132236281291761267883317206598</p>
<p>995396418127021779858404042159853183251540889433902</p>
<p>091920554957783589672039160081957216630582755380425</p>
<p>583726015528348786419432054508915275783882625175435</p>
<p>528800822842770817965453762184851149029376.</p>
<p>You don’t have to wait to get this value 😀</p>
</li>
<li>
<p>More:</p>
<p>Python can be used in more fields, XML, Gaming, Graphics, Robots, Networking and more, everything is possible 🙂</p>
</li>
</ul>
<h1 id="bottom-line"><span style="font-family: georgia,palatino;">Bottom Line: </span></h1>
<p>That’s enough for today, hope I’ll tell you more on my next blog.</p>
<p>For now I’d suggest you to read more about the language and its features from the language website: <a href="https://www.Python.org">www.Python.org</a>.</p>
<p>And also don’t forget to download the appropriate built for your platform.</p>
<p>Cheers.</p>]]></content:encoded>
    </item>
    <item>
      <title>Your drawings are Objects in GDI&#43;</title>
      <link>https://mpcabd.xyz/your-drawings-are-objects-in-gdi/</link>
      <pubDate>Tue, 12 Jun 2007 16:43:16 +0000</pubDate>
      <guid>https://mpcabd.xyz/your-drawings-are-objects-in-gdi/</guid>
      <description>&lt;p&gt;Hi all .Net developers and programmers.&lt;/p&gt;
&lt;p&gt;If you’re a .Net developer or a programmer you must have heard of the Drawing namespace in System namespace, and you maybe used it to draw in your applications.&lt;/p&gt;
&lt;p&gt;For those who used them they must have found that moving a single shape in a scene using simple code is not that easy, you’ll have to redraw the whole scene with the shape in its new location, the same thing happens for rotating and scaling a shape, so I had an idea, “Why can’t we just write Rectangle.Move(X,Y) and it moves? Why should I remember every shape coordinates to redraw a small shape in a new position?” so I answered the question.&lt;/p&gt;</description>
      <content:encoded><![CDATA[<p>Hi all .Net developers and programmers.</p>
<p>If you’re a .Net developer or a programmer you must have heard of the Drawing namespace in System namespace, and you maybe used it to draw in your applications.</p>
<p>For those who used them they must have found that moving a single shape in a scene using simple code is not that easy, you’ll have to redraw the whole scene with the shape in its new location, the same thing happens for rotating and scaling a shape, so I had an idea, “Why can’t we just write Rectangle.Move(X,Y) and it moves? Why should I remember every shape coordinates to redraw a small shape in a new position?” so I answered the question.</p>
<p>I developed a small class that lets you manipulate your drawings as Objects, I mean that you can define a rectangle and just write Rectangle.Move(x,y) and it’ll move to the given position without much hard-coding, I defined (Rectangle, Ellipse, Lines), but you can also define your own shape, you just have to inherit the base class (MagicGraphics.Shape) and you’ll have to write your own Render sub (void) and ToString function, and you can add as much as you want of properties.</p>
<p dir="ltr">
  All the shapes you draw must be placed in a ShapeContainer that handles the drawing according to the Z-Order between shapes.
</p>
<p dir="ltr">
  The following links are for the class and the testing project in VB .Net 2005:
</p>
<p dir="ltr">
  <a target="_blank" href="http://www.savefile.com/files/757490" title="http://www.savefile.com/files/757490">The Class</a> &#8211;    <a target="_blank" href="http://www.savefile.com/files/757502" title="http://www.savefile.com/files/757502">The Testing Project.</a>
</p>
<p dir="ltr">
  The testing project shows how to draw, rotate and move shapes, you can start using my class directly after downloading it.
</p>
<p dir="ltr">
  P.S.: The whole project is still Beta but I wanted to share the first build with you.
</p>
<p dir="ltr">
  Have fun, and please tell me what do you think.
</p>]]></content:encoded>
    </item>
  </channel>
</rss>
