Skip to content

Commit b269635

Browse files
authored
M
1 parent 63a4335 commit b269635

File tree

20 files changed

+742
-0
lines changed

20 files changed

+742
-0
lines changed

M/mac-address-changer/README.md

Whitespace-only changes.
Lines changed: 60 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,60 @@
1+
import subprocess
2+
import string
3+
import random
4+
import re
5+
6+
7+
def get_random_mac_address():
8+
"""Generate and return a MAC address in the format of Linux"""
9+
# get the hexdigits uppercased
10+
uppercased_hexdigits = ''.join(set(string.hexdigits.upper()))
11+
# 2nd character must be 0, 2, 4, 6, 8, A, C, or E
12+
mac = ""
13+
for i in range(6):
14+
for j in range(2):
15+
if i == 0:
16+
mac += random.choice("02468ACE")
17+
else:
18+
mac += random.choice(uppercased_hexdigits)
19+
mac += ":"
20+
return mac.strip(":")
21+
22+
23+
def get_current_mac_address(iface):
24+
# use the ifconfig command to get the interface details, including the MAC address
25+
output = subprocess.check_output(f"ifconfig {iface}", shell=True).decode()
26+
return re.search("ether (.+) ", output).group().split()[1].strip()
27+
28+
29+
30+
def change_mac_address(iface, new_mac_address):
31+
# disable the network interface
32+
subprocess.check_output(f"ifconfig {iface} down", shell=True)
33+
# change the MAC
34+
subprocess.check_output(f"ifconfig {iface} hw ether {new_mac_address}", shell=True)
35+
# enable the network interface again
36+
subprocess.check_output(f"ifconfig {iface} up", shell=True)
37+
38+
39+
if __name__ == "__main__":
40+
import argparse
41+
parser = argparse.ArgumentParser(description="Python Mac Changer on Linux")
42+
parser.add_argument("interface", help="The network interface name on Linux")
43+
parser.add_argument("-r", "--random", action="store_true", help="Whether to generate a random MAC address")
44+
parser.add_argument("-m", "--mac", help="The new MAC you want to change to")
45+
args = parser.parse_args()
46+
iface = args.interface
47+
if args.random:
48+
# if random parameter is set, generate a random MAC
49+
new_mac_address = get_random_mac_address()
50+
elif args.mac:
51+
# if mac is set, use it instead
52+
new_mac_address = args.mac
53+
# get the current MAC address
54+
old_mac_address = get_current_mac_address(iface)
55+
print("[*] Old MAC address:", old_mac_address)
56+
# change the MAC address
57+
change_mac_address(iface, new_mac_address)
58+
# check if it's really changed
59+
new_mac_address = get_current_mac_address(iface)
60+
print("[+] New MAC address:", new_mac_address)
Lines changed: 114 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,114 @@
1+
import subprocess
2+
import regex as re
3+
import string
4+
import random
5+
6+
# the registry path of network interfaces
7+
network_interface_reg_path = r"HKEY_LOCAL_MACHINE\\SYSTEM\\CurrentControlSet\\Control\\Class\\{4d36e972-e325-11ce-bfc1-08002be10318}"
8+
# the transport name regular expression, looks like {AF1B45DB-B5D4-46D0-B4EA-3E18FA49BF5F}
9+
transport_name_regex = re.compile("{.+}")
10+
# the MAC address regular expression
11+
mac_address_regex = re.compile(r"([A-Z0-9]{2}[:-]){5}([A-Z0-9]{2})")
12+
13+
def get_random_mac_address():
14+
"""Generate and return a MAC address in the format of WINDOWS"""
15+
# get the hexdigits uppercased
16+
uppercased_hexdigits = ''.join(set(string.hexdigits.upper()))
17+
# 2nd character must be 2, 4, A, or E
18+
return random.choice(uppercased_hexdigits) + random.choice("24AE") + "".join(random.sample(uppercased_hexdigits, k=10))
19+
20+
21+
def clean_mac(mac):
22+
"""Simple function to clean non hexadecimal characters from a MAC address
23+
mostly used to remove '-' and ':' from MAC addresses and also uppercase it"""
24+
return "".join(c for c in mac if c in string.hexdigits).upper()
25+
26+
27+
def get_connected_adapters_mac_address():
28+
# make a list to collect connected adapter's MAC addresses along with the transport name
29+
connected_adapters_mac = []
30+
# use the getmac command to extract
31+
for potential_mac in subprocess.check_output("getmac").decode().splitlines():
32+
# parse the MAC address from the line
33+
mac_address = mac_address_regex.search(potential_mac)
34+
# parse the transport name from the line
35+
transport_name = transport_name_regex.search(potential_mac)
36+
if mac_address and transport_name:
37+
# if a MAC and transport name are found, add them to our list
38+
connected_adapters_mac.append((mac_address.group(), transport_name.group()))
39+
return connected_adapters_mac
40+
41+
42+
def get_user_adapter_choice(connected_adapters_mac):
43+
# print the available adapters
44+
for i, option in enumerate(connected_adapters_mac):
45+
print(f"#{i}: {option[0]}, {option[1]}")
46+
if len(connected_adapters_mac) <= 1:
47+
# when there is only one adapter, choose it immediately
48+
return connected_adapters_mac[0]
49+
# prompt the user to choose a network adapter index
50+
try:
51+
choice = int(input("Please choose the interface you want to change the MAC address:"))
52+
# return the target chosen adapter's MAC and transport name that we'll use later to search for our adapter
53+
# using the reg QUERY command
54+
return connected_adapters_mac[choice]
55+
except:
56+
# if -for whatever reason- an error is raised, just quit the script
57+
print("Not a valid choice, quitting...")
58+
exit()
59+
60+
61+
def change_mac_address(adapter_transport_name, new_mac_address):
62+
# use reg QUERY command to get available adapters from the registry
63+
output = subprocess.check_output(f"reg QUERY " + network_interface_reg_path.replace("\\\\", "\\")).decode()
64+
for interface in re.findall(rf"{network_interface_reg_path}\\\d+", output):
65+
# get the adapter index
66+
adapter_index = int(interface.split("\\")[-1])
67+
interface_content = subprocess.check_output(f"reg QUERY {interface.strip()}").decode()
68+
if adapter_transport_name in interface_content:
69+
# if the transport name of the adapter is found on the output of the reg QUERY command
70+
# then this is the adapter we're looking for
71+
# change the MAC address using reg ADD command
72+
changing_mac_output = subprocess.check_output(f"reg add {interface} /v NetworkAddress /d {new_mac_address} /f").decode()
73+
# print the command output
74+
print(changing_mac_output)
75+
# break out of the loop as we're done
76+
break
77+
# return the index of the changed adapter's MAC address
78+
return adapter_index
79+
80+
81+
def disable_adapter(adapter_index):
82+
# use wmic command to disable our adapter so the MAC address change is reflected
83+
disable_output = subprocess.check_output(f"wmic path win32_networkadapter where index={adapter_index} call disable").decode()
84+
return disable_output
85+
86+
87+
def enable_adapter(adapter_index):
88+
# use wmic command to enable our adapter so the MAC address change is reflected
89+
enable_output = subprocess.check_output(f"wmic path win32_networkadapter where index={adapter_index} call enable").decode()
90+
return enable_output
91+
92+
93+
if __name__ == "__main__":
94+
import argparse
95+
parser = argparse.ArgumentParser(description="Python Windows MAC changer")
96+
parser.add_argument("-r", "--random", action="store_true", help="Whether to generate a random MAC address")
97+
parser.add_argument("-m", "--mac", help="The new MAC you want to change to")
98+
args = parser.parse_args()
99+
if args.random:
100+
# if random parameter is set, generate a random MAC
101+
new_mac_address = get_random_mac_address()
102+
elif args.mac:
103+
# if mac is set, use it after cleaning
104+
new_mac_address = clean_mac(args.mac)
105+
106+
connected_adapters_mac = get_connected_adapters_mac_address()
107+
old_mac_address, target_transport_name = get_user_adapter_choice(connected_adapters_mac)
108+
print("[*] Old MAC address:", old_mac_address)
109+
adapter_index = change_mac_address(target_transport_name, new_mac_address)
110+
print("[+] Changed to:", new_mac_address)
111+
disable_adapter(adapter_index)
112+
print("[+] Adapter is disabled")
113+
enable_adapter(adapter_index)
114+
print("[+] Adapter is enabled again")

