Saturday, 23 March 2024
Python Coding challenge - Day 155 | What is the output of the following Python Code?
Python Coding March 23, 2024 Python Coding Challenge No comments
def func(x, y=5, z=10):
return x + y + z
result = func(3, z=7)
print(result)
Solution and Explanation:
This Python code defines a function called func with three parameters: x, y, and z. The parameters y and z have default values of 5 and 10 respectively.
Here's the breakdown:
x is a positional argument.
y is a keyword argument with a default value of 5.
z is also a keyword argument with a default value of 10.
When the function func is called with func(3, z=7), it assigns 3 to x (as a positional argument), and 7 to z (as a keyword argument), while leaving y to its default value of 5.
So the function call func(3, z=7) effectively calculates 3 + 5 + 7, which equals 15.
Then, the value 15 is assigned to the variable result.
Finally, print(result) prints the value of result, which is 15. So, when you run this code, it will print 15 to the console.
Friday, 22 March 2024
Creating QR Code with Logo
Python Coding March 22, 2024 Python No comments
import qrcode
from PIL import Image
# Generate QR code for a URL
url = "https://www.clcoding.com"
qr = qrcode.QRCode(version=1, error_correction=qrcode.constants.ERROR_CORRECT_L, box_size=8, border=5)
qr.add_data(url)
qr.make(fit=True)
# Create an image with logo
image = qr.make_image(fill_color="black", back_color="pink")
# Add logo to the QR code
logo = Image.open("clcodinglogo.png")
logo_size = img.size[0] // 4
# Use Image.LANCZOS for resizing with anti-aliasing
logo = logo.resize((logo_size, logo_size), Image.LANCZOS)
image.paste(logo, ((img.size[0] - logo.size[0]) // 2, (img.size[1] - logo.size[1]) // 2))
# Save the image
image.save("qr_code.png")
Image.open("qr_code.png")
Explantion of the code:
Python pattern challenge - Day 5
Python Coding March 22, 2024 Python Coding Challenge No comments
def print_pattern():
for i in range(5, 0, -1):
for j in range(i, 0, -1):
print(chr(64 + j), end="")
print()
print_pattern()
Solution and Explanation:
Thursday, 21 March 2024
Python Coding challenge - Day 154 | What is the output of the following Python Code?
Python Coding March 21, 2024 Python Coding Challenge No comments
def outer():
x = 10
def inner():
nonlocal x
x += 5
print("Inner:", x)
inner()
print("Outer:", x)
outer()
Solution and Explanation
This code demonstrates nested functions in Python, along with the use of the nonlocal keyword.
Here's a breakdown of what each part does:
def outer():: This line defines a function named outer.
x = 10: Inside the outer function, a variable x is initialized with the value 10.
def inner():: Inside the outer function, another function named inner is defined.
nonlocal x: This statement inside the inner function tells Python that the variable x being referenced is not local to the inner function but belongs to the enclosing scope (which is the outer function in this case).
x += 5: Inside the inner function, x is incremented by 5.
print("Inner:", x): This line prints the value of x from the inner function after it has been incremented.
inner(): This line calls the inner function from within the outer function.
print("Outer:", x): After the inner function call, the value of x within the outer function is printed. Since x was modified within the inner function using the nonlocal keyword, its value will reflect the increment done inside the inner function.
outer(): Finally, the outer function is called, which executes the code inside it and its nested inner function.
When you run outer(), it will print:
Inner: 15
Outer: 15
This output shows that the inner function has successfully modified the value of x, and the change is reflected in the outer function as well.
Python pattern challenge - Day 4
Python Coding March 21, 2024 Python Coding Challenge No comments
n = 7
d = n // 2 + 1
for x in range(1, n + 1):
for y in range(1, n + 1):
if x == n // 2 + 1 or y == d:
print("*", end="")
else:
print(" ", end="")
if x <= n // 2:
d += 1
else:
d -= 1
print()
Wednesday, 20 March 2024
Python Coding challenge - Day 153 | What is the output of the following Python Code?
Python Coding March 20, 2024 Python Coding Challenge No comments
Code:
def some_func(a, b, c=0, d=1):
return a + b + c + d
result = some_func(1, 2, d=4)
print(result)
Solution and Explanation:
This code defines a function named some_func which takes four parameters: a, b, c, and d. Parameters c and d have default values of 0 and 1 respectively. The function calculates the sum of all four parameters and returns the result.
Here's the breakdown of the function:
a, b, c, and d are parameters representing values that can be passed into the function.
c=0 and d=1 in the function signature are default parameter values. This means if you call the function without providing values for c and d, they will default to 0 and 1 respectively.
Inside the function, it calculates the sum of a, b, c, and d and returns the result.
Now, when the function is called with some_func(1, 2, d=4), the values passed are a=1, b=2, c is not specified (so it takes the default value of 0), and d=4. Therefore, the function computes 1 + 2 + 0 + 4, which equals 7.
Finally, the result, which is 7, is printed using print(result).
Tuesday, 19 March 2024
Python Coding challenge - Day 152 | What is the output of the following Python Code?
Python Coding March 19, 2024 Python Coding Challenge No comments
def foo(x, y=[]):
y.append(x)
return y
print(foo(1))
print(foo(2))
This code defines a function foo that takes two arguments x and y, with y having a default value of an empty list []. Let's break down what happens:
def foo(x, y=[]):: This line defines a function named foo with two parameters, x and y. If y is not provided when calling the function, it defaults to an empty list [].
y.append(x): This line appends the value of x to the list y. Since y is a mutable object and is provided as a default argument, it retains its state across multiple calls to the function.
return y: This line returns the modified list y.
print(foo(1)): This line calls the foo function with x equal to 1. Since y is not provided explicitly, it defaults to [], which becomes [1] after appending 1 to it. So, it prints [1].
print(foo(2)): This line calls the foo function again, this time with x equal to 2. The default value of y is [1] now (the list modified in the previous call). So, 2 is appended to the existing list, resulting in [1, 2]. It prints [1, 2].
However, there's a caveat with this code due to the default mutable argument y=[]. If you call the function foo without providing a value for y, it'll reuse the same list across multiple function calls. This can lead to unexpected behavior if you're not careful. In this case, each time foo is called without specifying y, it keeps appending to the same list object. So, calling foo(1) modifies the list y to [1], and then calling foo(2) appends 2 to the modified list, resulting in [1, 2].
Python pattern challenge - Day 3
Python Coding March 19, 2024 Python Coding Challenge No comments
# Method 1: Using a loop
def print_sequence_loop(n):
for i in range(n+1):
print(f"{i}{'*' * i}")
# Method 2: Using list comprehension
def print_sequence_list_comprehension(n):
sequence = [f"{i}{'*' * i}" for i in range(n+1)]
print('\n'.join(sequence))
# Method 3: Using a generator function
def generate_sequence(n):
for i in range(n+1):
yield f"{i}{'*' * i}"
def print_sequence_generator(n):
sequence = generate_sequence(n)
for item in sequence:
print(item)
# Testing the functions
n = 5
print("Using loop:")
print_sequence_loop(n)
print("\nUsing list comprehension:")
print_sequence_list_comprehension(n)
print("\nUsing generator function:")
print_sequence_generator(n)
Method 1: Using a loop
- print_sequence_loop is a function that takes an integer n as input.
- It iterates over the range from 0 to n (inclusive) using a for loop.
- Inside the loop, it prints a string composed of the current number i followed by a number of asterisks (*) corresponding to the value of i.
Method 2: Using list comprehension
- print_sequence_list_comprehension is a function that takes an integer n as input.
- It uses list comprehension to generate a list where each element is a string composed of the current number i followed by a number of asterisks (*) corresponding to the value of i.
- It then joins the elements of the list with newline characters ('\n') and prints the resulting string.
Method 3: Using a generator function
- generate_sequence is a generator function that yields each element of the sequence lazily. It takes an integer n as input.
- Inside the function, it iterates over the range from 0 to n (inclusive) using a for loop, yielding a string composed of the current number i followed by a number of asterisks (*) corresponding to the value of i.
- print_sequence_generator is a function that takes an integer n as input.
- It creates a generator object sequence by calling generate_sequence(n).
- It then iterates over the elements of the generator using a for loop, printing each element.
The statistics module in Python
Python Coding March 19, 2024 Python No comments
Calculating Mean:
import statistics
data = [1, 2, 3, 4, 5]
mean = statistics.mean(data)
print("Mean:", mean)
#clcoding.com
Mean: 3
Calculating Median:
import statistics
data = [1, 2, 3, 4, 5]
median = statistics.median(data)
print("Median:", median)
#clcoding.com
Median: 3
Calculating Mode:
import statistics
data = [1, 2, 2, 3, 4, 4, 4, 5]
mode = statistics.mode(data)
print("Mode:", mode)
#clcoding.com
Mode: 4
Calculating Variance:
import statistics
data = [1, 2, 3, 4, 5]
variance = statistics.variance(data)
print("Variance:", variance)
#clcoding.com
Variance: 2.5
Calculating Standard Deviation:
import statistics
data = [1, 2, 3, 4, 5]
std_dev = statistics.stdev(data)
print("Standard Deviation:", std_dev)
#clcoding.com
Standard Deviation: 1.5811388300841898
Calculating Quartiles:
import statistics
data = [1, 2, 3, 4, 5]
q1 = statistics.quantiles(data, n=4)[0]
q3 = statistics.quantiles(data, n=4)[-1]
print("First Quartile (Q1):", q1)
print("Third Quartile (Q3):", q3)
#clcoding.com
First Quartile (Q1): 1.5
Third Quartile (Q3): 4.5
Calculating Correlation Coefficient:
import statistics
data1 = [1, 2, 3, 4, 5]
data2 = [2, 4, 6, 8, 10]
corr_coeff = statistics.correlation(data1, data2)
print("Correlation Coefficient:", corr_coeff)
#clcoding.com
Correlation Coefficient: 1.0
Monday, 18 March 2024
Python pattern challenge - Day 2
Python Coding March 18, 2024 Python Coding Challenge No comments
Method 1: Using Nested Loops
Method 2: Using Recursion
Method 3: Using List Comprehension
The faker library in Python
Python Coding March 18, 2024 Python No comments
Installing faker:
Generating Fake Names:
Generating Fake Addresses:
Generating Fake Email Addresses:
Generating Fake Text:
Generating Fake Dates:
Generating Fake User Profiles:
Sunday, 17 March 2024
Python Coding challenge - Day 151 | What is the output of the following Python Code?
Python Coding March 17, 2024 Python Coding Challenge No comments
Let's break down the code:
s = 'clcoding'
index = s.find('n', -1)
print(index)
s = 'clcoding': This line initializes a variable s with the string 'clcoding'.
index = s.find('n', -1): This line uses the find() method on the string s. The find() method searches for the specified substring within the given string. It takes two parameters: the substring to search for and an optional parameter for the starting index. If the starting index is negative, it counts from the end of the string.
In this case, 'n' is the substring being searched for.
The starting index -1 indicates that the search should start from the end of the string.
Since the substring 'n' is not found in the string 'clcoding', the method returns -1.
print(index): This line prints the value stored in the variable index, which is the result of the find() method. In this case, it will print -1, indicating that the substring 'n' was not found in the string 'clcoding'.
So, the overall output of this code will be -1.
Saturday, 16 March 2024
Python Coding challenge - Day 150 | What is the output of the following Python Code?
Python Coding March 16, 2024 Python Coding Challenge No comments
Let's break down each line:
my_tuple = (1, 2, 3): This line creates a tuple named my_tuple containing three elements: 1, 2, and 3.
x, y, z, *rest = my_tuple: This line uses tuple unpacking to assign values from my_tuple to variables x, y, z, and rest. The *rest syntax is used to gather any extra elements into a list called rest.
x is assigned the first element of my_tuple, which is 1.
y is assigned the second element of my_tuple, which is 2.
z is assigned the third element of my_tuple, which is 3.
*rest gathers any remaining elements of my_tuple (if any) into a list named rest. In this case, there are no remaining elements, so rest will be an empty list.
print(x, y, z, rest): This line prints the values of x, y, z, and rest.
x, y, and z are the values assigned earlier, which are 1, 2, and 3 respectively.
rest is an empty list since there are no remaining elements in my_tuple.
Therefore, when you run this code, it will output:
1 2 3 []
Operators - Lecture 2
Python Coding March 16, 2024 Python Coding Challenge No comments
Q:- What is Operator ?
Operators are symbol or special characters that perform specific
operations on one or more operands (Values or Variables).
Assignment Question
1. Write a program that prompts the user to enter their name, age, and
favorite number. Calculate and print the product of their age and
favorite number.
2. Write a program that prompts the user for enter a sentence and then
check the length of the sentence and prints the sentence also.
3. Write a program that takes two sentences from user and then checks for
the length of both sentences using “Identity Operators”.
4. Write a program that takes a integer value from the user and checks that
the number is between 10 and 20 then it will print true or else false , use
Logical and & or operator both for checking the result.
5. Write the uses of all the operators which comes inside these operators
use comments in python for writing the uses :-
Arithmetic operators
Assignment operators
Comparison operators
Logical operators
Identity operators
Basics of Coding - Lecture 1
Python Coding March 16, 2024 Python Coding Challenge No comments
1. What is coding?
->Coding refers to the process of creating instructions for a computer to
perform specific tasks. It involves writing lines of code using a programming
language that follows a defined syntax and set of rules.
Coding can be used to create software applications, websites, algorithms, and
much more. It is a fundamental skill in the field of computer science and in
essential for anyone interested in software development, data analysis,
machine learning, and various other technological domains.
2. What is algorithm?
->An algorithm is a set of clear and specific instructions that guide the
computer to solve a problem or complete a task efficiently and accurately. It’s
like a recipe that tells the computer exactly what do to achieve a desired
outcome.
3. Who created Python?
-> Python was created by Guido van Rossum. He started developing Python in
the late 1980s, and the first version of the programming language was released
in 1991.
4. What is Python?
->Python is a popular and easy to learn programming language. It is known for
it’s simplicity and readability, making it a great choice for beginners. Python is
versatile and can be used for a wide range of tasks, from web development to
data analysis and artificial intelligence. It’s clear syntax and extensive library
support make it efficient and productive for software development. Overall,
Python is a powerful yet user-friendly language that is widely used in the tech
industry.
Assignment Questions
1. Declare two variables, x and y, and assign them the values 5
and 3, respectively. Calculate their sum and print the result.
2. Declare a variable radius and assign it a value of 7. Calculate the
area of a circle with that radius and print the result.
3. Declare a variable temperature and assign it a value of 25.
Convert the temperature from Celsius to Fahrenheit and print the
result.
4. Declare three variables a, b, and c and assign them the values
10, 3.5, and 2, respectively. Calculate the result of a divided by the
product of b and c and print the result.
5. Declare a variable initial_amount and assign it a value of 1000.
Calculate the compound interest after one year with an interest rate
of 5% and print the result.
6. Declare a variable seconds and assign it a value of 86400.
Convert the seconds into hours, minutes, and seconds, and print the
result in the format: "hh:mm:ss".
7. Declare a variable numerator and assign it a value of 27.
Declare another variable denominator and assign it a value of 4.
Calculate the integer division and remainder of numerator divided by
denominator and print both results.
8. Declare a variable length and assign it a value of 10. Calculate
the perimeter and area of a square with that length and print the
results.
Friday, 15 March 2024
The json library in Python
Python Coding March 15, 2024 Python No comments
The json library in Python
1. Encoding Python Data to JSON:
import json
# Python dictionary to be encoded to JSON
data = {
"name": "John",
"age": 30,
"city": "New York"
}
# Encode the Python dictionary to JSON
json_data = json.dumps(data)
print("Encoded JSON:", json_data)
#clcoding.com
Encoded JSON: {"name": "John", "age": 30, "city": "New York"}
2. Decoding JSON to Python Data:
import json
# JSON data to be decoded to Python
json_data = '{"name": "John", "age": 30, "city": "New York"}'
# Decode the JSON data to a Python dictionary
data = json.loads(json_data)
print("Decoded Python Data:", data)
#clcoding.com
Decoded Python Data: {'name': 'John', 'age': 30, 'city': 'New York'}
3. Reading JSON from a File:
clcoding
import json
# Read JSON data from a file
with open('clcoding.json', 'r') as file:
data = json.load(file)
print("JSON Data from File:", data)
#clcoding.com
JSON Data from File: {'We are supporting freely to everyone. Join us for live support. \n\nWhatApp Support: wa.me/919767292502\n\nInstagram Support : https://www.instagram.com/pythonclcoding/\n\nFree program: https://www.clcoding.com/\n\nFree Codes: https://clcoding.quora.com/\n\nFree Support: pythonclcoding@gmail.com\n\nLive Support: https://t.me/pythonclcoding\n\nLike us: https://www.facebook.com/pythonclcoding\n\nJoin us: https://www.facebook.com/groups/pythonclcoding': None}
4. Writing JSON to a File:
import json
# Python dictionary to be written to a JSON file
data = {
"name": "John",
"age": 30,
"city": "New York"
}
# Write the Python dictionary to a JSON file
with open('output.json', 'w') as file:
json.dump(data, file)
#clcoding.com
5. Handling JSON Errors:
import json
# JSON data with syntax error
json_data = '{"name": "John", "age": 30, "city": "New York"'
try:
# Attempt to decode JSON data
data = json.loads(json_data)
except json.JSONDecodeError as e:
# Handle JSON decoding error
print("Error decoding JSON:", e)
#clcoding.com
Error decoding JSON: Expecting ',' delimiter: line 1 column 47 (char 46)
Thursday, 14 March 2024
Python Coding challenge - Day 149 | What is the output of the following Python Code?
Python Coding March 14, 2024 Python Coding Challenge No comments
Let's break down the given code:
for i in range(1, 3):
print(i, end=' - ')
This code snippet is a for loop in Python. Let's go through it step by step:
for i in range(1, 3)::
This line initiates a loop where i will take on values from 1 to 2 (inclusive). The range() function generates a sequence of numbers starting from the first argument (1 in this case) up to, but not including, the second argument (3 in this case).
So, the loop will iterate with i taking on the values 1 and 2.
print(i, end=' - '):
Within the loop, this line prints the current value of i, followed by a dash (-), without moving to the next line due to the end=' - ' parameter.
So, during each iteration of the loop, it will print the value of i followed by a dash and space.
When you execute this code, it will output:
1 - 2 -
Explanation: The loop runs for each value of i in the range (1, 3), which are 1 and 2. For each value of i, it prints the value followed by a dash and space. So, the output is 1 - 2 - .
Learn hashlib library in Python
Python Coding March 14, 2024 Python No comments
1. Hashing Strings:
import hashlib
# Hash a string using SHA256 algorithm
string_to_hash = "Hello, World!"
hashed_string = hashlib.sha256(string_to_hash.encode()).hexdigest()
print("Original String:", string_to_hash)
print("Hashed String:", hashed_string)
#clcoding.com
Original String: Hello, World!
Hashed String: dffd6021bb2bd5b0af676290809ec3a53191dd81c7f70a4b28688a362182986f
2. Hashing Files:
#clcoding.com
import hashlib
def calculate_file_hash(file_path, algorithm='sha256'):
# Choose the hash algorithm
hash_algorithm = getattr(hashlib, algorithm)()
# Read the file in binary mode and update the hash object
with open(file_path, 'rb') as file:
for chunk in iter(lambda: file.read(4096), b''):
hash_algorithm.update(chunk)
# Get the hexadecimal representation of the hash value
hash_value = hash_algorithm.hexdigest()
return hash_value
# Example usage
file_path = 'example.txt'
file_hash = calculate_file_hash(file_path)
print("SHA-256 Hash of the file:", file_hash)
#clcoding.com
SHA-256 Hash of the file: e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855
3. Using Different Hash Algorithms:
import hashlib
# Hash a string using different algorithms
string_to_hash = "Hello, World!"
# MD5
md5_hash = hashlib.md5(string_to_hash.encode()).hexdigest()
# SHA1
sha1_hash = hashlib.sha1(string_to_hash.encode()).hexdigest()
# SHA512
sha512_hash = hashlib.sha512(string_to_hash.encode()).hexdigest()
print("MD5 Hash:", md5_hash)
print("SHA1 Hash:", sha1_hash)
print("SHA512 Hash:", sha512_hash)
#clcoding.com
MD5 Hash: 65a8e27d8879283831b664bd8b7f0ad4
SHA1 Hash: 0a0a9f2a6772942557ab5355d76af442f8f65e01
SHA512 Hash: 374d794a95cdcfd8b35993185fef9ba368f160d8daf432d08ba9f1ed1e5abe6cc69291e0fa2fe0006a52570ef18c19def4e617c33ce52ef0a6e5fbe318cb0387
4. Hashing Passwords (Securely):
import hashlib
# Hash a password securely using a salt
password = "my_password"
salt = "random_salt"
hashed_password = hashlib.pbkdf2_hmac('sha256', password.encode(), salt.encode(), 100000)
hashed_password_hex = hashed_password.hex()
print("Salted and Hashed Password:", hashed_password_hex)
#clcoding.com
Salted and Hashed Password: b18597b62cda4415c995eaff30f61460da8ff4d758d3880f80593ed5866dcf98
5. Verifying Passwords:
import hashlib
# Verify a password against a stored hash
stored_hash = "stored_hashed_password"
def verify_password(password, stored_hash):
input_hash = hashlib.sha256(password.encode()).hexdigest()
if input_hash == stored_hash:
return True
else:
return False
password_to_verify = "password_to_verify"
if verify_password(password_to_verify, stored_hash):
print("Password is correct!")
else:
print("Password is incorrect.")
#clcoding.com
Password is incorrect.
6. Hashing a String using SHA-256:
import hashlib
# Create a hash object
hash_object = hashlib.sha256()
# Update the hash object with the input data
input_data = b'Hello, World!'
hash_object.update(input_data)
# Get the hexadecimal representation of the hash value
hash_value = hash_object.hexdigest()
print("SHA-256 Hash:", hash_value)
#clcoding.com
SHA-256 Hash: dffd6021bb2bd5b0af676290809ec3a53191dd81c7f70a4b28688a362182986f
7. Hashing a String using MD5:
import hashlib
# Create a hash object
hash_object = hashlib.md5()
# Update the hash object with the input data
input_data = b'Hello, World!'
hash_object.update(input_data)
# Get the hexadecimal representation of the hash value
hash_value = hash_object.hexdigest()
print("MD5 Hash:", hash_value)
#clcoding.com
MD5 Hash: 65a8e27d8879283831b664bd8b7f0ad4
Wednesday, 13 March 2024
Learn psutil library in Python 🧵:
Python Coding March 13, 2024 Python No comments
Learn psutil library in Python
pip install psutil
1. Getting CPU Information:
import psutil
# Get CPU information
cpu_count = psutil.cpu_count()
cpu_percent = psutil.cpu_percent(interval=1)
print("CPU Count:", cpu_count)
print("CPU Percent:", cpu_percent)
#clcoding.com
CPU Count: 8
CPU Percent: 6.9
2. Getting Memory Information:
import psutil
# Get memory information
memory = psutil.virtual_memory()
total_memory = memory.total
available_memory = memory.available
used_memory = memory.used
percent_memory = memory.percent
print("Total Memory:", total_memory)
print("Available Memory:", available_memory)
print("Used Memory:", used_memory)
print("Memory Percent:", percent_memory)
#clcoding.com
Total Memory: 8446738432
Available Memory: 721600512
Used Memory: 7725137920
Memory Percent: 91.5
3. Listing Running Processes:
import psutil
# List running processes
for process in psutil.process_iter():
print(process.pid, process.name())
#clcoding.com
0 System Idle Process
4 System
124 Registry
252 chrome.exe
408 PowerToys.Peek.UI.exe
436 msedge.exe
452 svchost.exe
504 smss.exe
520 svchost.exe
532 RuntimeBroker.exe
544 TextInputHost.exe
548 svchost.exe
680 csrss.exe
704 fontdrvhost.exe
768 wininit.exe
776 chrome.exe
804 chrome.exe
848 services.exe
924 lsass.exe
1036 WUDFHost.exe
1100 svchost.exe
1148 svchost.exe
1160 SgrmBroker.exe
1260 dllhost.exe
1284 PowerToys.exe
1328 svchost.exe
1392 svchost.exe
1400 svchost.exe
1408 svchost.exe
1488 svchost.exe
1504 svchost.exe
1512 svchost.exe
1600 SmartAudio3.exe
1608 svchost.exe
1668 svchost.exe
1716 svchost.exe
1724 IntelCpHDCPSvc.exe
1732 svchost.exe
1752 svchost.exe
1796 TiWorker.exe
1828 svchost.exe
1920 chrome.exe
1972 svchost.exe
1992 svchost.exe
2016 svchost.exe
2052 svchost.exe
2060 svchost.exe
2068 IntelCpHeciSvc.exe
2148 igfxCUIService.exe
2168 svchost.exe
2224 svchost.exe
2260 svchost.exe
2316 svchost.exe
2360 chrome.exe
2364 svchost.exe
2400 MsMpEng.exe
2420 svchost.exe
2428 svchost.exe
2448 PowerToys.FancyZones.exe
2480 screenrec.exe
2488 svchost.exe
2496 svchost.exe
2504 svchost.exe
2552 svchost.exe
2604 svchost.exe
2616 MemCompression
2716 svchost.exe
2792 chrome.exe
2796 dasHost.exe
2804 chrome.exe
2852 svchost.exe
2876 svchost.exe
2932 CxAudioSvc.exe
3016 svchost.exe
3240 svchost.exe
3416 svchost.exe
3480 svchost.exe
3536 spoolsv.exe
3620 svchost.exe
3660 svchost.exe
3700 svchost.exe
3752 RuntimeBroker.exe
3848 taskhostw.exe
3976 svchost.exe
3984 svchost.exe
3992 svchost.exe
4000 svchost.exe
4008 svchost.exe
4016 svchost.exe
4024 svchost.exe
4032 svchost.exe
4100 svchost.exe
4132 OneApp.IGCC.WinService.exe
4140 AnyDesk.exe
4148 armsvc.exe
4156 CxUtilSvc.exe
4208 WMIRegistrationService.exe
4284 msedge.exe
4312 svchost.exe
4320 AGMService.exe
4340 svchost.exe
4488 chrome.exe
4516 svchost.exe
4584 svchost.exe
4720 jhi_service.exe
4928 chrome.exe
5004 chrome.exe
5176 dwm.exe
5348 svchost.exe
5368 Flow.exe
5380 svchost.exe
5536 chrome.exe
5540 chrome.exe
5584 audiodg.exe
5620 svchost.exe
5724 svchost.exe
5776 svchost.exe
5992 ctfmon.exe
6032 CompPkgSrv.exe
6056 SearchProtocolHost.exe
6076 msedge.exe
6120 SearchIndexer.exe
6128 RuntimeBroker.exe
6156 svchost.exe
6192 MoUsoCoreWorker.exe
6380 PowerToys.PowerLauncher.exe
6424 PowerToys.Awake.exe
6480 msedge.exe
6596 svchost.exe
6740 svchost.exe
6792 winlogon.exe
6856 TrustedInstaller.exe
6872 svchost.exe
6888 igfxEM.exe
6908 svchost.exe
6948 chrome.exe
7140 csrss.exe
7296 PowerToys.KeyboardManagerEngine.exe
7336 WhatsApp.exe
7348 chrome.exe
7416 chrome.exe
7440 MusNotifyIcon.exe
7444 StartMenuExperienceHost.exe
7480 svchost.exe
7520 chrome.exe
7556 SearchApp.exe
7560 SecurityHealthService.exe
7720 msedge.exe
8220 MmReminderService.exe
8316 RuntimeBroker.exe
8636 svchost.exe
8836 python.exe
9088 ShellExperienceHost.exe
9284 svchost.exe
9344 NisSrv.exe
9560 msedge.exe
9664 chrome.exe
9736 chrome.exe
9784 SearchApp.exe
9808 svchost.exe
9868 python.exe
9884 svchost.exe
9908 chrome.exe
9936 chrome.exe
9996 QtWebEngineProcess.exe
10012 taskhostw.exe
10024 chrome.exe
10148 svchost.exe
10228 svchost.exe
10236 PowerToys.CropAndLock.exe
10304 Taskmgr.exe
10324 Video.UI.exe
10584 svchost.exe
10680 chrome.exe
10920 LockApp.exe
11064 chrome.exe
11176 chrome.exe
11188 msedge.exe
11396 msedge.exe
11500 QtWebEngineProcess.exe
11592 svchost.exe
12132 msedge.exe
12212 RuntimeBroker.exe
12360 RuntimeBroker.exe
12500 chrome.exe
12596 python.exe
12704 chrome.exe
12744 svchost.exe
12832 svchost.exe
12848 MicTray64.exe
12852 fontdrvhost.exe
12992 chrome.exe
13092 chrome.exe
13268 chrome.exe
13332 chrome.exe
13388 sihost.exe
13572 chrome.exe
13760 SecurityHealthSystray.exe
13792 msedge.exe
13880 fodhelper.exe
13900 chrome.exe
14160 UserOOBEBroker.exe
14220 RuntimeBroker.exe
14260 chrome.exe
14356 msedge.exe
14572 chrome.exe
14648 chrome.exe
14696 PowerToys.AlwaysOnTop.exe
14852 chrome.exe
14868 PowerToys.ColorPickerUI.exe
14876 conhost.exe
14888 PowerToys.PowerOCR.exe
14948 chrome.exe
15324 explorer.exe
4. Getting Process Information:
252
import psutil
# Get information for a specific process
pid = 252 # Replace with the process ID of interest
process = psutil.Process(pid)
print("Process Name:", process.name())
print("Process Status:", process.status())
print("Process CPU Percent:", process.cpu_percent(interval=1))
print("Process Memory Info:", process.memory_info())
#clcoding.com
Process Name: chrome.exe
Process Status: running
Process CPU Percent: 0.0
Process Memory Info: pmem(rss=29597696, vms=24637440, num_page_faults=14245, peak_wset=37335040, wset=29597696, peak_paged_pool=635560, paged_pool=635560, peak_nonpaged_pool=21344, nonpaged_pool=17536, pagefile=24637440, peak_pagefile=33103872, private=24637440)
5. Killing a Process:
import psutil
# Kill a process
pid_to_kill = 10088
# Replace with the process ID to kill
process_to_kill = psutil.Process(pid_to_kill)
process_to_kill.terminate()
#clcoding.com
6. Getting Disk Usage:
import psutil
# Get disk usage information
disk_usage = psutil.disk_usage('/')
total_disk_space = disk_usage.total
used_disk_space = disk_usage.used
free_disk_space = disk_usage.free
disk_usage_percent = disk_usage.percent
print("Total Disk Space:", total_disk_space)
print("Used Disk Space:", used_disk_space)
print("Free Disk Space:", free_disk_space)
print("Disk Usage Percent:", disk_usage_percent)
#clcoding.com
Total Disk Space: 479491600384
Used Disk Space: 414899838976
Free Disk Space: 64591761408
Disk Usage Percent: 86.5
Tuesday, 12 March 2024
Python Coding challenge - Day 148 | What is the output of the following Python Code?
Python Coding March 12, 2024 Python Coding Challenge No comments
Let's break down the provided code:
d = {'Milk': 1, 'Soap': 2, 'Towel': 3}
if 'Soap' in d:
print(d['Soap'])
d = {'Milk': 1, 'Soap': 2, 'Towel': 3}: This line initializes a dictionary named d with three key-value pairs. Each key represents an item, and its corresponding value represents the quantity of that item. In this case, there are items such as 'Milk', 'Soap', and 'Towel', each associated with a quantity.
if 'Soap' in d:: This line checks whether the key 'Soap' exists in the dictionary d. It does this by using the in keyword to check if the string 'Soap' is a key in the dictionary. If 'Soap' is present in the dictionary d, the condition evaluates to True, and the code inside the if block will execute.
print(d['Soap']): If the key 'Soap' exists in the dictionary d, this line will execute. It retrieves the value associated with the key 'Soap' from the dictionary d and prints it. In this case, the value associated with 'Soap' is 2, so it will print 2.
So, in summary, this code checks if the dictionary contains an entry for 'Soap'. If it does, it prints the quantity of soap available (which is 2 in this case).
Plots using Python
Python Coding March 12, 2024 Python No comments
1. Line Plot:
#clcoding.com
import matplotlib.pyplot as plt
# Sample data
x = [1, 2, 3, 4, 5]
y = [2, 4, 6, 8, 10]
# Create a line plot
plt.plot(x, y)
plt.xlabel('X-axis')
plt.ylabel('Y-axis')
plt.title('Line Plot Example')
plt.show()
#clcoding.com
2. Bar Plot:
import matplotlib.pyplot as plt
# Sample data
categories = ['A', 'B', 'C', 'D']
values = [10, 20, 15, 25]
# Create a bar plot
plt.bar(categories, values)
plt.xlabel('Categories')
plt.ylabel('Values')
plt.title('Bar Plot Example')
plt.show()
3. Histogram:
import matplotlib.pyplot as plt
import numpy as np
# Generate random data
data = np.random.randn(1000)
# Create a histogram
plt.hist(data, bins=30)
plt.xlabel('Values')
plt.ylabel('Frequency')
plt.title('Histogram Example')
plt.show()
4. Scatter Plot:
import matplotlib.pyplot as plt
import numpy as np
# Generate random data
x = np.random.randn(100)
y = 2 * x + np.random.randn(100)
# Create a scatter plot
plt.scatter(x, y)
plt.xlabel('X-axis')
plt.ylabel('Y-axis')
plt.title('Scatter Plot Example')
plt.show()
5. Box Plot:
import seaborn as sns
import numpy as np
# Generate random data
data = np.random.randn(100)
# Create a box plot
sns.boxplot(data=data)
plt.title('Box Plot Example')
plt.show()
6. Violin Plot:
import seaborn as sns
import numpy as np
# Generate random data
data = np.random.randn(100)
# Create a violin plot
sns.violinplot(data=data)
plt.title('Violin Plot Example')
plt.show()
7. Heatmap:
#clcoding.com
import seaborn as sns
import numpy as np
# Generate random data
data = np.random.rand(10, 10)
#clcoding.com
# Create a heatmap
sns.heatmap(data)
plt.title('Heatmap Example')
plt.show()
8. Area Plot:
import matplotlib.pyplot as plt
# Sample data #clcoding.com
x = [1, 2, 3, 4, 5]
y1 = [2, 4, 6, 8, 10]
y2 = [1, 3, 5, 7, 9]
# Create an area plot
plt.fill_between(x, y1, color="skyblue", alpha=0.4)
plt.fill_between(x, y2, color="salmon", alpha=0.4)
plt.xlabel('X-axis')
plt.ylabel('Y-axis')
plt.title('Area Plot Example')
plt.show()
9. Pie Chart:
import matplotlib.pyplot as plt
# Sample data
sizes = [30, 20, 25, 15, 10]
labels = ['A', 'B', 'C', 'D', 'E']
# Create a pie chart
plt.pie(sizes, labels=labels, autopct='%1.1f%%', startangle=140)
plt.title('Pie Chart Example')
plt.show()
10. Polar Plot:
g
import matplotlib.pyplot as plt
import numpy as np
# Sample data
theta = np.linspace(0, 2*np.pi, 100)
r = np.sin(3*theta)
# Create a polar plot #clcoding.com
plt.polar(theta, r)
plt.title('Polar Plot Example')
plt.show()
11. 3D Plot:
import matplotlib.pyplot as plt
import numpy as np
# Sample data
x = np.linspace(-5, 5, 100)
y = np.linspace(-5, 5, 100)
X, Y = np.meshgrid(x, y)
Z = np.sin(np.sqrt(X**2 + Y**2))
# Create a 3D surface plot
fig = plt.figure()
ax = fig.add_subplot(111, projection='3d')
ax.plot_surface(X, Y, Z)
ax.set_title('3D Plot Example')
plt.show()
12. Violin Swarm Plot:
#clcoding.com
import seaborn as sns
import numpy as np
# Generate random data
data = np.random.randn(100)
#clcoding.com
# Create a violin swarm plot
sns.violinplot(data=data, inner=None, color='lightgray')
sns.swarmplot(data=data, color='blue', alpha=0.5)
plt.title('Violin Swarm Plot Example')
plt.show()
13. Pair Plot:
import seaborn as sns
import pandas as pd
# Load sample dataset
iris = sns.load_dataset('iris')
# Create a pair plot
sns.pairplot(iris)
plt.title('Pair Plot Example')
plt.show()
Monday, 11 March 2024
Python Coding challenge - Day 147 | What is the output of the following Python Code?
Python Coding March 11, 2024 Python Coding Challenge No comments
In Python, the is operator checks whether two variables reference the same object in memory, while the == operator checks for equality of values. Now, let's analyze the given code:
g = (1, 2, 3)
h = (1, 2, 3)
print(f"g is h: {g is h}")
print(f"g == h: {g == h}")
Explanation:
Identity (is):
The g is h expression checks if g and h refer to the same object in memory.
In this case, since tuples are immutable, Python creates separate objects for g and h with the same values (1, 2, 3).
Equality (==):
The g == h expression checks if the values contained in g and h are the same.
Tuples are compared element-wise. In this case, both tuples have the same elements (1, 2, 3).
Output:
The output of the code will be:
g is h: False
g == h: True
Explanation of Output:
g is h: False: The is operator returns False because g and h are distinct objects in memory.
g == h: True: The == operator returns True because the values inside g and h are the same.
In summary, the tuples g and h are different objects in memory, but they contain the same values, leading to == evaluating to True.
Cybersecurity using Python
Python Coding March 11, 2024 Python No comments
1. Hashing Passwords:
import hashlib
def hash_password(password):
hashed_password = hashlib.sha256(password.encode()).hexdigest()
return hashed_password
# Example
password = "my_secure_password"
hashed_password = hash_password(password)
print("Hashed Password:", hashed_password)
#clcoding.com
Hashed Password: 2c9a8d02fc17ae77e926d38fe83c3529d6638d1d636379503f0c6400e063445f
2. Generating Random Passwords:
import random
import string
def generate_random_password(length=12):
characters = string.ascii_letters + string.digits + string.punctuation
password = ''.join(random.choice(characters) for _ in range(length))
return password
# Example
random_password = generate_random_password()
print("Random Password:", random_password)
#clcoding.com
Random Password: zH7~ANoO:7#S
3. Network Scanning with Scapy:
from scapy.all import IP, ICMP, sr1
def ping(host):
packet = IP(dst=host)/ICMP()
response = sr1(packet, timeout=2, verbose=0)
if response:
return f"{host} is online"
else:
return f"{host} is offline"
# Example
host_to_scan = "example.com"
result = ping(host_to_scan)
print(result)
#clcoding.com
4. Web Scraping for Security Research:
import requests
from bs4 import BeautifulSoup
def scrape_security_news():
url = "https://example-security-news.com"
response = requests.get(url)
soup = BeautifulSoup(response.text, 'html.parser')
headlines = soup.find_all('h2', class_='security-headline')
return [headline.text for headline in headlines]
# Example
security_headlines = scrape_security_news()
print("Security Headlines:", security_headlines)
#clcoding.com
5. Password Cracking Simulation:
import hashlib
def simulate_password_cracking(hashed_password, password_list):
for password in password_list:
if hashlib.sha256(password.encode()).hexdigest() == hashed_password:
return f"Password cracked: {password}"
return "Password not found"
# Example
hashed_password_to_crack = "d033e22ae348aeb5660fc2140aec35850c4da997"
common_passwords = ["password", "123456", "qwerty", "admin"]
result = simulate_password_cracking(hashed_password_to_crack, common_passwords)
print(result)
#clcoding.com
6. Secure File Handling:
import os
def secure_file_deletion(file_path):
with open(file_path, 'w') as file:
file.write(os.urandom(1024))
# Overwrite the file with random data
os.remove(file_path)
print(f"{file_path} securely deleted")
# Example
file_path_to_delete = "example.txt"
secure_file_deletion(file_path_to_delete)
#clcoding.com
Sunday, 10 March 2024
Python Coding challenge - Day 146 | What is the output of the following Python Code?
Python Coding March 10, 2024 Python Coding Challenge No comments
Let's go through the code step by step:
years = 5: Initializes a variable named years with the value 5.
if True or False:: This is an if statement with a condition. The condition is True or False, which will always be True because the logical OR (or) operator returns True if at least one of the operands is True. In this case, True is always True, so the condition is satisfied.
years = years + 2: Inside the if block, there's an assignment statement that adds 2 to the current value of the years variable. Since the condition is always True, this line of code will always be executed.
print(years): Finally, this line prints the current value of the years variable.
As a result, the code will always enter the if block, increment the value of years by 2 (from 5 to 7), and then print the final value of years, which is 7.
Saturday, 9 March 2024
try and except in Python
Python Coding March 09, 2024 Python Coding Challenge No comments
Example 1: Handling a Specific Exception
try:
# Code that might raise an exception
num = int(input("Enter a number: "))
result = 10 / num
print("Result:", result)
except ZeroDivisionError:
# Handle the specific exception (division by zero)
print("Error: Cannot divide by zero.")
except ValueError:
# Handle the specific exception (invalid input for conversion to int)
print("Error: Please enter a valid number.")
#clcoding.com
Enter a number: 5
Result: 2.0
Example 2: Handling Multiple Exceptions
try:
file_name = input("Enter the name of a file: ")
# Open and read the contents of the file
with open(file_name, 'r') as file:
contents = file.read()
print("File contents:", contents)
except FileNotFoundError:
# Handle the specific exception (file not found)
print("Error: File not found.")
except PermissionError:
# Handle the specific exception (permission error)
print("Error: Permission denied to access the file.")
except Exception as e:
# Handle any other exceptions not explicitly caught
print(f"An unexpected error occurred: {e}")
#clcoding.com
Enter the name of a file: clcoding
Error: File not found.
Example 3: Using a Generic Exception
try:
# Code that might raise an exception
x = int(input("Enter a number: "))
y = 10 / x
print("Result:", y)
except Exception as e:
# Catch any type of exception
print(f"An error occurred: {e}")
#clcoding.com
Enter a number: 5
Result: 2.0
Python Coding challenge - Day 145 | What is the output of the following Python Code?
Python Coding March 09, 2024 Python Coding Challenge No comments
Let's evaluate the provided Python code:
a = 20 or 40
if 30 <= a <= 50:
print('Hello')
else:
print('Hi')
Here's a step-by-step breakdown:
Assignment of a:
a = 20 or 40: In Python, the or operator returns the first true operand or the last operand if none are true. In this case, 20 is considered true, so a is assigned the value 20.
Condition Check:
if 30 <= a <= 50:: Checks whether the value of a falls within the range from 30 to 50 (inclusive).
Print Statement Execution:
Since a is assigned the value 20, which is outside the range 30 to 50, the condition is not met.
Therefore, the else block is executed, and the output will be Hi.
Let's run through the logic:
Is 30 <= 20 <= 50? No.
So, the else block is executed, and 'Hi' is printed.
The output of this code will be:
Hi
Popular Posts
-
What does the following Python code do? arr = [10, 20, 30, 40, 50] result = arr[1:4] print(result) [10, 20, 30] [20, 30, 40] [20, 30, 40, ...
-
What will be the output of this code? nums = (1, 2, 3) output = {*nums} print(output) Options: {1, 2, 3} [1, 2, 3] (1, 2, 3) TypeError Ste...
-
What will be the output of the following code? import numpy as np arr = np.array([1, 2, 3, 4]) result = arr * arr[::-1] print(result) [1, ...
-
What will be the output of the following code? import numpy as np arr = np.arange(1, 10).reshape(3, 3) result = arr.sum(axis=0) - arr.sum(...
-
Code Explanation: range(5): The range(5) generates numbers from 0 to 4 (not including 5). The loop iterates through these numbers one by o...
-
Through a recent series of breakthroughs, deep learning has boosted the entire field of machine learning. Now, even programmers who know c...
-
Code Explanation: Define a Recursive Function: def recursive_sum(n): A function named recursive_sum is defined. This function takes a sing...
-
Code Explanation: Define the Function: def mystery(a, b, c): A function named mystery is defined with three parameters: a, b, and c. Use of ...
-
Code Explanation: Importing NumPy: The statement import numpy as np imports the NumPy library, which is a popular Python library for numer...