<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[Stories by Rajguleria on Medium]]></title>
        <description><![CDATA[Stories by Rajguleria on Medium]]></description>
        <link>https://medium.com/@rajguleria3?source=rss-c8873afac1d4------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/0*xtOqgFGjeKTlSepY</url>
            <title>Stories by Rajguleria on Medium</title>
            <link>https://medium.com/@rajguleria3?source=rss-c8873afac1d4------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Fri, 27 Nov 2026 20:15:07 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@rajguleria3/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[“Turned Department Of Justice Into Department Of Injustice”: Trump Jabs Biden]]></title>
            <link>https://medium.com/@rajguleria3/turned-department-of-justice-into-department-of-injustice-trump-jabs-biden-47898d2113b4?source=rss-c8873afac1d4------2</link>
            <guid isPermaLink="false">https://medium.com/p/47898d2113b4</guid>
            <category><![CDATA[trump]]></category>
            <category><![CDATA[donald-trump]]></category>
            <category><![CDATA[biden]]></category>
            <dc:creator><![CDATA[Rajguleria]]></dc:creator>
            <pubDate>Sat, 15 Mar 2025 08:19:59 GMT</pubDate>
            <atom:updated>2025-03-15T08:19:59.115Z</atom:updated>
            <content:encoded><![CDATA[<h4>Donald Trump has made attacks on the US media a central part of his message ever since his first election to the presidency in 2016.</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/773/0*_kgBzbt_rJCQrqsL" /></figure><p>Since returning to office Trump has taken a sledgehammer to the Justice Department.</p><p><strong>Washington, United States: </strong>US President Donald Trump launched a bitter attack against the “illegal” media and his political enemies Friday, as a speech at the Department of Justice turned into a grievance-filled diatribe.</p><p>Trump — the first convicted felon to sit in the White House — was meant to be talking about law and order at an organization supposed to be insulated from political pressure. But instead the 78-year-old Republican spent much of his time rehearsing complaints that predecessor Joe Biden had “weaponized” the department against him and pledging to “expose” his foes.</p><p>“Our predecessors turned the Department of Justice into the Department of Injustice,” Trump said. “I stand before you today to declare that those days are over, and they are never going to come back.”</p><p>Since returning to office Trump has taken a sledgehammer to the Justice Department, which previously brought two criminal cases against him including one for allegedly trying to overturn the result of the 2020 election.</p><p>But in his speech he vowed to go a step further and investigate his foes, saying: “We must be honest about the lies and abuses that have occurred within these walls.”</p><p>He said his administration would “expel the rogue actors and corrupt forces from our government, we will… very much expose their egregious crimes and severe misconduct.”</p><p>Trump reserved special ire for US media outlets which cover him critically.</p><p>Speaking to an audience of prosecutors and law enforcement agents, Trump said broadcasters CNN and MSNBC and unidentified newspapers “literally write 97.6 percent bad about me” and “it has to stop. It has to be illegal.”</p><p>He described the media outlets as “political arms of the Democrat party. And in my opinion they’re really corrupt and they’re illegal. What they do is illegal.”</p><h3>‘Fake news’</h3><p>Trump has made attacks on the US media a central part of his message ever since his first election to the presidency in 2016 — describing them as “enemies of the people” and “fake news.”</p><p>Since starting his second term in January, Trump has moved quickly to pressure mainstream media like The Associated Press while boosting access to the White House for formerly fringe right-wing outlets.</p><p>Trump’s extraordinary speech stepped up his breaking of decades-old political norms aimed at preserving judicial independence from the White House.</p><p>Trump pledged on the campaign trail in the 2024 election to overhaul the department if he won a second term.</p><p>He had it in his sights ever since Special Counsel Jack Smith charged him with plotting to overturn the results of the 2020 election, which he still refuses to admit he lost, and illegally taking thousands of secret documents with him on leaving the White House in 2021.</p><p>But neither case came to trial and the special counsel, in line with a Justice Department policy of not prosecuting a sitting president, dropped them both after Trump won the November presidential election.</p><p>Trump rocked the department on his first day back in office by pardoning more than 1,500 supporters who, in an unprecedented act of US political violence, stormed the Capitol on January 6, 2021, seeking to interrupt certification of Biden’s election win.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=47898d2113b4" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[After Trump Request, Putin Says He Will “Spare” Ukraine Troops If They…]]></title>
            <link>https://medium.com/@rajguleria3/after-trump-request-putin-says-he-will-spare-ukraine-troops-if-they-a8accc02e32f?source=rss-c8873afac1d4------2</link>
            <guid isPermaLink="false">https://medium.com/p/a8accc02e32f</guid>
            <category><![CDATA[donald-trump]]></category>
            <category><![CDATA[putin]]></category>
            <dc:creator><![CDATA[Rajguleria]]></dc:creator>
            <pubDate>Sat, 15 Mar 2025 06:18:05 GMT</pubDate>
            <atom:updated>2025-03-15T06:18:05.313Z</atom:updated>
            <content:encoded><![CDATA[<h3>Defeat in Kursk would be a major blow to Ukraine’s plans to use its hold on the region as a bargaining chip in peace talks for the three-year-old war.</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/773/0*uLKjS8hE-NMwXpoV" /></figure><p>Putin called on Friday for beleaguered Ukrainian troops in Russian region of Kursk to “surrender”.</p><p><strong>Moscow:</strong></p><p>President Vladimir Putin called on Friday for beleaguered Ukrainian troops in the Russian region of Kursk to “surrender” as Ukraine’s President Volodymyr Zelensky accused the Russian leader of seeking to sabotage a ceasefire initiative.</p><p>US President Donald Trump urged Putin to spare the lives of the Ukrainian troops as he said his envoy had held “productive” talks with Russia’s leader on a proposed 30-day ceasefire.</p><p>Russia has mounted a rapid counteroffensive in the western border region of Kursk over the past week, recapturing much of the territory Ukraine seized in a shock incursion last August.</p><p>Defeat in Kursk would be a major blow to Ukraine’s plans to use its hold on the region as a bargaining chip in peace talks for the three-year-old war.</p><p>“We are sympathetic to President Trump’s call,” Putin said in remarks broadcast on Russian television.</p><p>“If they lay down their arms and surrender, they will be guaranteed life and dignified treatment,” Putin said.</p><p>Trump said “thousands” of Ukrainian troops were “completely surrounded by the Russian military, and in a very bad and vulnerable position”.</p><h3>‘Horrible massacre’</h3><p>“I have strongly requested to President Putin that their lives be spared. This would be a horrible massacre, one not seen since World War II,” Trump said.</p><p>Ukraine’s military leadership denied the claims. “There is no threat of our units being encircled,” Ukraine’s General Staff posted on social media.</p><p>Zelensky gave a more sober assessment in comments to reporters in Kyiv. “The situation in the Kursk region is obviously very difficult,” he said, while insisting the campaign still had value.</p><p>Russia, he said, had been forced to pull troops from other areas on the front line, easing pressure on Ukrainian forces fighting to keep control of the eastern logistics hub of Pokrovsk.</p><p>Trump’s latest comments came as he gave an update on a meeting Thursday between his envoy Steve Witkoff and Putin on a US-Ukrainian proposal for a 30-day pause in hostilities.</p><p>“We had very good and productive discussions with President Vladimir Putin of Russia yesterday, and there is a very good chance that this horrible, bloody war can finally come to an end,” Trump said on his Truth Social platform.</p><h3>Ukraine losing grip</h3><p>Putin said Thursday that he had “serious questions” about the proposal and that events in Kursk would influence the next moves towards a ceasefire.</p><p>Zelensky accused the Russian leader of seeking to undermine the ceasefire initiative.</p><p>“He is now doing everything he can to sabotage diplomacy by setting extremely difficult and unacceptable conditions right from the start even before a ceasefire,” Zelensky posted on X.</p><p>The Kremlin said Friday that it was “cautiously optimistic” a deal could be reached, but that Trump and Putin had to speak directly before talks could progress.</p><p>US National Security Advisor Mike Waltz said in a Fox News interview that the United States had “some cautious optimism” after Witkoff’s visit.</p><p>US Secretary of State Marco Rubio said at a meeting of the Group of Seven western powers in Canada that both sides would have to make “concessions”.</p><p>G7 foreign ministers warned Russia of new sanctions unless it accepted a ceasefire “on equal terms”, saying sanctions could include “caps on oil prices, as well as additional support for Ukraine, and other means”.</p><p>France and Germany accused Russia of seeking to block a ceasefire, and support for Ukraine was to be discussed again in a video conference of some European leaders with Zelensky on Saturday.</p><p>UK Prime Minister Keir Starmer on Friday said Russia’s “complete disregard for President Trump’s ceasefire proposal only serves to demonstrate that Putin is not serious about peace”.</p><p>Diplomatic sources said EU foreign affairs chief Kaja Kallas would propose that the 27-country bloc supply up to 40 billion euros ($43.5 billion) in new military aid to Ukraine.</p><p>Ukraine hoped its hold on Kursk would be a bargaining chip in talks with Russia and was eyeing a potential land swap with Moscow, which has occupied around a fifth of Ukraine since it took Crimea in 2014 and launched its military offensive in February 2022.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=a8accc02e32f" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Falcon 9 Lands At Cape Canaveral, Minutes After Crew-10 Launch]]></title>
            <link>https://medium.com/@rajguleria3/falcon-9-lands-at-cape-canaveral-minutes-after-crew-10-launch-edfeb14c0a5b?source=rss-c8873afac1d4------2</link>
            <guid isPermaLink="false">https://medium.com/p/edfeb14c0a5b</guid>
            <category><![CDATA[elon-musk]]></category>
            <category><![CDATA[donald-trump]]></category>
            <category><![CDATA[tesla]]></category>
            <dc:creator><![CDATA[Rajguleria]]></dc:creator>
            <pubDate>Sat, 15 Mar 2025 06:12:02 GMT</pubDate>
            <atom:updated>2025-03-15T06:12:02.174Z</atom:updated>
            <content:encoded><![CDATA[<h3>The mission will enable the return of Sunita Williams and Butch Wilmore, who have been stuck aboard the orbital lab since June last year, to Earth.</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/773/0*ReFt4Hnu9oqSz49m" /></figure><p>The first stage of the SpaceX Falcon 9 rocket landed at the Landing Zone 1 at Cape Canaveral Space Force Station in Florida, after launching the Crew-10 mission into space, which will hope bring astronauts Sunita Williams and Butch Wilmore back to Earth.</p><p>The landing occurred around 10 minutes after Falcon 9 rocket with a Crew Dragon fixed to its top blasted off from the Kennedy Space Center in Florida at 7.03 pm EST (2303 GMT), carrying a four-member team bound for the orbital outpost.</p><p>Williams and Wilmore have spent over nine months on the International Space Station (ISS) after the Boeing Starliner spacecraft they were testing on its maiden crewed voyage suffered propulsion issues and was deemed unfit to fly them back to Earth. What was to be a days-long round trip turned into a time frame much higher than the stipulated six months rotation time for astronauts on the ISS.</p><p>Along with Wilmore and Williams, NASA astronaut Nick Hague and Russian cosmonaut Aleksandr Gorbunov will also be aboard the returning Dragon capsule.</p><p>After the Crew-10 spaceship docks at a scheduled time of 11.30 pm EST, the Crew-9 team will begin preparing for departure. An ocean splashdown off the Florida coast is expected no sooner than March 19.</p><p>The Crew-10 team consists of NASA astronauts Anne McClain and Nichole Ayers, Japan’s Takuya Onishi, and Russia’s Kirill Peskov. During their mission, the new crew will conduct a range of scientific experiments, including flammability tests for future spacecraft designs and research into the effects of space on the human body.</p><p>While visuals from the astronauts’ space stay raised concerns on their health, it also took a political turn. President Donald Trump and SpaceX founder Elon Musk have often suggested that former president Joe Biden “abandoned” the pair intentionally and rejected a plan to bring them back sooner. While Musk gave no specifics regarding the Crew-9 mission and the return plan for the astronauts, he also went on to lash out at Danish astronaut Andreas Mogensen who raised questions regarding the mission.</p><p>Trump, meanwhile, referred to Williams, a decorated former naval captain, as “the woman with the wild hair” and speculated about the personal dynamic between the two astronauts. “They’ve been left up there — I hope they like each other, maybe they love each other, I don’t know,” he said during a recent White House press conference.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=edfeb14c0a5b" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[The 5 Non-Negotiable Daily Habits I Used To Radically Improve My Life.]]></title>
            <link>https://medium.com/@rajguleria3/the-5-non-negotiable-daily-habits-i-used-to-radically-improve-my-life-d8bee2cf3fd9?source=rss-c8873afac1d4------2</link>
            <guid isPermaLink="false">https://medium.com/p/d8bee2cf3fd9</guid>
            <dc:creator><![CDATA[Rajguleria]]></dc:creator>
            <pubDate>Thu, 25 Jul 2024 13:27:11 GMT</pubDate>
            <atom:updated>2024-07-25T13:27:11.997Z</atom:updated>
            <content:encoded><![CDATA[<blockquote><em>“Successful people aren’t born that way. They become successful by establishing the habit of doing things unsuccessful people don’t like to do.” ―William Makepeace Thackeray.</em></blockquote><p>Great self-improvement advice tends to not change over time.</p><p>What works for successful people in the past will tend to work for those trying to be successful today and into the future.</p><p>Think about the most successful people you know. What habits do they have? What mindsets do they cultivate? Who do they tend to surround themselves with? I can almost guarantee there are areas of commonality.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*6KTABarY5YegPilcTWV0Xw.jpeg" /></figure><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=d8bee2cf3fd9" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Python Forensics and Virtualization | Hash Functions — Python Tutorial]]></title>
            <link>https://medium.com/@rajguleria3/python-forensics-and-virtualization-hash-functions-python-tutorial-73f727a42848?source=rss-c8873afac1d4------2</link>
            <guid isPermaLink="false">https://medium.com/p/73f727a42848</guid>
            <category><![CDATA[python-forensics]]></category>
            <category><![CDATA[virtualization]]></category>
            <category><![CDATA[tutorial-python]]></category>
            <dc:creator><![CDATA[Rajguleria]]></dc:creator>
            <pubDate>Tue, 17 Jan 2023 08:06:09 GMT</pubDate>
            <atom:updated>2023-01-17T08:06:09.789Z</atom:updated>
            <content:encoded><![CDATA[<h3>Python Forensics and Virtualization | Hash Functions — Python Tutorial</h3><p>In this tutorial, we will learn the Forensics science using Python, basic Python forensics applications, Hash functions, Cracking an Encryption, Visualization, Naming Conventions, Dshell and Scapy, Network Forensics with its detailed explanation.</p><h3>Introduction</h3><p>Collecting and preserving evidence is most essential for cyber forensic investigation and analysis at the computer devices. It plays important role in a court room to be used against the criminal. Nowadays, technology facilitates us to get the information by just typing the query on the browser. But it also invites the cyber crooks. Cyber crooks are those who perform the malicious activity by using their system and internet. They can get your all information from sitting somewhere else.</p><p>With its wide applications, Python also provides the facility to work with the digital forensics. By using it, we can gather data, extract evidence, and also encrypt password. It will support us to reinstate the reliability of evidence.</p><p>Before go further, you must familiar with the <a href="https://www.javatpoint.com/python-tutorial">Python</a> and its advance concepts.</p><h3>Introduction to Computational Forensics</h3><p>Computational Forensics is a part of study which used to solve problems in various forensics disciplines. It uses computer-based modeling, analysis, computer simulation and recognition. Python Forensics was invented by the <strong>Chet Homster</strong>. There are also pattern evidence, such as fingerprints, shoeprints, toolmarks and any documents. It makes use of procedures, scope of objects, and substances. There are also physiological and behavioral patterns such as digital evidence, <a href="https://www.javatpoint.com/dna-full-form">DNA</a>, and crime scenes.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/800/0*8cmktGcQN8RYFiYp.png" /></figure><p>We can also use the various algorithms to deal with the signal and image processing. By using algorithms, we can also handle the, <a href="https://www.javatpoint.com/data-mining">data mining</a>, <a href="https://www.javatpoint.com/computer-graphics-tutorial">computer graphics</a>, <a href="https://www.javatpoint.com/machine-learning">machine learning</a>, computer vision data visualization, and statistical pattern recognition.</p><p>In a few words, the computation forensics is used to study the digital evidence, computational forensics deals with the various types of evidence.</p><h3>Naming Conventions for Python Forensics Application</h3><p>We must familiar with the naming convention and patterns to follow the Python Forensics guidelines. Consider the following table.</p><p>Naming ConventionExample</p><p>The hashing algorithm is one of the best ways of take as an input a stream of binary data. In the real life scenario, we can encrypt our password, file, or even any kinds of digital file or data. The algorithm takes an input and generates the encrypted message. Let’s see the given example.</p><h3>Example</h3><pre>import sys,string,md5  <br>print(&quot;Enter the name&quot;)  <br>line=sys.stdin.readline()  <br>line=line.rstrip()  <br>md5_object=md5.new()  <br>md5_object.update(line)  <br>print(md5_object.hexdigest())  </pre><h3>Python Hash Function</h3><p>Python hash function is used to map a vast amount of data to a fixed value. An input returns the same output. It is a hash sum and stores features with precise information. Once we map the data to a fixed value, that cannot be revert. That’s why we also refer it as one-way cryptographic algorithm.</p><p>Let’s understand the following example -</p><p><strong>Example -</strong></p><pre>import hashlib  <br>import uuid  <br>  <br>def hash_pass(password):  <br>    s = uuid.uuid4().hex  <br>    return hashlib.sha256(s.encode() + password.encode()).hexdigest() + &#39;:&#39; + s  <br>def verify_password(hashed_password, user_password):  <br>    password, s = hashed_password.split(&#39;:&#39;)  <br>    return password == hashlib.sha256(s.encode() + user_password.encode()).hexdigest()  <br>new_password = input(&#39;Enter your password :&#39;)  <br>  <br>hashed_password = hash_pass(new_password)  <br>print(&#39;The hash string to store in the db is: &#39; + hashed_password)  </pre><p><strong>Output:</strong></p><pre>Enter your password: sharma<br>The hash string to store in the db is: 947782bdb0c7a5ad642f1f26179b6aef2d9857427b45a09af4fce3b8f1346e91:8a8371941513482487e5ab8af2ae6466</pre><p>Now, we will re-enter the password.</p><pre>old_password = input(&#39;Enter new password &#39;)  <br>if verify_password(hashed_password, old_password):  <br>    print(&#39; Entered password is correct&#39;)  <br>else:  <br>    print(&#39;Passwords do not match&#39;)</pre><p><strong>Output:</strong></p><pre>Enter your password devansh <br>The hash string to store in the db is: 4762866edd3b49c7736163ef3d981e42629a09a9ca7e081f56d116e137d77b9c:ebbf5b16bd9f4b989505a495bf7ae9b9<br>Enter new password sharma<br>Passwords do not match</pre><p>The hash function has the following properties.</p><ul><li>We can simply transform any hash value for any input value.</li><li>It doesn’t able to produce the same output as given hash value.</li><li>It is unrealistic to transform the input without moving the hash value.</li></ul><h3>Cracking an Encryption in Python</h3><p>We must know how to encrypt the text data that we fetch during analysis and evidence. First, understand the basic cryptographic.</p><p>Generally, secret messages are sent by the army person to convey their plans without get read by their enemies. These messages are not in the human-readable format. The plain texts are encrypted by using the encryption algorithm and these texts are called cipher text.</p><p>Suppose a general commander sends a message to senior to save the text from their enemies. Here, we take shift the plain text letter four place in the alphabet. Now, the A will be E, each B is F and so no.</p><p>Let’s understand the following example to crack the vector data.</p><p><strong>Example -</strong></p><pre>import sys  <br>def decryption(text,cipher):  <br>    simple_text=&#39;&#39;  <br>    for each in cipher:  <br>        x = (ord(each)-text) % 126  <br>        if x &lt; 32:  <br>            x+=95  <br>            simple_text += chr(x)  <br>            print(simple_text)  <br>cipher_text = input(&#39;Enter the message: &#39;)  <br>for i in range(1,95,1):  <br>    decryption(i,cipher_text)  </pre><p><strong>Output:</strong></p><pre>Enter message: Yes<br>~<br>}<br>|<br>{<br>z<br>y<br>x<br>w<br>v<br>u<br>t<br>s<br>r<br>r~<br>q<br>q}<br>p<br>p|<br>o<br>o{<br>n<br>nz<br>m<br>my<br>l<br>lx<br>k<br>kw<br>j<br>jv<br>i<br>iu<br>h<br>ht<br>g<br>gs<br>f<br>fr<br>e<br>eq<br>d<br>dp<br>dp~<br>c<br>co<br>co}<br>b<br>bn<br>bn|<br>a<br>am<br>am{<br>`<br>`l<br>`lz<br>_<br>_k<br>_ky<br>j<br>jx<br>i<br>iw<br>h<br>hv<br>g<br>gu<br>f<br>ft</pre><h3>Virtualization</h3><p>A virtualization is an act of emulate IT system such as workstations, networks and storage. We make the virtual instance of such a resource. It can be done with the help of hypervisor.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/650/0*oZKLlQW0jK5y2Y2w.png" /></figure><p>The virtualization of hardware plays very important role in the computer forensics. By using the virtualization, we can get following advantages.</p><ul><li>We can use the workstation in a validate state for each investigation.</li><li>We can recover deleted data by including <strong>dd</strong> images of a drive on a virtual machine.</li><li>The virtual machine can turn into the recovery device that will help to gather evidence.</li></ul><p>We define the following steps to create virtual machine using Python</p><p><strong>Step — 1:</strong> Suppose we consider our local machine as <strong>“dummy”</strong>. Each Virtual Machine will have at least 512 MB of memory.</p><pre>virmach_memory = 512 * 1024 * 1024  </pre><p><strong>Step — 2:</strong> Now, we attach this virtual machine to the default cluster.</p><pre>virmach_cluster = api.clusters.get(name = &quot;Default&quot;)  </pre><p><strong>Step — 3:</strong> Next, boot the virtual machine from the virtual HDD.</p><pre>vm_os = params.OperatingSystem(boot = [params.Boot(dev = &quot;hd&quot;)])  </pre><p>Now, we will combine the above steps into a virtual machine parameter object. Let’s understand the following example.</p><p><strong>Example -</strong></p><pre>from ovirtsdk.xml import params  <br>from ovirtsdk.api import API    <br>  <br>  <br>try:    <br># We need to provide Api credentials for virtual machine  <br>    api = API(url=&quot;https://HOST&quot;,  <br>              username=&quot;Example&quot;,  <br>              password=&quot;example123&quot;,  <br>              ca_file=&quot;ca.crt&quot;)  <br>  <br>    virmach_name = &quot;dummy&quot;  <br>    virmach_memory = 512 * 1024 * 1024  # calculating the memory in bytes  <br>    virmach_cluster = api.clusters.get(name=&quot;Default&quot;)  <br>    virmach_template = api.templates.get(name=&quot;Blank&quot;)  <br>  <br>    # here we are assigning the parameters to operating system  <br>    virmach_os = params.OperatingSystem(boot=[params.Boot(dev=&quot;hd&quot;)])  <br>  <br>    virmach_params = params.VM(name=virmach_name,  <br>                          memory=virmach_memory,  <br>                          cluster=virmach_cluster,  <br>                          template=virmach_template,  <br>                           os = virmach_os)  <br>  <br>    try:  <br>        api.vms.add(vm=virmach_params)  <br>        print(&quot;Virtual machine &#39;%s&#39; added successfully.&quot; % virmach_name)   <br>    except Exception as ex:  <br>        print(&quot;Adding virtual machine &#39;%s&#39; failed: %s&quot; % (virmach_name, ex))  <br>        api.disconnect()  <br>  <br>except Exception as ex:  </pre><p><strong>Output:</strong></p><pre>Virtual Machine dummy added successfully.</pre><h3>Network Forensics in Python</h3><p>Python also provide the facility to work with the network forensics. In the modern days, Python network forensics environment investing can come across many difficulties. These problems can be responding to a breach report, executing assessments pertaining to susceptibility, or validating regularity compliances. Let’s understand the basic terminology of network forensics.</p><p><strong>Client </strong>— The client runs personal computer and workstation.</p><p><strong>Server </strong>— The server executes the client’s request.</p><p><strong>Protocols </strong>— Protocols are the set of rule that must be followed while data transfer.</p><p><strong>Websockets </strong>— A websockets are protocol that provides the full-duplex communication and runs over the TCP connection. We can send the bi-direction messages using the websockets.</p><p>With the help of those protocols, we can authenticate the information and sent or received by the third party users. But, encryption is necessary to secure channels.</p><p>Let’s understand the following example of network</p><p><strong>Example -</strong></p><pre>import socket  <br># creating a socket object  <br>sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)  <br># getting local machine name  <br>host = socket.gethostname()  <br>port = 8080  <br># connection to hostname on the port.  <br>sock.connect((host, port))  <br># Receive no more than 1024 bytes  <br>temp = sock.recv(1024)  <br>print(&quot;The client waits for connection&quot;)  <br>sock.close()  </pre><p><strong>Output:</strong></p><pre>The client waits for connection</pre><h3>Python Scapy and Dshell</h3><p>Let’s understand the brief introduction Python Scapy and Dshell.</p><h3>Python Scapy</h3><p>A <strong>scapy</strong> is Python-based tool which analyze and manipulate network traffic. With the help of scapy, we can analyze packet manipulation. We can also capture and decode the packets of a wide number of protocols. The benefit of using scapy is to get the detailed report about network traffic to the investigator. The third-party tools such as OS fingerprint app can be also used in Scapy. Let’s understand the following example.</p><p><strong>Example -</strong></p><pre>#Imports scapy and GeoIP toolkit  <br>import scapy, GeoIP   <br>from scapy import *  <br>  <br>geoIp = GeoIP.new(GeoIP.GEOIP_MEMORY_CACHE)   <br>def locatePackage(pkg):  <br>    # extracts the source IP address  <br>    source = pkg.getlayer(IP).src  <br>    # extracts the destination IP address  <br>    destination = pkg.getlayer(IP).dst  <br>    # gets Country details of source  <br>    srcCountry = geoIp.country_code_by_addr(source)   <br>    dstCountry = geoIp.country_code_by_addr(destination)  <br>    # gets country details of destination  <br>    print src+&quot;(&quot;+sourceCountry+&quot;) &gt;&gt; &quot;+destination+&quot;(&quot;+destinationcountry+&quot;)\n&quot;  </pre><p><strong>Output:</strong></p><pre>source INDIA &gt;&gt; destination USA</pre><h3>Python Dshell</h3><p>The Dshell is a Python-based network forensics analysis toolkit. It was developed by the US army research laboratory and released it open-source in 2014. It makes the forensics investigation very easy. Dshell provides the following decoders.</p><ul><li><strong>reservedips </strong>— It is used to identify solutions for the DNS problems.</li><li><strong>rip-http </strong>— It extracts the files from HTTP traffic.</li><li><strong>large-flows </strong>— It is a decoder that represents the list net flows.</li><li><strong>Protocols </strong>— It identifies the non-standard protocols.</li><li><strong>dns </strong>— It extracts DNS-related queries.</li></ul><h3>Python Searching</h3><p>Searching is the most important part of the forensics investigation. Nowadays, the good search is upon the investigator who is running the evidence. Keyword searching from the message is a pillar of the investigation. We can find the strong evidence with the help of a keyword.</p><p>The experience and knowledge both are required to get the information from the deleted messages.</p><p>Python provides the various built-in modules to support search operation. The investigator can find the result using the keywords such as “who”, “what”, “where”, “when”, “which”, etc. Let’s understand the following example.</p><p><strong>Example -</strong></p><pre># Searching a particular word from a message  <br>str1 = &quot;This is an example for Computational forensics of gathering evidence!&quot;  <br>str2 = &quot;string&quot;  <br>  <br>print(str1.find(str2))  <br>print(str1.find(str2, 10))  <br>print(str1.find(str2, 40))  </pre><p><strong>Output:</strong></p><pre>11<br>11<br>-1</pre><h3>Python Indexing</h3><p>Indexing is feature that the investigator can use to gather potential evidence from the files. The evidence can be restricted within the memory snapshot, a disk image, a file, or a network trace. It is very helpful to reduce time for time-consuming tasks like keyword searching. The indexing also used to locate the keywords in interactive searching phase. In the following examle, we have explained indexing in Python.</p><p><strong>Example -</strong></p><pre>list1 = [123, &#39;example&#39;, &#39;creative&#39;, &#39;indexing&#39;]  <br>  <br>print(&quot;Index example : &quot;, list1.index(&#39;example&#39;))  <br>print(&quot;Index for indexing : &quot;, list1.index(&#39;indexing&#39;))  <br>  <br>str1 = &quot;This is a message for forensic investigation indexing&quot;  <br>str2 = &quot;message&quot;  <br>  <br>print(&quot;Index of the character keyword found is &quot;)  <br>print(str1.index(str2))  </pre><p><strong>Output:</strong></p><pre>Index example :  1<br>Index for indexing :  3<br>Index of the character keyword found is <br>10</pre><h3>PytIndex example : 1<br>Index for indexing : 3<br>Index of the character keyword found is <br>10hon Image Library</h3><p>The real meaning of forensics investigation is to extract the valuable information from the available resources. Getting all the relevant information from the resource is essential for the report. It helps us to derive appropriate result.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/230/0*WhUpNJ66wlHp8b05.png" /></figure><p>Resource data can be either simple data structure such as databases or complex data structures such as JPEG image.</p><p>Investigator can easily access the information from the simple data structure but extracting information from the complex data structure is tedious task.</p><p>Python provides the Image library which is known as PIL. It is used to add image processing capabilities to out Python interpreter. It also support the file formats, graphics capabilities and also provides powerful image processing. Let’s understand the following image to extracting data from images.</p><p>We define the programming example to explain how it actually works.</p><p><strong>Step — 1:</strong> Suppose we have a following image where we need to extract the details.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/289/0*J4ZYt4o7yacgHp0f.png" /></figure><p><strong>Step — 2:</strong> An image consists of various pixel values. The PIL library uses to extract the image details for gather evidence. Let’s understand the following example.</p><p><strong>Example -</strong></p><pre>from PIL import Image  <br>im = Image.open(&#39;penguin.jpeg&#39;, &#39;r&#39;)  <br>pix_val = list(im.getdata())  <br>pix_val_flat = [x for sets in pix_val for x in sets]  <br>print(pix_val_flat) </pre><p><strong>Output:</strong></p><pre>[255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255]</pre><p>The output is returned in the form of a list. It is a pixel value of the RGB combination that gives a better picture of what data is needed.</p><h3>Python Multiprocessing Support</h3><p>Forensics experts find difficulties to apply digital solutions to large digital evidence on the common crime. Most of the digital evidences are the single threaded that mean we can execute only one command at time. Let’s see the brief <a href="https://www.javatpoint.com/python-multiprocessing">introduction of multiprocessing</a>.</p><h3>Multiprocessing</h3><p>Multiprocessing is an ability of the system that support more than one process. It enables the several programs to run concurrently. There are two types of the multiprocessing — <strong>symmetric and asymmetric processing</strong>.</p><p>Let’s understand the following example of multiprocessing.</p><p><strong>Example -</strong></p><pre>import random  <br>import multiprocessing  <br>  <br>  <br>def list_append(count, id, out_list):  <br>    # count number of process at a time  <br>    for i in range(count):  <br>        out_list.append(random.random())  <br>  <br>    if __name__ == &quot;__main__&quot;:  <br>        size = 810  <br>        procs = 2  <br>        jobs = []  <br>  <br>    for i in range(0, procs):  <br>        out_list = list()  # list of processes  <br>        process1 = multiprocessing.Process(  <br>            target=list_append, args=(size, i, out_list))  <br>  <br>        # appends the list of processes  <br>        jobs.append(process1)  <br>  <br>    # Calculate the random number of processes  <br>    for j in jobs:  <br>        j.start()  # initiate the process  <br>  <br>    # After the processes have finished execution  <br>    for j in jobs:  <br>        j.join()  <br>        print(&quot;List processing complete.&quot;) </pre><p><strong>Output:</strong></p><pre>List processing complete</pre><h3>Mobile Forensics in Python</h3><p>Forensics investing is not only limited to the standard computer hardware such as hard disk, CPUs, etc. Hardware is followed with the help of techniques to analyze non-standard hardware or transient evidence.</p><p>Nowadays, smartphones are widely used in digital investigation, but they still meant as non-standard. With the proper research of smartphones, we can extract photos, smartphones, and messages.</p><p>The android smartphones uses the PIN, or alphanumeric password. The password can be between 4 and 16 digits/characters.</p><p>In the following example, we will get through a lock screen to extract data. The smartphone password generally stores inside a file <strong>password.key</strong> in <strong>/data/system</strong>.</p><p>Android stores a salted SHA1-hashsum and MD5-hashsum of this password. Let’s see the following example.</p><p><strong>Example -</strong></p><pre>public byte[] passwordToHash(String password) {  <br>  if (password == null) {  <br>     return null;  <br>  }  <br>  String algo = null;  <br>  byte[] hashed = null;  <br>  try {  <br>     byte[] saltedPassword = (password + getSalt()).getBytes();  <br>     byte[] sha1 = MessageDigest.getInstance(algo = &quot;SHA-1&quot;).digest(saltedPassword);  <br>     byte[] md5 = MessageDigest.getInstance(algo = &quot;MD5&quot;).digest(saltedPassword);  <br>     hashed = (toHex(sha1) + toHex(md5)).getBytes();  <br>  } catch (NoSuchAlgorithmException e) {  <br>     Log.w(TAG, &quot;Failed to encode string because of missing algorithm: &quot; + algo);  <br>  }  <br>  return hashed;  <br>}  </pre><p>The above code is a sample code of crack smartphone password. The dictionary attack won’t be affected to crack the password since hashed password is stored in a <strong>salt file</strong>. The salt file is a string of hexadecimal representation of a random integer of 64 bit. The Rooted smartphones or JTAG Adapter can access the <strong>salt</strong> file.</p><h3>Rooted Smartphones</h3><p>The file’s dump /data/system/password.key is stored in SQLite database under the lock <strong>screen.password_salt.</strong> The Password is stored under <strong>settings.db</strong>.</p><h3>JTAG Adapter</h3><p>The JTAG stands for Joint Test Action Group which can be used to access the salt. Similarly, a Riff-Box or a JIG-Adapter can be used to access the sale files. We can find the position of the encrypted data using the obtained information from Riff-box. The rules are given below.</p><ul><li>Find the associated string “<strong>password_salt</strong>”.</li><li>The width of the salt file represents in the bytes. This is its length.</li><li>This is the length which is actually searched to get the stored password/pin of the smartphones.</li></ul><h3>Memory and Forensics</h3><p>Python forensics primarily focuses on the volatile memory with the help of Volatility which is a Python based framework.</p><h3>Volatile Memory</h3><p>Volatile memory is a type of memory that erased when the system’s power is turned off or interrupted. In the simple words, if we are working on a document that has not been saved to the hard disk and suddenly the power goes off, we will lose our data.</p><p>The volatile memory follows the same pattern as the other forensics investigations.</p><ul><li>First, it needs to be selected the target of the investing.</li><li>Acquire the forensics data.</li><li>Forensics Analysis</li></ul><p>The <a href="https://www.javatpoint.com/ram-full-form">RAM</a> dump is tool which used to analysis the gathered data from the <a href="https://www.javatpoint.com/ram">RAM</a>.</p><h3>YARA Rules</h3><p>YARA is a tool which used to examine the suspected files/ directories and match strings. It is based on the pattern matching implementation. It plays an important role in forensics analysis.</p><p><strong>Example -</strong></p><pre>import operator  <br>import os  <br>import sys  <br>  <br>sys.path.insert(0, os.getcwd())  <br>import plyara.interp as interp  <br>  <br># Plyara is a script that lexes and parses a file consisting of one more Yara  <br>  <br>if __name__ == &#39;__main__&#39;:  <br>    file_to_analyze = sys.argv[1]  <br>Dictrules = interp.parseString(open(file_to_analyze).read())  <br>authors = {}  <br>imps = {}  <br>meta_keys = {}  <br>max_strings = []  <br>max_string_len = 0  <br>tags = {}  <br>rule_count = 0  <br>  <br>for rule in Dictrules:  <br>    rule_count += 1  <br>  <br># Imports   <br>if &#39;imports&#39; in rule:  <br>    for imp in rule[&#39;imports&#39;]:  <br>        imp = imp.replace(&#39;&quot;&#39;, &#39;&#39;)  <br>  <br>if imp in imps:  <br>    imps[imp] += 1  <br>else:  <br>    imps[imp] = 1  <br># Tags   <br>if &#39;tags&#39; in rule:  <br>    for tag in rule[&#39;tags&#39;]:  <br>        if tag in tags:  <br>           tags[tag] += 1  <br>        else:  <br>           tags[tag] = 1  <br>  <br># Metadata   <br>if &#39;metadata&#39; in rule:  <br>    for key in rule[&#39;metadata&#39;]:  <br>       if key in meta_keys:  <br>         meta_keys[key] += 1  <br>       else:  <br>         meta_keys[key] = 1  <br>  <br>if key in [&#39;Author&#39;, &#39;author&#39;]:  <br>    if rule[&#39;metadata&#39;][key] in authors:  <br>         authors[rule[&#39;metadata&#39;][key]] += 1  <br>else:  <br>authors[rule[&#39;metadata&#39;][key]] = 1  <br>  <br># Strings   <br>if &#39;strings&#39; in rule:  <br>    for strr in rule[&#39;strings&#39;]:  <br>if len(strr[&#39;value&#39;]) &gt; max_string_len:  <br>    max_string_len = len(strr[&#39;value&#39;])  <br>max_strings = [(rule[&#39;rule_name&#39;], strr[&#39;name&#39;], strr[&#39;value&#39;])]  <br>elif len(strr[&#39;value&#39;]) == max_string_len:  <br>max_strings.append((rule[&#39;rule_name&#39;], strr[&#39;key&#39;], strr[&#39;value&#39;]))  <br>  <br>print(&quot;\nThe number of rules implemented&quot; + str(rule_count))  <br>ordered_meta_keys = sorted(meta_keys.items(), key=operator.itemgetter(1),  <br>reverse = True)  <br>ordered_authors = sorted(authors.items(), key=operator.itemgetter(1),  <br>reverse = True)  <br>ordered_imps = sorted(imps.items(), key=operator.itemgetter(1), reverse=True)  <br>ordered_tags = sorted(tags.items(), key=operator.itemgetter(1), reverse=True)  </pre><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=73f727a42848" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Best Books to Learn Django for Beginners and Advance Programmers — Python Tutorial]]></title>
            <link>https://medium.com/@rajguleria3/best-books-to-learn-django-for-beginners-and-advance-programmers-python-tutorial-8ccbdd6d67cf?source=rss-c8873afac1d4------2</link>
            <guid isPermaLink="false">https://medium.com/p/8ccbdd6d67cf</guid>
            <category><![CDATA[python3]]></category>
            <category><![CDATA[free-python-tutorials]]></category>
            <category><![CDATA[python]]></category>
            <dc:creator><![CDATA[Rajguleria]]></dc:creator>
            <pubDate>Tue, 17 Jan 2023 07:41:14 GMT</pubDate>
            <atom:updated>2023-01-17T07:41:14.239Z</atom:updated>
            <content:encoded><![CDATA[<h3>Best Books to Learn Django for Beginners and Advance Programmers — Python Tutorial</h3><p>In this article, we will discuss a few excellent books to learn Django for all readers. We will explore their features, books writing style, example explanations, topics covered and the number of projects defined in the book. Before exploring the book, let’s have a brief introduction to Django.</p><h3>What is Django?</h3><p><a href="https://www.javatpoint.com/django-tutorial">Django</a> is an open-source <a href="https://www.javatpoint.com/python-tutorial">Python framework</a> used to develop rich web applications. It is one of the most popular frameworks for web development. It provides many built-in features so that the developer only needs to focus on the business logic rather than repetitive functionality. Let’s see some awesome features of Django. Let’s see some awesome features of Django.</p><ul><li>Great documentation, a vast community across the world.</li><li>It is fast, secure, reliable, and versatile.</li><li>Written in Python.</li><li>Follow the MVT approach which means the Model View Template.</li><li>It automatically handles the site maps, RSS feeds, content administration, user authentication, etc.</li><li>It provides a built-in admin panel.</li><li>Rapid release of its version.</li><li>It eliminates the need to write SQL queries by using Python objects. SQLite database comes with it.</li></ul><p>Learning Django may take a slightly longer time, but once we get the concepts properly. We will explore more concepts Django in our application.</p><h3>Best Django Books for Beginners</h3><p>We have listed below best Python Django books for beginners.</p><h3>1. Django for APIs: Build web APIs with Python &amp; Django</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/250/0*lLZeDqfPE_BS6WLP.jpg" /></figure><p><strong>Amazon </strong>— <a href="https://www.amazon.in/Django-APIs-Build-web-Python-ebook/dp/B08FMVYVFR/ref=sr_1_1?dchild=1&amp;keywords=Django+for+APIs&amp;qid=1606894976&amp;sr=8-1">Django for APIs</a></p><p>This book is written by William S. Vincent. The author has explained how to create <a href="https://www.javatpoint.com/restful-web-services-tutorial"><strong>RESTful</strong></a> API using Django and the Django REST framework from scratch in this book. This book is not explained “What is Django”; instead, it teaches us how to write code API that can be reused.</p><p>This book focuses on the best coding practice to build APIs and also explains the Django REST framework and React (JS library). If you have learned much from the official documentation, this book provides much information and covers only the most important concepts. The author has written this book for beginners, but he also written many complicated topics for advanced programmers.</p><h3>2. Django Unleashed</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/250/0*s2BUek6wokV3JCRt.jpg" /></figure><p><strong>Amazon </strong>— <a href="https://www.amazon.in/Andrew-Pinkham/e/B0184QUCMM?ref=sr_ntt_srch_lnk_1&amp;qid=1606895043&amp;sr=8-1">Django Unleashed</a></p><p>This is the best book for beginners as well as experienced Django programmers. This book has a detailed explanation and starts with scratch to build an application in Django. It includes different problem solving the same problem that we can identify which solution is appropriate. The author shifts the topic explanation from basic to complex topics. Some of the advance topics are difficult to follow initially, but we do the practice, we will appreciate the effort the author has put explain them. This book covers many topics such as Generic views, creating custom, security, performance, users and managers, etc., are explained very effectively.</p><h3>3. Beginners Django E-Commerce</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/250/0*rtnyMStcvurtmvV-.jpg" /></figure><p><strong>Flipkart </strong>— <a href="https://www.flipkart.com/beginning-django-e-commerce/p/itmetj6p2hkcuyyh?pid=9781430225355&amp;lid=LSTBOK9781430225355M2T4KL&amp;marketplace=FLIPKART&amp;srno=s_1_1&amp;otracker=search&amp;otracker1=search&amp;fm=SEARCH&amp;iid=3e84be39-c1c8-4ce4-9f95-5ea92d4ad80a.9781430225355.SEARCH&amp;ppt=sp&amp;ppn=sp&amp;ssid=6t0noy93hc0000001606895151476&amp;qH=2cf8b06abded96f7">Beginners Django E-Commerce</a></p><p>This book is written by <strong>Jin McGraw</strong>. It is not a purely technical book but also describe some practical concept of the framework. The author hasn’t explained the in-built libraries in detail. It focuses on how to use these in projects and scenarios. If someone has a basic knowledge of Django then it will help to sharpen the skill. However, we should have a decent understanding of <a href="https://www.javatpoint.com/html-tutorial">HTML</a>, <a href="https://www.javatpoint.com/css-tutorial">CSS</a>, <a href="https://www.javatpoint.com/xml-tutorial">XML</a>, <a href="https://www.javatpoint.com/sql-tutorial">SQL</a> other than Python. This book is also included e-commerce website, however author gives small details about the project but not described fully. We have to find out how to do what we are supposed to do. It is best book to understand Django for basic concepts.</p><h3>4. Lightweight Django 1stEdition</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/250/0*eC7mdL8E-Tw1e1Vs.jpg" /></figure><p><strong>Amazon </strong>— <a href="https://www.amazon.in/Lightweight-Django-Using-Websockets-Backbone/dp/9351108651/ref=sr_1_1?dchild=1&amp;keywords=Lightweight+Django&amp;qid=1606895207&amp;sr=8-1">Lightweight Django</a></p><p>This book is written by <strong>Jula Elman</strong> &amp; <strong>Mark Lavin</strong>. This is another nice interactive book with hands-on approaching book to learn Django. This book starts with the basic concepts and covers a most of topics in-depth. It is suitable for both beginners and advanced developers. The best thing about this book is that topics are broken into smaller components and explain each component, which makes each read and helps the reader understand the low-level details and overall pictures. The author has taken care to explain every single line code that everyone can understand very easily. We can say that the detailing of this book is just amazing.</p><p>Before diving into the topic, we must have a basic <strong>knowledge </strong><a href="https://www.javatpoint.com/jquery-tutorial"><strong>jQuery</strong></a><strong>, </strong><a href="https://www.javatpoint.com/bootstrap-tutorial"><strong>Bootstrap</strong></a><strong> and HTML</strong>. If we have the knowledge of these topics, it will add advantage and we can learn fast. This book is enough to understand the basic concepts, but we might need addition resources such as documentation/blogs to understand why something has been done.</p><h3>5. Django Design Pattern and Best Practices</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/250/0*g_kIJWqoaoxrEHmu.jpg" /></figure><p><strong>Amazon </strong>— <a href="https://www.amazon.in/Django-Design-Patterns-Practices-Industry-standard/dp/1788831349/ref=sr_1_1?dchild=1&amp;keywords=5.+Django+Design+Pattern+and+Best+Practices&amp;qid=1606895233&amp;sr=8-1">Django Design Pattern</a></p><p>This book is written by <strong>Arun Ravichandran</strong>. This book covers a few unique and important concepts that we would not find in many other resources or online resources. Apart from that, this book discusses a good amount of basics about Django starting with why Django came into existence. The author also discusses many problems with various solutions. It also explains how we make development faster. Various patterns help to reduce the coding time and enhance code performance. The author also explains to identify where and when to use pattern by giving examples and solutions. This book also talks about testing and security which makes it a very effective and useful book.</p><h3>6. Django 2 by Example</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/250/0*csMw6Q47QXjSIshI.png" /></figure><p><strong>Amazon </strong>— <a href="https://www.amazon.in/Django-Example-powerful-reliable-applications/dp/1788472489/ref=sr_1_1?dchild=1&amp;keywords=Django+2+by+Example&amp;qid=1606895299&amp;sr=8-1">Django 2 by Example</a></p><p>This book is written by <strong>Antonio Mele</strong>. This book is good for both beginners and intermediate level learners. If someone has a basic knowledge of <a href="https://www.javatpoint.com/javascript-tutorial">JavaScript</a>, HTML, and Python, this book would be the best choice. It covers basic and advanced concepts in-depth, including integration with other technologies like Celery and Radis. The author explains many coding examples and covers wide range of topics. We may need Django official documentation to learn understand more methods. We can consider this book to read basic about Django. The author assumes that you have no prior knowledge of Django.</p><h3>7. Two Scoops of Django 1.11: Best Practices for the Django Web Framework</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/250/0*5u2wREyMzXERRyqs.jpg" /></figure><p><strong>Amazon </strong>— <a href="https://www.amazon.in/Two-Scoops-Django-1-11-Practices/dp/0692915729/ref=sr_1_2?dchild=1&amp;keywords=Two+Scoop+of+Django&amp;qid=1606895360&amp;sr=8-2">Two Scoops of Django</a></p><p>This book is written by <strong>Daniel Roy Greenfeld</strong>. This book is best if someone has worked on a Django project and has basic idea of Django. This book is written for the both types of reader beginners and professionals. It includes tips and valuable suggestions for the best practices. This book includes plenty of informative diagrams that keep us hooked on the book. Writing style of this book is able to maintain a friendly tone. Each chapter is independent than the other so we can skip chapters and them as we like. We will also learn to deploy our application to the <strong>cloud(PaaS).</strong> The author is shared their experience in the form of tips, code, sample, tricks, and techniques.</p><h3>8. Django for Professionals: Production websites with Python &amp; Django</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/250/0*6ccR__0cVCpZ3hOr.jpg" /></figure><p><strong>Amazon </strong>— <a href="https://www.amazon.in/Two-Scoops-Django-1-11-Practices/dp/0692915729/ref=sr_1_2?dchild=1&amp;keywords=Two+Scoop+of+Django&amp;qid=1606895360&amp;sr=8-2">Django for Professionals</a></p><p>This book is written by William S. Vincent. This is an extension of the Django for beginners’ book. We will learn concepts with the practical approach. In the basic version, we will build simple websites. In this book, we will find many useful tips and tricks to build production apps. We will get many other useful tools in each chapter. The author has chosen very wisely. We need to have basic knowledge of the Python language. The author assumes that the reader do not know any others — Bootstrap, PostgreSQL, Docker, etc. This book also includes a complete guide to building a website covering all the concepts that we will need to become a pro in Django.</p><h3>9. Django for Beginners: Build Websites with Python and Django</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/250/0*VbMNnD04EAh2QEMD.jpg" /></figure><p><strong>Amazon </strong>— <a href="https://www.amazon.in/Django-Beginners-Build-websites-Python-ebook/dp/B079ZZLRRL/ref=sr_1_fkmr1_1?dchild=1&amp;keywords=Django+for+Beginners%3A+Build+Websites+with+Python+and+DjangoTwo+Scoop+of+Django&amp;qid=1606895427&amp;sr=8-1-fkmr1">Django for Beginners</a></p><p>This book is also written by William S. Vincent. This is the easiest way to start learning Django. The author makes sure that readers don’t feel boring while reading this book. This book is fast-paced and has easy flow to explain the topics. The transition of concepts from easy to difficult is smooth from chapter to chapter. We don’t need to have prior knowledge of Python and Django to learn from this book. The author has explained each topic in detail that encourages us to create basic applications. We wouldn’t need to read from other resources after buying this book. This book includes hello app to complex websites tutorial, and it follows an engaging structure and us seeking more.</p><h3>10. Practice Django 2 and Channels 2</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/250/0*E7WootxawhRO5FGg.jpg" /></figure><p><strong>Amazon </strong>— <a href="https://www.amazon.in/Practical-Django-Channels-Applications-Capabilities/dp/1484247043/ref=sr_1_1?dchild=1&amp;keywords=practical+django+2+and+channels+2&amp;qid=1606895546&amp;sr=8-1">Practice Django 2 and Channels 2</a></p><p>This book is written by <strong>Federico Marani</strong>. The best part of this book is for all learners. This book includes step and step guild that we can use to develop web applications. The author focuses on the make the boring technical topic interesting and includes large amount of information. This book understands the mindset perfectly. We may have doubts while this book, but it will be cleared as the book’s next thing. The author explores various aspects, such as e-commerce, banking, and finance. He also provides the use cases from each of these domains that developer can use guidance in their projects. In this book, we finds the Django channels that helps to solve problems related to event-driven programming using <strong>Redis, WebSocket, and Bootstrap.</strong> There are errors while doing code, but debugging is the best way to self-learn. We can find the complete working code on <a href="https://www.javatpoint.com/what-is-github">Github</a>, so errors are not so big deal. It is good investment of money; we will get the complete information related to Django.</p><h3>Django Books for Advance Programmers</h3><p>We have listed above few excellent Django books for beginners as well as experienced readers. The above books are quite effective to learn <strong>Django’s</strong> core concepts. However, we are defining few advance books for the programmers or have basic knowledge of Django. These books are given below.</p><h3>1. Build Your First Websites with Python and Django 1stEdition</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/266/0*4NImlpWL32rRNu9p.jpg" /></figure><p><strong>Amazon </strong>— <a href="https://www.amazon.in/Build-First-Website-Django-Fully-Functioning/dp/0994616864/ref=sr_1_1?dchild=1&amp;&amp;keywords=build+your+first+website+with+python+and+django+1st+edition&amp;&amp;qid=1606894731&amp;&amp;sr=8-1">Build Your First Websites</a></p><p>This book is written by Nigel George. This is the best book for programmers who work on Python and Django. This book is worth to build a solid foundation in Python. We will need many other resources because it doesn’t have much detail regarding topics. This is one of the best books for those who want to switch on Python and Django. Each topic is explained very nicely and includes many practical examples. In this book, we find step by step guidance to building a simple website.</p><h3>2. Learn Web Development with Python</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/250/0*xGJ81qFg9NXw2uB3.jpg" /></figure><p><strong>Amazon </strong>— <a href="https://www.amazon.in/Learn-Web-Development-Python-hands/dp/1789953294/ref=sr_1_2?crid=11TB57EF82MV9&amp;&amp;dchild=1&amp;&amp;keywords=learn+web+development+with+python&amp;&amp;qid=1606894879&amp;&amp;sprefix=Learn+Web+Development+with+%2Caps%2C344&amp;&amp;sr=8-2">Learn Web Development</a></p><p>This book is a comprehensive book to learn Python and Django simultaneously. The author covers simple topic firsts then moves to the complex topics of Django. In this book, we learn how to build a REST APIs and also learn how to build web application using Django. This book follows the practical approach to describe the topics. The author includes a step by step guide to develop a production website. If the reader belongs to a non-programmer background, he can take a short tutorial and start work with Django.</p><h3>Conclusion</h3><p>This article covers all excellent, effective, and useful books to learn Django with Python. Django has an extensive community across the world that solves many problems. Django also has the great-written documentation, but sometimes hard to follow. Good Books are the good option to enhance the knowledge of Django. We have figured out some excellent books for all types of learners. Some books have a very detailed explanation of topics and few have a full practical approach to describe the topics. You can choose any of books above mention to start learning Django.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=8ccbdd6d67cf" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[generate a Random StringPython Program to generate a Random String — Python Tutorial]]></title>
            <link>https://medium.com/@rajguleria3/generate-a-random-stringpython-program-to-generate-a-random-string-python-tutorial-b6a9c891bd6d?source=rss-c8873afac1d4------2</link>
            <guid isPermaLink="false">https://medium.com/p/b6a9c891bd6d</guid>
            <category><![CDATA[generate-a-random-string]]></category>
            <category><![CDATA[python]]></category>
            <category><![CDATA[python-programming]]></category>
            <category><![CDATA[python-program-generate]]></category>
            <category><![CDATA[generate-random-string]]></category>
            <dc:creator><![CDATA[Rajguleria]]></dc:creator>
            <pubDate>Tue, 17 Jan 2023 07:39:12 GMT</pubDate>
            <atom:updated>2023-01-17T07:39:12.713Z</atom:updated>
            <content:encoded><![CDATA[<h3>Python Program to generate a Random String — Python Tutorial</h3><p>&quot;Random&quot; refers to the collection of data or information that can be available in any order. The <a href="https://www.javatpoint.com/python-random-module"><strong>random</strong> module in python</a> is used to generate random strings. The random string is composed of numbers, characters, and punctuation that can contain any pattern. The random module contains two methods, <strong>random.choice()</strong> and <strong>secrets.choice()</strong>, to generate a secure string. Let’s understand how to generate a random string using the random.choice() and secrets.choice() methods in <a href="https://www.javatpoint.com/python-tutorial">python</a>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/600/0*cvBUzddaK6p-tICF.png" /></figure><h3>Using random.choice()</h3><p>The <strong>random.choice()</strong> function is used in the <a href="https://www.javatpoint.com/python-strings">python string</a> to generate the sequence of characters and digits that can repeat the string in any order.</p><p><strong>Create a program to generate a random string using the random.choices() function. function. Random_str.py</strong></p><pre>import string    <br>import random # define the random module  <br>S = 10  # number of characters in the string.  <br># call random.choices() string module to find the string in Uppercase + numeric data.  <br>ran = &#39;&#39;.join(random.choices(string.ascii_uppercase + string.digits, k = S))    <br>print(&quot;The randomly generated string is : &quot; + str(ran)) # print the random data  </pre><p><strong>Output:</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/812/0*Xq8xDm9CwFursStN.png" /></figure><p>Following are the methods used in the random module to generate the random string.</p><p>MethodsDescription</p><p><strong>String.ascii_letters</strong></p><p>It returns a random string that contains both uppercase and lowercase characters.</p><p><strong>String_ascii_uppercase</strong></p><p>It is a random string method that only returns a string in uppercase characters.</p><p><strong>String.ascii_lowercase</strong></p><p>It is a random string method that returns a string only in lowercase characters.</p><p><strong>String.digits</strong></p><p>It is a random string method that returns a string with numeric characters.</p><p><strong>String.punctuation</strong></p><p>It is a random string method that returns a string with punctuation characters.</p><p><strong>Generate a random string of upper case and lower-case lettersUprLwr.py</strong></p><pre># write a program to generate the random string in upper and lower case letters.  <br>import random  <br>import string  <br>def Upper_Lower_string(length): # define the function and pass the length as argument  <br>    # Print the string in Lowercase  <br>    result = &#39;&#39;.join((random.choice(string.ascii_lowercase) for x in range(length))) # run loop until the define length  <br>    print(&quot; Random string generated in Lowercase: &quot;, result)  <br>  <br>    # Print the string in Uppercase  <br>    result1 = &#39;&#39;.join((random.choice(string.ascii_uppercase) for x in range(length))) # run the loop until the define length  <br>    print(&quot; Random string generated in Uppercase: &quot;, result1)  <br>  <br>Upper_Lower_string(10) # define the length  </pre><p><strong>Output:</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/760/0*FjjZMnmOTbtKrWDa.png" /></figure><h3>Random String of Specified Characters</h3><p><strong>Specific.py</strong></p><pre># create a program to generate the random string of given letters.  <br>import random  <br>import string  <br>def specific_string(length):  <br>    sample_string = &#39;pqrstuvwxy&#39; # define the specific string  <br>    # define the condition for random string  <br>    result = &#39;&#39;.join((random.choice(sample_string)) for x in range(length))  <br>    print(&quot; Randomly generated string is: &quot;, result)  <br>  <br>specific_string(8) # define the length  <br>specific_string(10) </pre><p><strong>Output:</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/769/0*hwVnDwqs_HeA6uGn.png" /></figure><h4>Note: The random.choice() method is used in the python program to repeat the same characters strings. If we don’t want to display repetitive characters, we should use random.sample() function.</h4><p><strong>Generate a random string without repeating the same charactersWithoutRepeat.py</strong></p><pre># create a program to generate a string with or without repeating the characters.  <br>import random  <br>import string  <br>print(&quot;Use of random.choice() method&quot;)  <br>def specific_string(length):  <br>     <br>    letters = string.ascii_lowercase # define the lower case string  <br>     # define the condition for random.choice() method  <br>    result = &#39;&#39;.join((random.choice(letters)) for x in range(length))  <br>    print(&quot; Random generated string with repetition: &quot;, result)  <br>  <br>specific_string(8) # define the length  <br>specific_string(10)  <br>  <br>  <br>print(&quot;&quot;) # print the space  <br>print(&quot;Use of random.sample() method&quot;)  <br>def WithoutRepeat(length):  <br>    letters = string.ascii_lowercase # define the specific string  <br>    # define the condition for random.sample() method  <br>    result1 = &#39;&#39;.join((random.sample(letters, length)))   <br>    print(&quot; Random generated string without repetition: &quot;, result1)  <br>  <br>WithoutRepeat(8) # define the length  <br>WithoutRepeat(10) </pre><p><strong>Output:</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/820/0*gZjAkvOFB96RvM21.png" /></figure><p>As we can see in the above output, the random.sample() method returns a string in which all characters are unique and non-repeating. Whereas, the random.choice() method returns a string that may contain repetitive characters. So, we can say that if we want to generate a unique random string, use <strong>random.sample</strong>() method.</p><h3>Generate a random alphanumeric string consisting of fixed letters and digits</h3><p>For example, suppose we want a randomly generated alphanumeric string that contains five letters and four digits. We need to define these parameters into the function.</p><p>Let’s write a program to generate an alphanumeric string that contains a fixed number of letters and digits.</p><p><strong>fixedString.py</strong></p><pre>import random  <br>import string  <br>def random_string(letter_count, digit_count):  <br>    str1 = &#39;&#39;.join((random.choice(string.ascii_letters) for x in range(letter_count)))  <br>    str1 += &#39;&#39;.join((random.choice(string.digits) for x in range(digit_count)))  <br>  <br>    sam_list = list(str1) # it converts the string to list.  <br>    random.shuffle(sam_list) # It uses a random.shuffle() function to shuffle the string.  <br>    final_string = &#39;&#39;.join(sam_list)  <br>    return final_string  <br>  <br># define the length of the letter is eight and digits is four  <br>print(&quot;Generated random string of first string is:&quot;, random_string(8, 4))  <br>  <br># define the length of the letter is seven and digits is five  <br>print(&quot;Generated random string of second string is:&quot;, random_string(7, 5))  </pre><p><strong>Output:</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/792/0*rJL_iPigkydyNbva.png" /></figure><h3>Using secrets.choice()</h3><p>A secrets.choice() method is used to generate a more secure random string than random.choice(). It is a cryptographically random string generator that ensures no two processes can obtain the same results simultaneously using secrets.choice() method.</p><p>Let’s write a program to print a secure random string using the secrets.choice method.</p><p><strong>Secret_str.py</strong></p><pre>import random   <br>import string  <br>import secrets # import package  <br>num = 10 # define the length of the string  <br># define the secrets.choice() method and pass the string.ascii_letters + string.digits as an parameters.  <br>res = &#39;&#39;.join(secrets.choice(string.ascii_letters + string.digits) for x in range(num))  <br>  <br># print the Secure string   <br>print(&quot;Secure random string is :&quot;+ str(res))  </pre><p><strong>Output:</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/782/0*CkHc6XPOG-o60fKW.png" /></figure><h3>Use the different method of the random module to generate a safe random string.</h3><p>Let’s write a program to print secure random strings using different methods of secrets.choice().</p><p><strong>Secret.py</strong></p><pre># write a program to display the different random string method using the secrets.choice().  <br># imports necessary packages  <br>import random   <br>import string  <br>import secrets  <br>num = 10 # define the length of the string  <br># define the secrets.choice() method and pass the string.ascii_letters + string.digits as an parameters.  <br>res = &#39;&#39;.join(secrets.choice(string.ascii_letters + string.digits) for x in range(num))  <br># Print the Secure string with the combination of ascii letters and digits  <br>print(&quot;Secure random string is :&quot;+ str(res))  <br>  <br>res = &#39;&#39;.join(secrets.choice(string.ascii_letters) for x in range(num))  <br># Print the Secure string with the combination of ascii letters   <br>print(&quot;Secure random string is :&quot;+ str(res))  <br>  <br>res = &#39;&#39;.join(secrets.choice(string.ascii_uppercase) for x in range(num))  <br># Print the Secure string in Uppercase  <br>print(&quot;Secure random string is :&quot;+ str(res))  <br>  <br>res = &#39;&#39;.join(secrets.choice(string.ascii_lowercase) for x in range(num))  <br># Print the Secure string in Lowercase  <br>print(&quot;Secure random string is :&quot;+ str(res))  <br>  <br>res = &#39;&#39;.join(secrets.choice(string.ascii_letters + string.punctuation) for x in range(num))  <br># Print the Secure string with the combination of letters and punctuation  <br>print(&quot;Secure random string is :&quot;+ str(res))  <br>  <br>res = &#39;&#39;.join(secrets.choice(string.digits) for x in range(num))  <br># Print the Secure string using string.digits  <br>print(&quot;Secure random string is :&quot;+ str(res))  <br>  <br>res = &#39;&#39;.join(secrets.choice(string.ascii_letters + string.digits + string.punctuation) for x in range(num))  <br># Print the Secure string with the combonation of letters, digits and punctuation   <br>print(&quot;Secure random string is :&quot;+ str(res))  </pre><p><strong>Output:</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/752/0*u4tjB_0cCPiWJl5G.png" /></figure><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=b6a9c891bd6d" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How to One Hot Encode Sequence Data in Python — Python Tutorial]]></title>
            <link>https://medium.com/@rajguleria3/how-to-one-hot-encode-sequence-data-in-python-python-tutorial-8bd1e3d89dd6?source=rss-c8873afac1d4------2</link>
            <guid isPermaLink="false">https://medium.com/p/8bd1e3d89dd6</guid>
            <category><![CDATA[tutorial-python]]></category>
            <category><![CDATA[python]]></category>
            <category><![CDATA[python-programming]]></category>
            <category><![CDATA[encode-sequence-python]]></category>
            <dc:creator><![CDATA[Rajguleria]]></dc:creator>
            <pubDate>Tue, 17 Jan 2023 07:25:18 GMT</pubDate>
            <atom:updated>2023-01-17T07:25:18.507Z</atom:updated>
            <content:encoded><![CDATA[<h3>How to One Hot Encode Sequence Data in Python — Python Tutorial</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*cxgeUiK68E52dOoA" /><figcaption>Photo by <a href="https://unsplash.com/@ffstop?utm_source=medium&amp;utm_medium=referral">Fotis Fotopoulos</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>In this tutorial, we will learn to convert our input or output sequence data to a one-hot encoding for use in sequence classification.</p><p>One Hot Encoding is a useful feature of machine learning because few Machine learning algorithms cannot work with categorical data directly. While working with the datasets, we come across the column that holds no specific order of preference.</p><p>If we are working with a sequence classification type problem, the categorical data must be converted to numbers. This technique is also used when we work with deep learning methods such as Long Short-term Memory recurrent neural networks.</p><p>First, we will discuss the Categorical Data.</p><h3>What is Categorical Data?</h3><p>Categorical Data are the types of variables that have the label value rather than numerical values. These types of variables are also called nominal. Let’s see the following example of categorical data.</p><ul><li>A “<em>car</em>” variable with the values: “<em>Maruti</em>” and “<em>Jaguar</em>”.</li><li>A “<em>food</em>” variable with the values: “<em>Veg</em>”, and “<em>Non-Veg</em>”.</li><li>A “<em>place</em>” variable with the values: “first”, “<em>second</em>”, and “<em>third</em>”.</li></ul><p>As we can see in the above code, some categories may have a natural relationship such as natural ordering. In the third example, the “place” variable has a natural ordering of values.</p><h3>Problem with Categorical Data</h3><p>Some machine learning algorithms have the ability to work with categorical data directly. A few algorithms cannot operate on the label data directly because they require all the data variables and output variables to be numeric.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/650/0*uOAFJ7ZIJKmNxuir.png" /></figure><p>Therefore, we have to convert hierarchical data into numerical form. Suppose the categorical variable is an output variable. In that case, you may also want to change forecasts by the model back into a categorical form to represent them or use them in some application.</p><h3>How to Convert Categorical Data to Numeric Data</h3><p>There are two methods that use to convert categorical data into numerical data.</p><ul><li>Integer Encoding</li><li>One-Hot Encoding</li></ul><p>In the next section, we will discuss <strong>One-Hot Encoding</strong>.</p><h3>What is One Hot Encoding?</h3><p>A one hot encoding is used to convert the categorical variables into numeric values. Before doing further data analysis, the categorical values are mapped to integer values. Each column contains “0” or “1” corresponding to which column it has been placed. In this process, each integer value is represented as a binary vector that is all zero expect the index of the integer, which is marked with a 1.</p><h3>Example of a One Hot Encoding</h3><p>Let’s understand it by using the following simple example.</p><p>Suppose we have a sequence of labels with the value ‘yellow’ and ‘red.’ To convert them into the numerical value, we assign ‘yellow’ an integer value 1 to corresponding to its number of categories present in column and ‘red’ as 0. When we encounter these labels, we will assign same integer value. It is called an integer encoding.</p><p>Let’s see another example — Suppose there is a category called animal and it has fours values — Cat, Dog, Cow and Camel. Consider the following table which consists of animals and their corresponding categorical values.</p><h3>Why use a One Hot Encoding?</h3><p>One of the best advantages of One-Hot encoding is that it makes categorical data more expressive. As we discussed earlier, many machine learning algorithms cannot work directly with categorical data, so it needs to be converted into an integer.</p><p>We can use the integer value directly or where it is needed. It can solve the problem where the natural ordinal has a relationship between the categories. For example, we can assign the integer values to the <strong>“weather”</strong> label, such as &quot;winter,&quot; &quot;summer,&quot; and &quot;monsoon.&quot;</p><p>But there may be problems if no ordinal relationship is found. If we allow the representation to lean or any such relationship, it might be damaged the learning to solve problems.</p><h3>Manual One Hot Encoding</h3><p>In the following example, we will consider an example string of alphabetic letters that will be converted into an integer value.</p><pre>hello world </pre><p>Now, we will implement one hot code change to the above-given string value. Let’s see the following example:</p><p><strong>Example -</strong></p><pre>from numpy import argmax  <br># Here we are define input string  <br>str_data = &#39;hello python&#39;  <br>print(str_data)  <br># Here we are defining possible input values of english alphabate  <br>eng_alphabet = &#39;abcdefghijklmnopqrstuvwxyz &#39;  <br># define a mapping of chars to integers  <br>char_to_int = dict((c, i) for i, c in enumerate(eng_alphabet))  <br>int_to_char = dict((i, c) for i, c in enumerate(eng_alphabet))  <br># input data is encoding in integer  <br>int_encoded = [char_to_int[char] for char in data]  <br>print(int_encoded)  <br># one hot encode  <br>onehot_encoded = list()  <br>for value in int_encoded:  <br>  letter = [0 for _ in range(len(eng_alphabet))]  <br>  letter[value] = 1  <br>  onehot_encoded.append(letter)  <br>print(onehot_encoded)  <br># invert encoding  <br>inverted = int_to_char[argmax(onehot_encoded[0])]  <br>print(inverted)  </pre><p><strong>Output:</strong></p><pre>hello python<br><br>[7, 4, 11, 11, 14, 26, 15, 24, 19, 7, 14, 13]<br><br>[[0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], <br>[0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], <br>[0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], <br>[0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], <br>[0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0],<br> [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1], <br>[0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], <br>[0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0],<br>[0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0], <br>[0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], <br>[0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], <br>[0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]]</pre><p><strong>Explanation:</strong></p><p>In the above code, we have declared the input string and printed it. Next, we defined the universe of possible input values. Then, a mapping of all possible inputs is created from the char values to integer values. We used this mapping to encode the input string.</p><p>As we can see in the above output, the first letter <strong>h</strong> is encoded as 7. Then, this integer coding is converted to the one-hot encoding. One integer encodes one character at a time.</p><p>Each character has a specific index value; we marked the index of a specific character as 1. The first character is represented as a 7 in the binary vector of 27. We marked the 7th index as 1 for h.</p><p>Now, we will learn to implement one hot coding using the <strong>scikit-learn</strong> library.</p><h3>One Hot Encode using Scikit-learn</h3><p>In this example, let’s assume the following output sequence for the three labels:</p><pre>&quot;apple&quot;  <br>&quot;mango&quot;  <br>&quot;banana&quot;  </pre><p>An example sequence of 10 time steps may be</p><pre>apple, apple, mango, apple, banana, banana, mango, apple.  </pre><p>We assign an integer value to the above labels, such as 1, 2, or 3. In the one-hot encoding, we will use a binary vector with 3 values, such as [1, 0, 0]. The sequence includes at least one example of one possible value in the sequence.</p><p>We will use the Scikit-Learn library. We will use the <strong>LabelEncoder</strong> module from it for creating an integer encoding of labels and <strong>OneHotEncoder</strong> for creating a one-hot encoding of an integer encoded value.</p><p>Let’s understand the following example:</p><p><strong>Example -</strong></p><pre>from numpy import array  <br>from numpy import argmax  <br>from sklearn.preprocessing import LabelEncoder  <br>from sklearn.preprocessing import OneHotEncoder  <br># defining sequence example  <br>data_1 = [&#39;apple&#39;, &#39;apple&#39;, &#39;mango&#39;, &#39;apple&#39;, &#39;banana&#39;, &#39;banana&#39;, &#39;mango&#39;, &#39;apple&#39;]  <br>values_of_seq = array(data_1)  <br>print(values_of_seq)  <br># first appling integer encode  <br>label_encoder = LabelEncoder()  <br>integer_encoded = label_encoder.fit_transform(values_of_seq)  <br>print(integer_encoded)  <br># Now doing binary encode  <br>onehot_encoder = OneHotEncoder(sparse=False)  <br>integer_encoded = integer_encoded.reshape(len(integer_encoded), 1)  <br>onehot_encoded = onehot_encoder.fit_transform(integer_encoded)  <br>print(onehot_encoded)  </pre><p><strong>Output:</strong></p><pre>[&#39;apple&#39; &#39;apple&#39; &#39;mango&#39; &#39;apple&#39; &#39;banana&#39; &#39;banana&#39; &#39;mango&#39; &#39;apple&#39;]<br>[0 0 2 0 1 1 2 0]<br>[[1. 0. 0.]<br> [1. 0. 0.]<br> [0. 0. 1.]<br> [1. 0. 0.]<br> [0. 1. 0.]<br> [0. 1. 0.]<br> [0. 0. 1.]<br> [1. 0. 0.]]</pre><p><strong>Explanation -</strong></p><p>In the above code, first, we have printed the sequence of labels. Then, we performed integer encoding, and finally, one-hot encoding. The OneHotEncoder class returns well-organized sparse encoding. But this is not efficient for the some application such as use with keras library.</p><h3>One Hot Encoding with Keras</h3><p>Let’s suppose we have a sequence that is already integer-encoded. We can work with the integer encoding directly or map the integer encoding onto the label values. We can use the <strong>to_categorical()</strong> function to encode integer data.</p><p>In this example, we have five integer values [0, 1, 2, 3, 4], and we have an input sequence of the following 15 numbers:</p><pre>data_1 = [1, 4, 3, 3, 0, 3, 2, 2, 4, 0, 1, 2, 1, 4, 3]  </pre><p>Let’s understand the following example:</p><p><strong>Example -</strong></p><pre>from numpy import array  <br>from numpy import argmax  <br>from keras.utils import to_categorical  <br># define example  <br>data_1 = [1, 4, 3, 3, 0, 3, 2, 2, 4, 0, 1, 2, 1, 4, 3]  <br>data = array(data_1)  <br>print(data)  <br># one hot encoding using the to_categorical() method  <br>encoded = to_categorical(data)  <br>print(encoded)  <br># invert encoding  <br>inverted = argmax(encoded[0])  <br>print(inverted)  </pre><p><strong>Output:</strong></p><pre>[1 4 3 3 0 3 2 2 4 0 1 2 1 4 3]<br>[[0. 1. 0. 0. 0.]<br> [0. 0. 0. 0. 1.]<br> [0. 0. 0. 1. 0.]<br> [0. 0. 0. 1. 0.]<br> [1. 0. 0. 0. 0.]<br> [0. 0. 0. 1. 0.]<br> [0. 0. 1. 0. 0.]<br> [0. 0. 1. 0. 0.]<br> [0. 0. 0. 0. 1.]<br> [1. 0. 0. 0. 0.]<br> [0. 1. 0. 0. 0.]<br> [0. 0. 1. 0. 0.]<br> [0. 1. 0. 0. 0.]<br> [0. 0. 0. 0. 1.]<br> [0. 0. 0. 1. 0.]]<br>1</pre><p><strong>Explanation -</strong></p><p>In the above code, we have encoded the integers as binary vectors and printed them. Then, we used the Numpy <strong>argmax()</strong> function to invert the encoding on the first value in the sequence.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=8bd1e3d89dd6" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How to write square root in Python — Python Tutorial]]></title>
            <link>https://medium.com/@rajguleria3/how-to-write-square-root-in-python-python-tutorial-528218b2c65f?source=rss-c8873afac1d4------2</link>
            <guid isPermaLink="false">https://medium.com/p/528218b2c65f</guid>
            <category><![CDATA[wri-square-root-in-python]]></category>
            <category><![CDATA[square-root-in-python]]></category>
            <category><![CDATA[python3]]></category>
            <category><![CDATA[write-square-root-python]]></category>
            <category><![CDATA[tutorial-python]]></category>
            <dc:creator><![CDATA[Rajguleria]]></dc:creator>
            <pubDate>Tue, 17 Jan 2023 07:12:59 GMT</pubDate>
            <atom:updated>2023-01-17T07:12:59.614Z</atom:updated>
            <content:encoded><![CDATA[<h3>How to write square root in Python — Python Tutorial</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*utbWGBlgaiiRiYmd" /><figcaption>Photo by <a href="https://unsplash.com/@ffstop?utm_source=medium&amp;utm_medium=referral">Fotis Fotopoulos</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>Python has a predefined function that returns the square root of a number. It defines the square root of a value that multiplies itself to give a number. The <strong>sqrt()</strong> function is not used directly to find the square root of a given number, so we need to use a <strong>math</strong> module to call the <strong>sqrt()</strong> function in <a href="https://www.javatpoint.com/python-tutorial">Python</a>.</p><p>For example, the square root of 144 is 12.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/500/0*lz6ZABRXYfTMh_DS.png" /></figure><h3>Using math.sqrt() method</h3><p>The sqrt() function is an inbuilt function that returns the square root of any number. Following are the steps to find the square root of a number.</p><ol><li>Start the program</li><li>Define any number whose square root to be found.</li><li>Invoke the <strong>sqrt()</strong> function and pass the value that you have defined in step 2 and store the result in a variable.</li><li>Print the square root.</li><li>Terminate the program.</li></ol><p>Let’s create a Python program to find the square root of a number.</p><p><strong>SqrRoot.py</strong></p><pre>import math # import math module  <br>N = 25 # define the value to the variable N   <br>result = math.sqrt(N) # use math.sqrt() function and pass the variable.  <br>print(&quot; Square root of 25 is :&quot;, result) # prints the square root of a given number   <br>M = 625 # define the value  <br>result = math.sqrt(M) # use math.sqrt() function and pass the variable  <br>print(&quot; Square root of 625 is :&quot;, result) # prints the square root of a given number   <br>  <br>P = 144 # define the value  <br>result = math.sqrt(P) # use math.sqrt() function and pass the variable  <br>print(&quot; Square root of 144 is :&quot;, result) # prints the square root of a given number   <br>  <br>S = 64 # define the value  <br>result = math.sqrt(S) # use math.sqrt() function and pass the variable  <br>print(&quot; Square root of 64 is :&quot;, result) # prints the square root of a given number  </pre><p><strong>Output:</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/635/0*Gy1sfPVthk2pHMQR.png" /></figure><p>Let’s create a python program that finds the square root of a decimal numbers.</p><p><strong>SqrRoot.py</strong></p><pre>import math  <br>print(&quot; The Square root of 4.5 is&quot;, math.sqrt(4.5)) # Pass the decimal number  <br>print(&quot; The Square root of 627 is&quot;, math.sqrt(627)) # Pass the decimal number  <br>print(&quot; The Square root of 6.25 is&quot;, math.sqrt(6.25)) # Pass the decimal number  <br>  <br>print(&quot; The Square root of 0 is&quot;, math.sqrt(0)) # Pass number as 0  </pre><p><strong>Output:</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/549/0*wAJHtq9j-JoFtWDC.png" /></figure><p>In the following program, we have read a number form the user and find the square root.</p><p><strong>SqRoot_Usr.py</strong></p><pre>import math # import math module  <br>a = int(input(&quot;Enter a number to get the Square root&quot;)) # take an input   <br>res = math.sqrt(a) # Use math.sqrt() function and pass the variable a.  <br>print(&quot;Square root of the number is&quot;, res) # print the Square Root  </pre><p><strong>Output:</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/610/0*lR2PrZAN2V3cUqZz.png" /></figure><h3>Using math.pow() function</h3><p>The <strong>pow()</strong> is an inbuilt function that is used in Python to return the power of a number. It has two parameters. The first parameter defines the number and second parameter defines the power raise to that number.</p><p><strong>Pow_Sqrt.py</strong></p><pre>import math # import the math module  <br>num = float(input(&quot;Enter the number :&quot;)) # take an input  <br>SquareRoot = math.pow(num, 0.5) # Use the math.pow() function and pass the value and 0.5 (which is equal to √) as an parameters  <br>print(&quot; The Square Root of the given number {0} = {1}&quot; .format(num, SquareRoot)) # print the Square Root.  </pre><p><strong>Output:</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/662/0*rOgw3t5FjiGQ-QQC.png" /></figure><h3>Using ** Operator</h3><p>We can also use the exponent operator to find the square root of the number. The operator can be applied between two operands. For example, x**y. It means that left operand raised to the power of right.</p><p>Following are the steps to find the square root of a number.</p><p><strong>Step 1</strong>. Define a function and pass the value as an argument.</p><p><strong>Step 2</strong>. If the defined number is less than 0 or negative, it returns nothing.</p><p><strong>Step 3</strong>. Use the exponential ** sign to find the power of a number.</p><p><strong>Step 4</strong>. Take the numeric value from the user.</p><p><strong>Step 5</strong>. Call the function and store its output to a variable.</p><p><strong>Step 6</strong>. Display the Square Root of a number in Python.</p><p><strong>Step 7</strong>. Exit from the program.</p><p>Let’s implement the above steps in a Python program and calculate the square root of a number.</p><p><strong>SqrtFun.py</strong></p><pre>import math # import the math package or module  <br>def sqrt_fun(num): # define the sqrt_fun() and pass the num as an argument  <br>    if num &lt; 0:  # if num is less than 0 or negative, it returns nothing  <br>        return  <br>    else:  <br>        return num ** 0.5 # Use the exponent operator   <br>num = int(input (&quot; Enter a numeric value: &quot;) ) # take an input from the user  <br>  <br>res = sqrt_fun(num) # call the sqrt_fun() to find the result  <br>print(&quot;  Square Root of the {0} = {1}&quot;.format(num, res)) # print the Square Root of the variable </pre><p><strong>Output:</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/626/0*6wDQ3CKhOUPN2KjH.png" /></figure><p>As we can see in the above example, first we take an input (number) from the user and then use the exponent ** operator to find out the power of a number. Where 0.5 is equal to √ (root symbol) to raise the power of a given number.</p><p>Let’s create a Python program that finds the square root of between the specified range. In the following program, we have found the square root of all the number between 0 to 50.</p><p><strong>Sqrloop.py</strong></p><pre>import math  <br>for i in range(50):  <br>    print(&quot;Square root of a number {0} = {1}&quot;.format(i,math.sqrt(i)))  </pre><p><strong>Output:</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/652/0*EqBv0kiepov-_ITg.png" /></figure><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=528218b2c65f" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Pointer in Python | Why Python doesn’t support pointer]]></title>
            <link>https://medium.com/@rajguleria3/pointer-in-python-why-python-doesnt-support-pointer-c11e164cf299?source=rss-c8873afac1d4------2</link>
            <guid isPermaLink="false">https://medium.com/p/c11e164cf299</guid>
            <category><![CDATA[why-python-pointer]]></category>
            <category><![CDATA[python]]></category>
            <category><![CDATA[python3]]></category>
            <category><![CDATA[pointer-in-python]]></category>
            <category><![CDATA[pointer-python]]></category>
            <dc:creator><![CDATA[Rajguleria]]></dc:creator>
            <pubDate>Tue, 17 Jan 2023 07:08:26 GMT</pubDate>
            <atom:updated>2023-01-17T07:08:26.321Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*2NvgYE-vIKykibit" /><figcaption>Photo by <a href="https://unsplash.com/@pakata?utm_source=medium&amp;utm_medium=referral">Pakata Goh</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>In this tutorial, we will learn about pointers in Python and see why Python doesn’t support pointer concepts.</p><p>We will also understand how we can simulate the pointer in Python. Below is an introduction to the pointer for those who don’t know anything about it.</p><p>We will also understand how we can simulate the pointer in Python. Below is the introduction of pointer for those who don’t have any about it.</p><h3>What is Pointer?</h3><p>Pointer is a very popular and useful tool to store the address of a variable. If someone has ever worked with a low-level language such as <a href="https://www.javatpoint.com/c-programming-language-tutorial">C</a>. <a href="https://www.javatpoint.com/cpp-tutorial">C++</a>, he or she is probably familiar with pointers. It manages the code very efficiently. It can be slightly tough for beginners, but it is an important concept in the program. However, it can lead to various memory management bugs. Thus, the definition of pointers -</p><p><strong>“Pointers are the variables that hold the memory address of another variable.&quot; Pointer variables are represented by an asterisk (*).</strong></p><p>Let’s see the following example of the pointer in the C programming language.</p><p><strong>Example — How to use pointer in C</strong></p><pre>#include &lt;stdio.h&gt;  <br>int main()  <br>{  <br>   int* po, o;  <br>     <br>   0 = 10;  <br>   printf(&quot;Address of c: %p\n&quot;, &amp;c);  <br>   printf(&quot;Value of c: %d\n\n&quot;, c);    <br>     <br>   o = &amp;0;  <br>   printf(&quot;Address of pointer pc: %p\n&quot;, o);  <br>   printf(&quot;Content of pointer pc: %d\n\n&quot;, *o);     <br>   0 = 11;  <br>   printf(&quot;Address of pointer pc: %p\n&quot;, p0);  <br>   printf(&quot;Content of pointer pc: %d\n\n&quot;, *p0);     <br>   *po = 2;  <br>   printf(&quot;Address of c: %p\n&quot;, &amp;o);  <br>   printf(&quot;Value of c: %d\n\n&quot;, o);  <br>   return 0;  <br>}  </pre><p><strong>Output:</strong></p><pre>Address of o: 2686784<br>Value of o: 22<br><br>Address of pointer po: 2686784<br>Content of pointer po: 22<br><br>Address of pointer po: 2686784<br>Content of pointer po: 11<br><br>Address of o: 2686784<br>Value of o: 2</pre><p>Besides being useful, pointers are not used in <a href="https://www.javatpoint.com/python-tutorial">Python</a>. In this topic, we will discuss Python’s object model and learn why pointers in Python don’t exist. We will also learn different ways to simulate pointers in Python. First, let’s discuss why Python doesn’t support pointers.</p><h3>Why Doesn’t Python Support Pointers</h3><p>The exact reason for not supporting the pointer is not clear. Could pointers in Python exist natively? The main concept of Python is its simplicity, but pointers violate the <strong>Zen of Python.</strong> Pointers are mainly encouraged as implicit changes rather than explicit ones. They are also complex, especially for beginners.</p><p>Pointers tend to create complexity in the code, whereas Python mainly focuses on usability rather than speed. As a result, Python doesn’t support pointers. However, Python gives some benefits of using the pointer.</p><p>Before understanding the pointer in Python, we need to have a basic idea of the following points:</p><ul><li>Immutable vs. mutable objects</li><li>Python variables/names</li></ul><h3>Objects in Python</h3><p>In Python, everything is an object, even classes, functions, variables, etc. Each object contains at least three pieces of data.</p><ul><li>Reference count</li><li>Type</li><li>Value</li></ul><p>Let’s discuss one by one.</p><p><strong>Reference Count: </strong>It is used for memory management. To get more information regarding Python memory management, read Memory Management in Python.</p><p><strong>Type—T</strong>The <strong>CPython</strong> layer is used as the type to ensure type safety during runtime. Finally, there is a value, which is the actual value associated with the object.</p><p>If we go into depth with this object, we will find that not all objects are the same. The important distinction between the types of objects is between immutable and mutable. First of all, we need to understand the difference between the types of objects because it explores the pointer in Python.</p><h3>Understanding Python Variables</h3><p>The way of defining variables in Python is much different than the C or C++. A Python variable doesn’t define the data type. In fact, Python has names, not variables.</p><p>So we need to understand the difference between variables and names, and this is especially true when we are navigating the tricky subject of pointers in Python.</p><p>Let’s understand how the variable works in C and how the name works in Python.</p><h3>Variables in C</h3><p>In C language, a variable is that it holds value or store value. It is defined by the data type. Let’s see the following code that defines the variable:</p><pre>int x = 286;  </pre><ul><li>Allocate enough memory for an integer.</li><li>We assign the value 286 to that memory location.</li><li>The x represents that value.</li></ul><p>If we represent the view of memory -</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/253/0*dIRue6NWc7JvTljm.png" /></figure><p>As we can see, the x has a memory location for the value 286. Now, we will assign the new value to x.</p><p>x = 250</p><p>This new value overwrites the previous value. It means that the variable x is mutable.</p><p>The value location of x is same, but the value changed. It is a significant point indicating that x is the memory location, not just its name.</p><p>Now, we introduce the new variable that takes the x, and the y creates the new memory box.</p><pre>int y = x;  </pre><p>The variable y creates a new box called y and copies the value of x into the box.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/621/0*pKUe1gnuOGKrUJDh.png" /></figure><h3>Names in Python</h3><p>As we discussed earlier, Python doesn’t have variables. It has names, and we use this term as the variables. But there is a difference between variables and names. Let’s see the following example:</p><pre>x = 289  </pre><p>The above code is broken down during execution.</p><ol><li>Create a PyObject</li><li>Set the typecode to integer for the PyObject</li><li>Set the value to 289 for the PyObject</li><li>Create a name called x</li><li>Point x to the new PyObject</li><li>Increase the refcount of the PyObject by 1</li></ol><p>It will look like as below.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/521/0*pZPA5HiR9sGmW6V1.png" /></figure><p>We can understand the internal workings of a variable in Python. The variable x points to the reference of the object, and it doesn’t have the same memory space as before. It also shows that x = 289 is binding the name x to a reference.</p><p>Now, we introduce a new variable and assign x to it.</p><pre>y = x  </pre><p>In Python, The variable y will not create the new object; it is just a new name pointing to the same object. The object <strong>reference countthe</strong> also increased by one. We can confirm it as follows:</p><pre>y is x  </pre><p><strong>Output:</strong></p><pre>True</pre><p>If we increase the value of y by one, it will no longer refer to the same object.</p><pre>y + =1  <br>y is x  </pre><p>That means, in Python, we don’t assign variables. Instead, we bind names to references.</p><h3>Simulating Pointers in Python</h3><p>As we have discussed, Python doesn’t support pointers, but we can get the benefits of using a pointer. Python provides alternative ways to use the pointer in Python. These two ways are given below.</p><ul><li>Using mutable types as pointers</li><li>Using custom Python objects</li></ul><p>Let’s understand the given points.</p><h3>Using Mutable Types as Pointer</h3><p>In the previous section, we defined the mutable type objects; we can treat them as if they were pointers to simulate pointer behavior. Let’s understand the following example:</p><p>C</p><pre>void add_one(int *a) {  <br>    *a += 1;  <br>}  </pre><p>In the above code, we defined pointer *a, then we incremented the value by one. Now, we will implement it with the main() function.</p><pre>#include &lt;stdio.h&gt;  <br>  <br>int main(void) {  <br>    int y = 233;  <br>    printf(&quot;y = %d\n&quot;, y);  <br>    add_one(&amp;y);  <br>    printf(&quot;y = %d\n&quot;, y);  <br>    return 0;  <br>}  </pre><p><strong>Output:</strong></p><pre>y = 233<br>y = 234</pre><p>We can simulate this type of behavior by using the Python mutable type. Understand the following example.</p><pre>def add_one(x):  <br>    x[0] += 1  <br>  <br>y = [2337]  <br>add_one(y)  <br>y[0]  </pre><p>The above function accesses the first element of the list and increments its value by one. When we execute the above program, it prints the modified value of y. It means we can replicate the pointer using the mutable object. But if we try to simulate a pointer using an immutable object,</p><pre>z = (2337,)  <br>add_one(z)  </pre><p><strong>Output:</strong></p><pre>Traceback (most recent call last):<br>  File &quot;&quot;, line 1, in <br>  File &quot;&quot;, line 2, in add_one<br>TypeError: &#39;tuple&#39; object does not support item assignment</pre><p>We used a tuple, an immutable object, in the above code, so it returned the error. We can also use the dictionary to simulate the pointer in Python.</p><p>Let’s understand the following example, where we will count every operation that occurs in the program. We can use dict to achieve this.</p><p><strong>Example -</strong></p><pre>count = {&quot;funcCalls&quot;: 0}  <br>def car():  <br>    count[&quot;funcCalls&quot;] += 1  <br>  <br>def foo():  <br>    count[&quot;funCcalls&quot;] += 1  <br>    car()  <br>  <br>foo()  <br>count[&quot;funcCalls&quot;]  </pre><p><strong>Output:</strong></p><pre>2</pre><p><strong>Explanation -</strong></p><p>In the above example, we used the <strong><em>count</em></strong> dictionary, which kept track of the number of function calls. When the <strong>foo()</strong> function is called, the counter is increased by 2 because dict is mutable.</p><h3>Using Python Objects</h3><p>In the previous example, we have used dict to emulate the pointer in Python, but sometimes it becomes difficult to remember all used key names. We can use the Python custom class in place of the dictionary. Let’s understand the following example:</p><p><strong>Example -</strong></p><pre>class Pointer(object):  <br>    def __init__(self):  <br>        self._metrics = {  <br>            &quot;funCalls&quot;: 0,  <br>            &quot;catPictures&quot;: 0,  <br>        }  </pre><p>In the above code, we have defined the Pointer class. This class used a dictionary to hold actual data in the _metrics member variable. It will provide mutability to our program. We can do this as follows:</p><pre>class Pointer(object):  <br>    # ...  <br>  <br>    @property  <br>    def funCalls(self):  <br>        return self._metrics[&quot;func_calls&quot;]  <br>  <br>    @property  <br>    def catPictures_served(self):  <br>        return self._metrics[&quot;cat_pictures_served&quot;]  </pre><p>We have used the <strong><em>@property</em></strong> decorator. If you aren’t familiar with decorators, visit our Python decorator tutorial. The @property decorator will access funCalls and catPicture_served. Now, we will create an object of the Pointer class.</p><p>Here, we need to increment these values.</p><p>We have defined two new methods: increment() and cat_pics(). We have modified the values using these functions in the matrices. Here, we can change the class the same way we are modifying the pointer.</p><pre>pt = Pointer()  <br>pt.funCalls()  <br>pt.catPicture_served  </pre><h3>Python ctypes Module</h3><p>The Python ctypes module allows us to create a C-type pointer in Python. This module is helpful if we want to make a function call to a C library that requires a pointer. Let’s understand the following example:</p><p><strong>Example — C Language</strong></p><pre>void incr_one(int *x) {  <br>    *x += 1;  <br>}  </pre><p>In the above function, we have incremented the value of x by one. Suppose we save the above file, named incrPointer.c, and type the following command in the terminal.</p><pre>$ gcc -c -Wall -Werror -fpic incrPointer.c  <br>$ gcc -shared -o libinc.so incrPointer.o  </pre><p>The first command compiles <strong>incrPointer.c</strong> into an object called <strong>incrPointer.o.</strong> The second command accepts an object file and produces libinic.so to collaborate with ctypes.</p><pre>import ctypes  <br>##  libinc.so library should be same directory as this program  <br>lib = ctypes.CDLL(&quot;./libinc.so&quot;)  <br>lib.increment  </pre><p><strong>Output:</strong></p><pre>&lt;_FuncPtr object at 0x7f46bf6e0750&gt;</pre><p>In the above code, the ctypes. <strong>CDLL</strong> returns a shared object called <strong>libinic.so.</strong> It contains the <strong>incrPointer()</strong> function. If we need to specify the pointer to the functions we define in a shared object, we have to specify it using the ctypes. Let’s see the below example.</p><pre>inc = lib.increment   <br>## defining the argtypes   <br>inc.argtypes = [ctypes.POINTER(ctypes.c_int)]  </pre><p>If we call the function using a different type, it will throw an error.</p><pre>incrPointer(10)  </pre><p><strong>Output:</strong></p><pre>Traceback (most recent call last):<br>  File &quot;&lt;stdin&gt;&quot;, line 1, in &lt;module&gt;<br>ctypes.ArgumentError: argument 1: &lt;class &#39;TypeError&#39;&gt;: expected LP_c_int instance instead of int</pre><p>This is because the incrPointer requires a pointer, and ctypes is a way of passing a pointer in Python.</p><pre>v = ctypes.c_int(10) </pre><p>v is a C variable. The ctypes provide a method called <strong>byref(),</strong> which is used to pass the variable reference.</p><pre>inc(ctypes.byref(a))   <br>a  </pre><p><strong>Output:</strong></p><pre>c_int(11)</pre><p>We have increased the value using the reference variable.</p><h3>Conclusion</h3><p>We have discussed that the pointer is not present in Python, but we can implement the same behavior with the *mutable object. We also discussed the ctypes modules that can define a C pointer in Python. We have defined a few excellent ways to simulate pointers in Python.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=c11e164cf299" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>