M/malaria-classification/README.md

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,2 @@
1+
# To run this:
2+
- `pip3 install -r requirements.txt`
Lines changed: 112 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,112 @@
1+
import cv2
2+
import tensorflow as tf
3+
from tensorflow.keras.models import Sequential
4+
from tensorflow.keras.layers import Dense, Conv2D, MaxPool2D, Flatten, Activation
5+
from sklearn.model_selection import train_test_split
6+
import numpy as np
7+
import matplotlib.pyplot as plt
8+
9+
import glob
10+
import os
11+
12+
# after you extract the dataset,
13+
# put cell_images folder in the working directory
14+
img_dir="cell_images"
15+
img_size=70
16+
17+
def load_img_data(path):
18+
image_files = glob.glob(os.path.join(path, "Parasitized/*.png")) + \
19+
glob.glob(os.path.join(path, "Uninfected/*.png"))
20+
X, y = [], []
21+
for image_file in image_files:
22+
# 0 for uninfected and 1 for infected
23+
label = 0 if "Uninfected" in image_file else 1
24+
# load the image in gray scale
25+
img_arr = cv2.imread(image_file, cv2.IMREAD_GRAYSCALE)
26+
# resize the image to (70x70)
27+
img_resized = cv2.resize(img_arr, (img_size, img_size))
28+
X.append(img_resized)
29+
y.append(label)
30+
return X, y
31+
32+
# load the data
33+
X, y = load_img_data(img_dir)
34+
# reshape to (n_samples, 70, 70, 1) (to fit the NN)
35+
X = np.array(X).reshape(-1, img_size, img_size, 1)
36+
# scale pixels from the range [0, 255] to [0, 1]
37+
# to help the neural network learn much faster
38+
X = X / 255
39+
40+
# shuffle & split the dataset
41+
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.1, stratify=y)
42+
print("Total training samples:", X_train.shape)
43+
print("Total validation samples:", X_test.shape[0])
44+
45+
model = Sequential()
46+
model.add(Conv2D(64, (3, 3), input_shape=X_train.shape[1:]))
47+
model.add(Activation("relu"))
48+
model.add(MaxPool2D(pool_size=(2, 2)))
49+
50+
model.add(Conv2D(64, (3, 3)))
51+
model.add(Activation("relu"))
52+
model.add(MaxPool2D(pool_size=(2, 2)))
53+
54+
model.add(Conv2D(64, (3, 3)))
55+
model.add(Activation("relu"))
56+
model.add(MaxPool2D(pool_size=(2, 2)))
57+
58+
model.add(Flatten())
59+
60+
model.add(Dense(64))
61+
model.add(Activation("relu"))
62+
63+
model.add(Dense(64))
64+
model.add(Activation("relu"))
65+
66+
model.add(Dense(1))
67+
model.add(Activation("sigmoid"))
68+
69+
model.compile(loss="binary_crossentropy", optimizer="adam", metrics=["accuracy"])
70+
71+
# train the model with 3 epochs, 64 batch size
72+
model.fit(X_train, np.array(y_train), batch_size=64, epochs=3, validation_split=0.2)
73+
# if you already trained the model, uncomment below and comment above
74+
# so you can only load the previously trained model
75+
# model.load_weights("malaria-cell-cnn.h5")
76+
77+
loss, accuracy = model.evaluate(X_test, np.array(y_test), verbose=0)
78+
print(f"Testing on {len(X_test)} images, the results are\n Accuracy: {accuracy} | Loss: {loss}")
79+
80+
# save the model & weights
81+
model.save("malaria-cell-cnn.h5")
82+
83+
# testing some images
84+
uninfected_cell = "cell_images/testing-samples/C1_thinF_IMG_20150604_104919_cell_82.png"
85+
infected_cell = "cell_images/testing-samples/C38P3thinF_original_IMG_20150621_112116_cell_204.png"
86+
87+
_, ax = plt.subplots(1, 2)
88+
ax[0].imshow(plt.imread(uninfected_cell))
89+
ax[0].title.set_text("Uninfected Cell")
90+
ax[1].imshow(plt.imread(infected_cell))
91+
ax[1].title.set_text("Parasitized Cell")
92+
plt.show()
93+
94+
img_arr_uninfected = cv2.imread(uninfected_cell, cv2.IMREAD_GRAYSCALE)
95+
img_arr_infected = cv2.imread(infected_cell, cv2.IMREAD_GRAYSCALE)
96+
# resize the images to (70x70)
97+
img_arr_uninfected = cv2.resize(img_arr_uninfected, (img_size, img_size))
98+
img_arr_infected = cv2.resize(img_arr_infected, (img_size, img_size))
99+
# scale to [0, 1]
100+
img_arr_infected = img_arr_infected / 255
101+
img_arr_uninfected = img_arr_uninfected / 255
102+
# reshape to fit the neural network dimensions
103+
# (changing shape from (70, 70) to (1, 70, 70, 1))
104+
img_arr_infected = img_arr_infected.reshape(1, *img_arr_infected.shape)
105+
img_arr_infected = np.expand_dims(img_arr_infected, axis=3)
106+
img_arr_uninfected = img_arr_uninfected.reshape(1, *img_arr_uninfected.shape)
107+
img_arr_uninfected = np.expand_dims(img_arr_uninfected, axis=3)
108+
# perform inference
109+
infected_result = model.predict(img_arr_infected)[0][0]
110+
uninfected_result = model.predict(img_arr_uninfected)[0][0]
111+
print(f"Infected: {infected_result}")
112+
print(f"Uninfected: {uninfected_result}")
Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,5 @@
1+
tensorflow
2+
sklearn
3+
numpy
4+
matplotlib
5+
opencv-python

M/markdown-editor/README.md

Whitespace-only changes.

0 commit comments

Comments
 (0)