text:
using AdventOfCode.Shared;
using System;
using System.Linq;

namespace AdventOfCode.Day14
{
    public class Day14 : IAdventDay
    {
        public object SolvePartOne()
        {
            var lines = InputLineParser.GetAllLines(Day14Input.REINDEERS);
            var track = new Track();

            foreach (var line in lines)
            {
                var reindeer = ReindeerParser.ParseReindeer(line);
                track.Commit(reindeer);
            }

            track.LetThemRunFor(2503);

            var distance = track.GetLeadersByTraveledDistance().Max(r => r.TraveledDistance);

            return distance;
        }

        public object SolvePartTwo()
        {
            var lines = InputLineParser.GetAllLines(Day14Input.REINDEERS);
            var track = new Track();

            foreach (var line in lines)
            {
                var reindeer = ReindeerParser.ParseReindeer(line);
                track.Commit(reindeer);
            }

            for (int i = 0; i < 2503; i++)
            {
                track.AdvanceAllBySecond();
                var temporaryLeaders = track.GetLeadersByTraveledDistance();
                foreach (var leader in temporaryLeaders)
                {
                    leader.AwardByPoints(1);
                }
            }

            var winner = track.GetWinnerByScore();

            return winner.Score;
        }

        public string PuzzleName => "Reindeer Olympics";
    }
}

redpajama_set_name: RedPajamaGithub


text:
cd src/Dime/FrontendBundle/Resources/public
../../../../../dart-sdk/bin/pub get
../../../../../dart-sdk/bin/pub run build_runner build --config=release -o build


text:
import datetime

from django.db import models, transaction
from django.urls import reverse
from django_countries.fields import CountryField

from workshops.mixins import (
    AssignmentMixin,
    CreatedUpdatedMixin,
    COCAgreementMixin,
    DataPrivacyAgreementMixin,
    EventLinkMixin,
    HostResponsibilitiesMixin,
    StateMixin,
    InstructorAvailabilityMixin,
)
from workshops.models import (
    STR_LONGEST,
    Language,
    KnowledgeDomain,
    AcademicLevel,
    ComputingExperienceLevel,
    Curriculum,
    InfoSource,
    CommonRequest,
)

class DataVariant(models.Model):
    name = models.CharField(
        max_length=300,
        null=False,
        blank=False,
        default="",
        unique=True,
        verbose_name="Name",
        help_text="Data variant name and description",
    )
    unknown = models.BooleanField(
        null=False,
        blank=True,
        default=False,
        verbose_name="Unknown entry",
        help_text="Mark this record as 'I don't know yet', or "
        "'Unknown', or 'Not sure yet'. There can be only one such "
        "record in the database.",
    )

    class Meta:
        verbose_name = "Data variant"
        verbose_name_plural = "Data variants"
        ordering = [
            "id",
        ]

    def __str__(self):
        return self.name

    @transaction.atomic
    def save(self, *args, **kwargs):
        """When saving with `unknown=True`, update all other records with this
        parameter to `unknown=False`. This helps keeping only one record with
        `unknown=True` in the database - a specific case of uniqueness."""

        # wrapped in transaction in order to prevent from updating records to
        # `unknown=False` when saving fails
        if self.unknown:
            DataVariant.objects.filter(unknown=True).update(unknown=False)
        return super().save(*args, **kwargs)

class WorkshopInquiryRequest(
    AssignmentMixin,
    StateMixin,
    CreatedUpdatedMixin,
    CommonRequest,
    DataPrivacyAgreementMixin,
    COCAgreementMixin,
    HostResponsibilitiesMixin,
    InstructorAvailabilityMixin,
    EventLinkMixin,
    models.Model,
):
    """
    This model is used for storing inquiry information from anyone interested
    in The Carpentries and workshops in general.
    """

    UNSURE_CHOICE = ("", "Not sure yet.")

    location = models.CharField(
        max_length=STR_LONGEST,
        blank=False,
        null=False,
        default="",
        verbose_name="Workshop location",
        help_text="City, state, or province.",
    )
    country = CountryField(null=False, blank=False, verbose_name="Country",)
    # Here starts "Your Audience" part with this description:
    # The Carpentries offers several different workshops intended for audiences
    # from different domain backgrounds, with different computational
    # experience and learning goals. Your responses to the following questions
    # will help us advise you on which workshop(s) may best serve your
    # audience. All questions are optional so please share as much as you can.
    routine_data = models.ManyToManyField(
        DataVariant,
        blank=True,
        verbose_name="What kinds of data does your target audience routinely "
        "work with?",
        help_text="Check all that apply.",
    )
    routine_data_other = models.CharField(
        max_length=STR_LONGEST,
        blank=True,
        default="",
        verbose_name="Other kinds of routinely worked-with data",
    )
    domains = models.ManyToManyField(
        KnowledgeDomain,
        blank=True,
        verbose_name="Domains or topic of interest for target audience",
        help_text="The attendees' academic field(s) of study, if known. Check "
        "all that apply.",
    )
    domains_other = models.CharField(
        max_length=STR_LONGEST, blank=True, default="", verbose_name="Other domains",
    )
    academic_levels = models.ManyToManyField(
        AcademicLevel,
        blank=True,
        verbose_name="Attendees' academic level / career stage",
        help_text="If you know the academic level(s) of your attendees, "
        "indicate them here. Check all that apply.",
    )
    computing_levels = models.ManyToManyField(
        ComputingExperienceLevel,
        blank=True,
        verbose_name="Attendees' level of computing experience",
        help_text="Indicate the attendees' level of computing experience, if "
        "known. We will ask attendees to fill in a skills survey "
        "before the workshop, so this answer can be an "
        "approximation. Check all that apply.",
    )
    audience_description = models.TextField(
        blank=True,
        verbose_name="Please describe your anticipated audience, including "
        "their experience, background, and goals",
    )
    SWC_LESSONS_LINK = (
        ''
        "Software Carpentry lessons page"
    )
    DC_LESSONS_LINK = (
        ''
        "Data Carpentry lessons page"
    )
    LC_LESSONS_LINK = (
        ''
        "Library Carpentry lessons page"
    )
    requested_workshop_types = models.ManyToManyField(
        Curriculum,
        limit_choices_to={"active": True},
        blank=True,
        verbose_name="Which Carpentries workshop are you requesting?",
        help_text="If your learners are new to programming and primarily "
        "interested in working with data, Data Carpentry is likely "
        "the best choice. If your learners are interested in "
        "learning more about programming, including version control"
        " and automation, Software Carpentry is likely the best "
        "match. If your learners are people working in library and "
        "information related roles interested in learning data and "
        "software skills, Library Carpentry is the best choice. "
        "Please visit the "
        + SWC_LESSONS_LINK
        + ", "
        + DC_LESSONS_LINK
        + ", or the "
        + LC_LESSONS_LINK
        + " for more information about any of our lessons. If you're "
        "not sure and would like to discuss with us, please select "
        'the "Don\'t know yet" option below.
'
        "Check all that apply.",
    )
    preferred_dates = models.DateField(
        blank=True,
        null=True,
        verbose_name="Preferred dates",
        help_text="Our workshops typically run two full days. Please select "
        "your preferred first day for the workshop. If you do not "
        "have exact dates or are interested in an alternative "
        "schedule, please indicate so below. Because we need to "
        "coordinate with instructors, a minimum of 2-3 months lead "
        "time is required for workshop planning.",
    )
    other_preferred_dates = models.CharField(
        max_length=200,
        blank=True,
        null=False,
        default="",
        verbose_name="If your dates are not set, please provide more "
        "information below",
    )
    language = models.ForeignKey(
        Language,
        on_delete=models.PROTECT,
        blank=True,
        null=True,
        verbose_name="What is the preferred language of communication for the "
        "workshop?",
        help_text="Our workshops are offered primarily in English, with a few "
        "of our lessons available in Spanish. While materials are "
        "mainly in English, we know it can be valuable to have an "
        "instructor who speaks the native language of the learners. "
        "We will attempt to locate Instructors speaking a particular"
        " language, but cannot guarantee the availability of "
        "non-English speaking Instructors.",
    )
    ATTENDEES_NUMBER_CHOICES = (
        UNSURE_CHOICE,
        ("10-40", "10-40 (one room, two instructors)"),
        ("40-80", "40-80 (two rooms, four instructors)"),
        ("80-120", "80-120 (three rooms, six instructors)"),
    )
    number_attendees = models.CharField(
        max_length=15,
        choices=ATTENDEES_NUMBER_CHOICES,
        blank=True,
        null=True,
        default=None,
        verbose_name="Anticipated number of attendees",
        help_text="These recommendations are for in-person workshops. "
        "This number doesn't need to be precise, but will help us "
        "decide how many instructors your workshop will need. "
        "Each workshop must have at least two instructors.
"
        "For online Carpentries workshops, we recommend a maximum of "
        "20 learners per class. If your workshop attendance will "
        "exceed 20 learners please be sure to include a note in the "
        "comments section below. ",
    )
    FEE_CHOICES = (
        UNSURE_CHOICE,
        (
            "nonprofit",
            "I am with a government site, university, or other "
            "nonprofit. I understand the workshop fee of US$2500, "
            "and agree to follow through on The Carpentries "
            "invoicing process.",
        ),
        (
            "forprofit",
            "I am with a corporate or for-profit site. I understand "
            "The Carpentries staff will contact me about workshop "
            "fees. I will follow through on The Carpentries "
            "invoicing process for the agreed upon fee.",
        ),
        (
            "member",
            "I am with a Member Organisation so the workshop fee does "
            "not apply (Instructor travel costs will still apply).",
        ),
        (
            "waiver",
            "I am requesting a scholarship for the workshop fee "
            "(Instructor travel costs will still apply).",
        ),
    )
    administrative_fee = models.CharField(
        max_length=20,
        choices=FEE_CHOICES,
        blank=True,
        null=True,
        default=None,
        verbose_name="Which of the following applies to your payment for the "
        "administrative fee?",
    )
    TRAVEL_EXPENCES_MANAGEMENT_CHOICES = (
        UNSURE_CHOICE,
        (
            "booked",
            "Hotel and airfare will be booked by site; ground travel "
            "and meals/incidentals will be reimbursed within 60 days.",
        ),
        (
            "reimbursed",
            "All expenses will be booked by instructors and "
            "reimbursed within 60 days.",
        ),
        ("other", "Other:"),
    )
    travel_expences_management = models.CharField(
        max_length=20,
        null=False,
        blank=True,
        default="",
        choices=TRAVEL_EXPENCES_MANAGEMENT_CHOICES,
        verbose_name="How will you manage travel expenses for Carpentries "
        "Instructors?",
    )
    travel_expences_management_other = models.CharField(
        max_length=STR_LONGEST,
        null=False,
        blank=True,
        default="",
        verbose_name="Other travel expences management",
    )
    travel_expences_agreement = models.BooleanField(
        null=False,
        blank=False,
        default=False,
        verbose_name="Regardless of the fee due to The Carpentries, I "
        "understand I am also responsible for travel costs for "
        "the Instructors which can include airfare, ground "
        "travel, hotel, and meals/incidentals. I understand "
        "local Instructors will be prioritized but not "
        "guaranteed. Instructor travel costs are managed "
        "directly between the host site and the Instructors, not "
        "through The Carpentries. I will share detailed "
        "information regarding policies and procedures for "
        "travel arrangements with instructors. All "
        "reimbursements will be completed within 60 days of "
        "the workshop.",
    )
    RESTRICTION_CHOICES = (
        UNSURE_CHOICE,
        ("no_restrictions", "No restrictions."),
        ("other", "Other:"),
    )
    institution_restrictions = models.CharField(
        max_length=20,
        null=False,
        blank=True,
        default="",
        choices=RESTRICTION_CHOICES,
        verbose_name="Our instructors live, teach, and travel globally. We "
        "understand that institutions may have citizenship, "
        "confindentiality agreements or other requirements for "
        "employees or volunteers who facilitate workshops. If "
        "your institution fits this description, please share "
        "your requirements or note that there are no "
        "restrictions.",
    )
    institution_restrictions_other = models.CharField(
        max_length=STR_LONGEST,
        null=False,
        blank=True,
        default="",
        verbose_name="Other (institution restrictions)",
    )
    carpentries_info_source = models.ManyToManyField(
        InfoSource,
        blank=True,
        verbose_name="How did you hear about The Carpentries?",
        help_text="Check all that apply.",
    )
    carpentries_info_source_other = models.CharField(
        max_length=STR_LONGEST,
        null=False,
        blank=True,
        default="",
        verbose_name="Other source for information about The Carpentries",
    )
    user_notes = models.TextField(
        blank=True,
        verbose_name="Will this workshop be conducted in-person or online? "
        "Is there any other information you would like to share "
        "with us?",
        help_text="Knowing if this workshop is on-line or in-person will "
        "help ensure we can best support you in coordinating the event.",
    )

    # override field `public_event` from CommonRequest mixin
    public_event = models.CharField(
        max_length=CommonRequest._meta.get_field("public_event").max_length,
        null=False,
        blank=True,
        default="",
        choices=(UNSURE_CHOICE,)
        + CommonRequest._meta.get_field("public_event").choices,
        verbose_name=CommonRequest._meta.get_field("public_event").verbose_name,
        help_text=CommonRequest._meta.get_field("public_event").help_text,
    )

    class Meta:
        ordering = ["created_at"]

    def __str__(self):
        return (
            "Workshop inquiry ({institution}, {personal} {family}) - {state}"
        ).format(
            institution=str(self.institution or self.institution_other_name),
            personal=self.personal,
            family=self.family,
            state=self.get_state_display(),
        )

    def dates(self):
        if self.preferred_dates:
            return "{:%Y-%m-%d}".format(self.preferred_dates)
        else:
            return self.other_preferred_dates

    def preferred_dates_too_soon(self):
        # set cutoff date at 2 months
        cutoff = datetime.timedelta(days=2 * 30)
        if self.preferred_dates:
            return (self.preferred_dates - self.created_at.date()) < cutoff
        return False

    def get_absolute_url(self):
        return reverse("workshopinquiry_details", args=[self.id])

class SelfOrganisedSubmission(
    AssignmentMixin,
    StateMixin,
    CreatedUpdatedMixin,
    CommonRequest,
    DataPrivacyAgreementMixin,
    COCAgreementMixin,
    HostResponsibilitiesMixin,
    EventLinkMixin,
    models.Model,
):
    """
    This model is used for storing user-submitted self-organised workshop
    information. It's very similar to Workshop Submission combined with
    DC Self-Organized Workshop Request.
    """

    start = models.DateField(
        null=True,
        verbose_name="Workshop start date",
        help_text="Please provide the dates that your Self-Organised workshop will"
        " run.",
    )
    end = models.DateField(
        null=True,
        verbose_name="Workshop end date"
    )
    workshop_url = models.URLField(
        max_length=STR_LONGEST,
        blank=True,
        null=False,
        default="",
        verbose_name="Please share your workshop URL",
        help_text="Use the link to the website, not the repository. This is "
        "typically in the format https://username.github.io/"
        "YYYY-MM-DD-sitename.  If you are running an online workshop, "
        "please use the format YYYY-MM-DD-sitename-online.",
    )
    FORMAT_CHOICES = (
        ("standard", "Standard two-day Carpentries workshop"),
        ("short", "Short session (less than two days)"),
        (
            "periodic",
            "Modules taught over a period of time (several weeks, "
            "one semester, etc.)",
        ),
        ("other", "Other:"),
    )
    workshop_format = models.CharField(
        max_length=20,
        null=False,
        blank=False,
        default="",
        choices=FORMAT_CHOICES,
        verbose_name="What is the format of this workshop?",
    )
    workshop_format_other = models.CharField(
        max_length=STR_LONGEST,
        null=False,
        blank=True,
        default="",
        verbose_name="Other workshop format",
    )
    workshop_types = models.ManyToManyField(
        Curriculum,
        limit_choices_to={"active": True},
        blank=False,
        verbose_name="Which Carpentries workshop are you teaching?",
    )
    workshop_types_other = models.CharField(
        max_length=STR_LONGEST,
        null=False,
        blank=True,
        default="",
        verbose_name="Other workshop types",
    )
    workshop_types_other_explain = models.TextField(
        blank=True,
        verbose_name='If you selected "Mix & Match", please provide more'
        " information here",
        help_text="For example \"We are teaching Software Carpentry's Git "
        'lesson only" or "We are teaching Data Carpentry\'s Ecology '
        'workshop, but not teaching a programming language."',
    )
    country = CountryField(null=True, blank=False, verbose_name="Country",)
    language = models.ForeignKey(
        Language,
        on_delete=models.PROTECT,
        blank=False,
        null=False,
        verbose_name="What language is this workshop being conducted in?",
    )

    class Meta:
        verbose_name = "Self-Organised Submission"
        verbose_name_plural = "Self-Organised Submissions"
        ordering = ["created_at"]

    def __str__(self):
        return (
            "Self-Organised Submission ({institution}, {personal} {family}) - {state}"
        ).format(
            institution=str(self.institution or self.institution_other_name),
            personal=self.personal,
            family=self.family,
            state=self.get_state_display(),
        )

    def get_absolute_url(self):
        return reverse("selforganisedsubmission_details", args=[self.id])


text:
package cz.muni.fi.xklinec.whiteboxAES;

import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.security.AlgorithmParameters;
import java.security.InvalidAlgorithmParameterException;
import java.security.InvalidKeyException;
import java.security.Key;
import java.security.NoSuchAlgorithmException;
import java.security.SecureRandom;
import java.security.spec.AlgorithmParameterSpec;

import javax.crypto.BadPaddingException;
import javax.crypto.Cipher;
import javax.crypto.CipherSpi;
import javax.crypto.IllegalBlockSizeException;
import javax.crypto.NoSuchPaddingException;
import javax.crypto.ShortBufferException;

import cz.muni.fi.xklinec.whiteboxAES.generator.ExternalBijections;
import cz.muni.fi.xklinec.whiteboxAES.generator.Generator;

/**
 * Standard Java Crypto API for White-box AES.
 *
 * @author BacinskaL
 */
public final class AES_Cipher extends CipherSpi {

	private Generator generator = null;
	private boolean isEncrypting = true;
	private ExternalBijections extb = null;
	private AES coreAES = null;
	private byte[] dataBuffer = null;
	private int dataBufferActiveLength = 0;
	private State state = null;
	private int paddingScheme = 0; //0=NoPadding, 1=ISO9797m1, 2=ISO9797, 5=PKCS5

	/**
     * Creates an instance of WBAES with ECB mode.
     */
    public AES_Cipher() {
        generator = new Generator();
        dataBuffer = new byte[State.BYTES];
    }

    /*
     * Adds padding to the block of data
     */
	private void addPadding(byte[] data, int dataOffset, int dataLength) {
		int blockSize = engineGetBlockSize();

		if(paddingScheme == 2) {
			data[dataOffset] = (byte) 0x80;
			dataOffset++;
			dataLength++;

			if(dataLength > blockSize)
				dataLength = dataLength - blockSize;
		}

		if(paddingScheme == 1 || paddingScheme == 2) {
			while(dataLength < blockSize) {
				data[dataOffset] = (byte) 0x00;
				dataOffset++;
				dataLength++;
			}
		}

		if(dataLength == blockSize) dataLength = 0;

		if(paddingScheme == 5) {
			byte missingBytesNum = (byte)(blockSize - dataLength); //spravna operace?
			for(int iter = dataOffset; iter<data.length; iter++) {
				data[iter] = missingBytesNum;
			}
		}
	}

	/*
	 * Counts length od padding to be able to remove it
	 */
	private int paddingCount(byte[] data) throws BadPaddingException {

	    int count = data.length - 1; //?

	    if(paddingScheme == 1 || paddingScheme == 2)
		    while (count > 0 && data[count] == 0) count--;

		if (data[count] != (byte)0x80 && paddingScheme == 2)
			throw new BadPaddingException("Wrong padding - block corrupted");

		if(paddingScheme == 1)
			count++;

	    if(paddingScheme == 5)
	    	return data[count];

	    return data.length - count;
	}

    /**
     * Encrypts or decrypts data in a single-part operation, or finishes a multiple-part
     * operation.
     * The data is encrypted or decrypted, depending on how this cipher was initialized.
     *
     *
The first inputLen bytes in the input buffer,
     * starting at inputOffset, and any input bytes that may have been
     * buffered during a previous update operation, are processed,
     * with padding (if requested) being applied.
     * The result is stored in a new buffer.
     *
     *
The cipher is reset to its initial state (uninitialized) after this call.
     *
     * @param input the input buffer
     * @param inputOffset the offset in input where the input starts
     * @param inputLen the input length
     *
     * @return the new buffer with the result
     *
     * @exception IllegalBlockSizeException if this cipher is a block cipher,
     * no padding has been requested (only in encryption mode), and the total
     * input length of the data processed by this cipher is not a multiple of
     * block size
     * @exception BadPaddingException if this cipher is in decryption mode,
     * and (un)padding has been requested, but the decrypted data is not
     * bounded by the appropriate padding bytes
     */
	protected byte[] engineDoFinal(byte[] input, int inputOffset, int inputLen)
			throws IllegalBlockSizeException, BadPaddingException {

		int length = 0;
		byte[] out = new byte[engineGetOutputSize(inputLen)];
		try {
			length = engineDoFinal(input, inputOffset, inputLen, out, 0);
		} catch(ShortBufferException e) { /*?*/ }

		if(length != out.length) {
			byte[] output = new byte[length];
			System.arraycopy(out, 0, output, 0, length);
			out = output;
		}
		return out;
	}

	/**
     * Encrypts or decrypts data in a single-part operation, or finishes a multiple-part
     * operation.
     * The data is encrypted or decrypted, depending on how this cipher was initialized.
     *
     *
The first inputLen bytes in the input buffer,
     * starting at inputOffset, and any input bytes that may have been
     * buffered during a previous update operation, are processed,
     * with padding (if requested) being applied.
     * The result is stored in the output buffer, starting at outputOffset.
     *
     *
The cipher is reset to its initial state (uninitialized) after this call.
     *
     * @param input the input buffer
     * @param inputOffset the offset in input where the input starts
     * @param inputLen the input length
     * @param output the buffer for the result
     * @param outputOffset the offset in output where the result is stored
     *
     * @return the number of bytes stored in output
     *
     * @exception IllegalBlockSizeException if this cipher is a block cipher,
     * no padding has been requested (only in encryption mode), and the total
     * input length of the data processed by this cipher is not a multiple of
     * block size
     * @exception ShortBufferException if the given output buffer is too small
     * to hold the result
     * @exception BadPaddingException if this cipher is in decryption mode,
     * and (un)padding has been requested, but the decrypted data is not
     * bounded by the appropriate padding bytes
     */
	protected int engineDoFinal(byte[] input, int inputOffset, int inputLen, byte[] output, int outputOffset)
			throws ShortBufferException, IllegalBlockSizeException, BadPaddingException {

		int blockSize = engineGetBlockSize();
		int length = dataBufferActiveLength + inputLen;

		// check for "nothing to be done"
		if(length == 0)
			return 0;

		if(length % blockSize != 0 && paddingScheme == 0)
			throw new BadPaddingException("No padding used, input length n*blockSize expected");

		int outputSize = engineGetOutputSize(inputLen);

		// output size checking
		if ((output == null) || ((output.length - outputOffset) < outputSize)) {
			throw new ShortBufferException("Short output buffer - " + length + " bytes needed");
		}

		byte[] dataBufferWithInput = new byte[outputSize];
		System.arraycopy(dataBuffer, 0, dataBufferWithInput, 0, dataBufferActiveLength);
		System.arraycopy(input, inputOffset, dataBufferWithInput, dataBufferActiveLength, inputLen);

		int lastBlockSize = length % blockSize;
		if(lastBlockSize == 0 && length > 0 && paddingScheme != 0)
			lastBlockSize = blockSize;
		//int lastBlockOffset = length - lastBlockSize;
		//int blocksNumber = lastBlockOffset / blockSize;

		if(isEncrypting && paddingScheme != 0) {
			addPadding(dataBufferWithInput, length, lastBlockSize);
		}

		// prepisat outputLength s length a i - abo asi radsi nechat, ale s while
		int outputLength = 0;
		for(int i = 0; i < outputSize; i += blockSize) {
			byte[] processingBlock = new byte[blockSize];
			System.arraycopy(dataBufferWithInput, i, processingBlock, 0, blockSize);

			state = new State(processingBlock, true,  false);
			state.transpose();
		    generator.applyExternalEnc(state, extb, true);
		    coreAES.crypt(state);
		    generator.applyExternalEnc(state, extb, false);

		    System.arraycopy(state.getState(), 0, output, outputOffset + outputLength, blockSize);
			outputLength += blockSize;
		}

		if(!isEncrypting && paddingScheme != 0) {
			int paddingLength = paddingCount(output);
			return outputLength - paddingLength;
		}

		return outputLength;
	}

    /**
     * Returns the block size (in bytes).
     *
     * @return the block size (in bytes), or 0 if the underlying algorithm is not a block cipher
     */
	protected int engineGetBlockSize() {
		return State.BYTES;
	}

    /**
     * Returns the initialization vector (IV) in a new buffer.
     *
     *
This is useful in the case where a random IV has been created
     * (see init),
     * or in the context of password-based encryption or
     * decryption, where the IV is derived from a user-provided password.
     *
     * @return the initialization vector in a new buffer, or null if the underlying
     * algorithm does not use an IV, or if the IV has not yet been set.
     */
	protected byte[] engineGetIV() {
		return null; 	//current implementation doesn't support modes using IV
	}

    /**
     * Returns the length in bytes that an output buffer would need to be in order
     * to hold the result of the next update or doFinal
     * operation, given the input length inputLen (in bytes).
     *
     *
This call takes into account any unprocessed (buffered) data from a
     * previous update call, and padding.
     *
     *
The actual output length of the next update or doFinal
     * call may be smaller than the length returned by this method.
     *
     * @param inputLen the input length (in bytes)
     *
     * @return the required output buffer size (in bytes)
     */
	protected int engineGetOutputSize(int inputLen) {
		int size = dataBufferActiveLength + inputLen; //ak sa nebude pridavat padding, rovno hodit do return

		int blockSize = engineGetBlockSize();
		int blocksNumber = (size + blockSize - 1) / blockSize;
		if(isEncrypting && (size % blockSize == 0) && (paddingScheme == 2 || paddingScheme == 5)) blocksNumber++;
		// when decrypting - return sumLen, when encrypting only without padding
		return blocksNumber * blockSize;
	}

    /**
     * Returns the parameters used with this cipher.
     *
     *
The returned parameters may be the same that were used to initialize
     * this cipher, or may contain the default set of parameters or a set of
     * randomly generated parameters used by the underlying cipher
     * implementation (provided that the underlying cipher implementation
     * uses a default set of parameters or creates new parameters if it needs
     * parameters but was not initialized with any).
     *
     * @return the parameters used with this cipher, or null if this cipher
     * does not use any parameters.
     */
	protected AlgorithmParameters engineGetParameters() {
		return null; //the only parameter for EAS would be IV, but not in this implementation (ECB mode)
	}

	/*
	 * converts Key to byte array
	 */
    private byte[] getKey(Key key) throws InvalidKeyException {
        if (key == null) {
            throw new InvalidKeyException("No key data");
        }
        if (!(key.getFormat()).equals("RAW")) {
            throw new InvalidKeyException("Wrong format: RAW needed");
        }
        byte[] keyBytes = key.getEncoded();
        if (keyBytes == null) {
            throw new InvalidKeyException("RAW key bytes missing");
        }
        return keyBytes;
    }

    /**
     * Initializes this cipher with a key and a source of randomness.
     *
     *
The cipher is initialized for one of the following four operations:
     * encryption, decryption, key wrapping or key unwrapping, depending on
     * the value of opmode.
     *
     *
If this cipher requires an initialization vector (IV), it will get
     * it from random.
     * This behaviour should only be used in encryption or key wrapping
     * mode, however.
     * When initializing a cipher that requires an IV for decryption or
     * key unwrapping, the IV
     * (same IV that was used for encryption or key wrapping) must be provided
     * explicitly as a
     * parameter, in order to get the correct result.
     *
     *
This method also cleans existing buffer and other related state
     * information.
     *
     * @param opmode the operation mode of this cipher (this is one of
     * the following:
     * ENCRYPT_MODE, DECRYPT_MODE,
     * WRAP_MODE or UNWRAP_MODE)
     * @param key the secret key
     * @param random the source of randomness
     *
     * @exception InvalidKeyException if the given key is inappropriate for
     * initializing this cipher
     */
    protected void engineInit(int opmode, Key key, SecureRandom random)
			throws InvalidKeyException {
        try {
    		this.engineInit(opmode, key, (AlgorithmParameterSpec)null, random);
	    } catch (InvalidAlgorithmParameterException e) {
	        throw new InvalidKeyException(e.getMessage());
	    }
	}

    /**
     * Initializes this cipher with a key, a set of
     * algorithm parameters, and a source of randomness.
     *
     *
The cipher is initialized for one of the following four operations:
     * encryption, decryption, key wrapping or key unwrapping, depending on
     * the value of opmode.
     *
     *
If this cipher (including its underlying feedback or padding scheme)
     * requires any random bytes, it will get them from random.
     *
     * @param opmode the operation mode of this cipher (this is one of
     * the following:
     * ENCRYPT_MODE, DECRYPT_MODE,
     * WRAP_MODE or UNWRAP_MODE)
     * @param key the encryption key
     * @param params the algorithm parameters
     * @param random the source of randomness
     *
     * @exception InvalidKeyException if the given key is inappropriate for
     * initializing this cipher
     * @exception InvalidAlgorithmParameterException if the given algorithm
     * parameters are inappropriate for this cipher
     */
	protected void engineInit(int opmode, Key key, AlgorithmParameterSpec params, SecureRandom random)
			throws InvalidKeyException, InvalidAlgorithmParameterException {

		if(params != null)
			throw new InvalidAlgorithmParameterException("Current impelmentation doesn't support AlgorithmParameter");

        isEncrypting = (opmode == Cipher.ENCRYPT_MODE);

		if(key == null) {

			try {
		        FileInputStream fileIn = new FileInputStream("extb_tables_" + isEncrypting + ".ser");
		        ObjectInputStream in = new ObjectInputStream(fileIn);
		        extb = (ExternalBijections) in.readObject();
		        coreAES = (AES) in.readObject();
		        in.close();
		        fileIn.close();
		        System.out.println("Serialized data read successfully");
			} catch(IOException i) {
		        //i.printStackTrace();
				throw new InvalidKeyException(i.getMessage());
		    } catch(ClassNotFoundException c) {
		        System.out.println("ExternalBijections class (bijections) not found");
		        c.printStackTrace();
		        return;
		    }

		}
		else {

	    	byte[] keyBytes = getKey(key);

	    	if(random != null)
	    		generator.setRand(random);

	    	extb = new ExternalBijections();
	        generator.generateExtEncoding(extb, 0);

	        // all protections are enabled (transformations are not identities)
	        generator.setUseIO04x04Identity(false);
	        generator.setUseIO08x08Identity(false);
	        generator.setUseMB08x08Identity(false);
	        generator.setUseMB32x32Identity(false);

	        try {
	        	generator.generate(isEncrypting, keyBytes, keyBytes.length, extb);
	        } catch (ArrayIndexOutOfBoundsException e) {throw new InvalidKeyException("Wrong key length");}
	        coreAES = generator.getAESi();

	        try {
	        	FileOutputStream fileOut = new FileOutputStream("extb_tables_" + isEncrypting + ".ser");
	            ObjectOutputStream out = new ObjectOutputStream(fileOut);
	            out.writeObject(extb);
	            out.writeObject(coreAES);
	            out.flush();
	            out.close();
	            fileOut.close();
	            System.out.println("Serialized data is saved in extb_tables_" + isEncrypting + ".ser");
	        } catch(IOException i) {
	            i.printStackTrace();
	        }

		}
	}

    /**
     * Initializes this cipher with a key, a set of
     * algorithm parameters, and a source of randomness.
     *
     *
The cipher is initialized for one of the following four operations:
     * encryption, decryption, key wrapping or key unwrapping, depending on
     * the value of opmode.
     *
     *
If this cipher (including its underlying feedback or padding scheme)
     * requires any random bytes, it will get them from random.
     *
     * @param opmode the operation mode of this cipher (this is one of
     * the following:
     * ENCRYPT_MODE, DECRYPT_MODE,
     * WRAP_MODE or UNWRAP_MODE)
     * @param key the encryption key
     * @param params the algorithm parameters
     * @param random the source of randomness
     *
     * @exception InvalidKeyException if the given key is inappropriate for
     * initializing this cipher
     * @exception InvalidAlgorithmParameterException if the given algorithm
     * parameters are inappropriate for this cipher
     */
	protected void engineInit(int opmode, Key key, AlgorithmParameters params, SecureRandom random)
			throws InvalidKeyException, InvalidAlgorithmParameterException {
		if(params != null)
			throw new InvalidAlgorithmParameterException("Current impelmentation doesn't support AlgorithmParameter");

		this.engineInit(opmode, key, (AlgorithmParameterSpec)null, random);
	}

    /**
     * Sets the mode of this cipher.
     *
     * @param mode the cipher mode
     *
     * @exception NoSuchAlgorithmException if the requested cipher mode does not exist
     */
	protected void engineSetMode(String mode) throws NoSuchAlgorithmException {
		if(mode == null)
			throw new NoSuchAlgorithmException("Mode is null"); // urcite treba vynimku?
		if(!mode.equals("ECB"))
			throw new NoSuchAlgorithmException("Only ECB mode is supported");
	}

    /**
     * Sets the padding mechanism of this cipher.
     *
     * @param padding the padding mechanism
     *
     * @exception NoSuchPaddingException if the requested padding mechanism does not exist
     */
	// state sa pri vytvarani orezava/predlzuje (ak je copy true) na 16*8 bits
	protected void engineSetPadding(String padding) throws NoSuchPaddingException {
		if(padding == null)
			throw new NoSuchPaddingException("Padding is null"); // urcite treba vynimku? tuto asi ne
		else if(padding.equalsIgnoreCase("NoPadding")) paddingScheme = 0;
		else if(padding.equalsIgnoreCase("ISO9797M1Padding")) paddingScheme = 1;
		else if(padding.equalsIgnoreCase("ISO9797M2Padding")) paddingScheme = 2;
		else if(padding.equalsIgnoreCase("PKCS5Padding")) paddingScheme = 5;
		else throw new NoSuchPaddingException(padding + " is not supported");
	}

    /**
     * Continues a multiple-part encryption or decryption operation (depending
     * on how this cipher was initialized), processing another data part.
     *
     *
The first inputLen bytes in the input
     * buffer, starting at inputOffset, are processed, and the
     * result is stored in a new buffer.
     *
     * @param input the input buffer
     * @param inputOffset the offset in input where the input starts
     * @param inputLen the input length
     *
     * @return the new buffer with the result
     *
     * @exception IllegalStateException if this cipher is in a wrong state
     * (e.g., has not been initialized)
     */
	protected byte[] engineUpdate(byte[] input, int inputOffset, int inputLen) {
		int length = 0;
		byte[] out = new byte[engineGetOutputSize(inputLen)];
		try {
			length = engineUpdate(input, inputOffset, inputLen, out, 0);
		} catch(ShortBufferException e) { /* */ }

		if(length != out.length) {
			byte[] output = new byte[length];
			System.arraycopy(out, 0, output, 0, length);
			out = output;
		}
		return out;
	}

    /**
     * Continues a multiple-part encryption or decryption operation (depending
     * on how this cipher was initialized), processing another data part.
     *
     *
The first inputLen bytes in the input
     * buffer, starting at inputOffset, are processed, and the
     * result is stored in the output buffer, starting at
     * outputOffset.
     *
     * @param input the input buffer
     * @param inputOffset the offset in input where the input starts
     * @param inputLen the input length
     * @param output the buffer for the result
     * @param outputOffset the offset in output where the result is stored
     *
     * @return the number of bytes stored in output
     *
     * @exception ShortBufferException if the given output buffer is too small
     * to hold the result
     */
	protected int engineUpdate(byte[] input, int inputOffset, int inputLen, byte[] output, int outputOffset)
			throws ShortBufferException {

		int length = dataBufferActiveLength + inputLen;

		// check for "nothing to be done"
		if(length == 0)
			return 0;

		// output size checking
		int blockSize = engineGetBlockSize();
		int processingDataLength = length  - (length % blockSize);
		if ((output == null) || ((output.length - outputOffset) < processingDataLength)) {
	        throw new ShortBufferException("Short output buffer - " + processingDataLength + " bytes needed");
	    }

		byte[] dataBufferWithInput = new byte[length];
		System.arraycopy(dataBuffer, 0, dataBufferWithInput, 0, dataBufferActiveLength);
		System.arraycopy(input, inputOffset, dataBufferWithInput, dataBufferActiveLength, inputLen);

		int outputLength = 0;
		for(int i = 0; i < processingDataLength; i += blockSize) {
			byte[] processingBlock = new byte[blockSize];
			System.arraycopy(dataBufferWithInput, i, processingBlock, 0, blockSize);

			state  = new State(processingBlock, true,  false);
			state.transpose();
            generator.applyExternalEnc(state, extb, true); //canceling the effect of external encodings in the first round
            coreAES.crypt(state);
            generator.applyExternalEnc(state, extb, false); //canceling the effect of external encodings in the last round

            System.arraycopy(state.getState(), 0, output, outputOffset + outputLength, blockSize);
			outputLength += blockSize;
		}

		dataBufferActiveLength = length % blockSize;
		System.arraycopy(dataBufferWithInput, processingDataLength, dataBuffer, 0, dataBufferActiveLength);

		return outputLength;
	}

    /**
     *  Returns the key size of the given key object.
     *
     * @param key the key object.
     *
     * @return the key size of the given key object.
     *
     * @exception InvalidKeyException if key is invalid.
     */
	// use only in secure environment?
	protected int engineGetKeySize(Key key) throws InvalidKeyException{
		return getKey(key).length;
	}

}


text:
from hopfield_network import *
from visuals import *
from alphabet import *
import numpy as np
from pylab import *

def to_state(letter):
    return array([1 if char == 'X' else -1 for char in letter.replace('\n','')])

def show_state(state):
    state = state.reshape((5, 5))
    imshow(state, cmap=cm.binary, interpolation='nearest')
    show()

myNet = VisualHopfield(25)
alphabet = [A, B, C, D, E, F, G, H, I, J, K, L, M,
        N, O, P, Q, R, S, T, U, V, W, X, Y, Z]
training_data = [to_state(letter) for letter in alphabet]
learning_data = [to_state(l1)]
myNet.run_visualization(training_data, learning_data)


text:
package com.rusticisoftware.tincan.http;

import lombok.Data;
import lombok.EqualsAndHashCode;
import org.eclipse.jetty.client.ContentExchange;
import org.eclipse.jetty.io.Buffer;
import org.eclipse.jetty.io.ByteArrayBuffer;

import java.io.IOException;
import java.util.Map;

/**
 * HTTPRequest Class Description
 */
@Data
@EqualsAndHashCode(callSuper = false)
public class HTTPRequest {
    private String method;
    private String resource;
    private Map<String, String> queryParams;
    private Map<String, String> headers;
    private String contentType;
    private ByteArrayBuffer contentBuffer;
    private byte[] content;
    private HTTPResponse response;
}


text:
export default async synchronizer => {
  await synchronizer.$store.dispatch('market/refreshTicker')
}


text:
package org.nd4j.linalg.cpu.nativecpu.rng;

import org.bytedeco.javacpp.PointerPointer;
import org.nd4j.nativeblas.NativeOps;
import org.nd4j.nativeblas.NativeOpsHolder;
import org.nd4j.nativeblas.OpaqueRandomGenerator;
import org.nd4j.rng.NativeRandom;

public class CpuNativeRandom extends NativeRandom {
    private NativeOps nativeOps;

    public CpuNativeRandom() {
        super();
    }

    public CpuNativeRandom(long seed) {
        super(seed);
    }

    public CpuNativeRandom(long seed, long numberOfElements) {
        super(seed, numberOfElements);
    }

    @Override
    public void init() {
        nativeOps = NativeOpsHolder.getInstance().getDeviceNativeOps();
        statePointer = nativeOps.createRandomGenerator(this.seed, this.seed ^ 0xdeadbeef);
    }

    @Override
    public void close() {
        nativeOps.deleteRandomGenerator((OpaqueRandomGenerator)statePointer);
    }

    @Override
    public PointerPointer getExtraPointers() {
        return null;
    }

    @Override
    public void setSeed(long seed) {
        this.seed = seed;
        this.currentPosition.set(0);
        nativeOps.setRandomGeneratorStates((OpaqueRandomGenerator)statePointer, seed, seed ^ 0xdeadbeef);
    }

    @Override
    public long getSeed() {
        return seed;
    }

    @Override
    public int nextInt() {
        return nativeOps.getRandomGeneratorNextInt((OpaqueRandomGenerator)statePointer);
    }

    @Override
    public float nextFloat() {
        return nativeOps.getRandomGeneratorNextFloat((OpaqueRandomGenerator)statePointer);
    }

    @Override
    public double nextDouble() {
        return nativeOps.getRandomGeneratorNextDouble((OpaqueRandomGenerator)statePointer);
    }

    @Override
    public long nextLong() {
        return nativeOps.getRandomGeneratorNextLong((OpaqueRandomGenerator)statePointer);
    }

    public long rootState() {
        return nativeOps.getRandomGeneratorRootState((OpaqueRandomGenerator)statePointer);
    }

    public long nodeState() {
        return nativeOps.getRandomGeneratorNodeState((OpaqueRandomGenerator)statePointer);
    }

    @Override
    public void setStates(long rootState, long nodeState) {
        nativeOps.setRandomGeneratorStates((OpaqueRandomGenerator)statePointer, rootState, nodeState);
    }
}


text:
package schema

import (
	"net/http"

	rketypes "github.com/rancher/rke/types"

	eksv1 "github.com/rancher/eks-operator/pkg/apis/eks.cattle.io/v1"
	gkev1 "github.com/rancher/gke-operator/pkg/apis/gke.cattle.io/v1"
	"github.com/rancher/norman/types"
	m "github.com/rancher/norman/types/mapper"
	v3 "github.com/rancher/rancher/pkg/apis/management.cattle.io/v3"
	"github.com/rancher/rancher/pkg/schemas/factory"
	"github.com/rancher/rancher/pkg/schemas/mapper"
	v1 "k8s.io/api/core/v1"
	apiserverconfig "k8s.io/apiserver/pkg/apis/config"
)

var (
	Version = types.APIVersion{
		Version: "v3",
		Group:   "management.cattle.io",
		Path:    "/v3",
	}

	AuthSchemas = factory.Schemas(&Version).
			Init(authnTypes).
			Init(tokens).
			Init(userTypes)

	Schemas = factory.Schemas(&Version).
		Init(nativeNodeTypes).
		Init(nodeTypes).
		Init(authzTypes).
		Init(clusterTypes).
		Init(catalogTypes).
		Init(authnTypes).
		Init(tokens).
		Init(schemaTypes).
		Init(userTypes).
		Init(projectNetworkPolicyTypes).
		Init(logTypes).
		Init(globalTypes).
		Init(rkeTypes).
		Init(alertTypes).
		Init(composeType).
		Init(projectCatalogTypes).
		Init(clusterCatalogTypes).
		Init(multiClusterAppTypes).
		Init(globalDNSTypes).
		Init(kontainerTypes).
		Init(etcdBackupTypes).
		Init(clusterScanTypes).
		Init(monitorTypes).
		Init(credTypes).
		Init(mgmtSecretTypes).
		Init(clusterTemplateTypes).
		Init(driverMetadataTypes).
		Init(driverMetadataCisTypes).
		Init(encryptionTypes).
		Init(fleetTypes).
		Init(notificationTypes)

	TokenSchemas = factory.Schemas(&Version).
			Init(tokens)
)

func fleetTypes(schemas *types.Schemas) *types.Schemas {
	return schemas.MustImport(&Version, v3.FleetWorkspace{})
}

func rkeTypes(schemas *types.Schemas) *types.Schemas {
	return schemas.AddMapperForType(&Version, rketypes.BaseService{}, m.Drop{Field: "image"}).
		AddMapperForType(&Version, v1.Taint{},
			m.Enum{Field: "effect", Options: []string{
				string(v1.TaintEffectNoSchedule),
				string(v1.TaintEffectPreferNoSchedule),
				string(v1.TaintEffectNoExecute),
			}},
			m.Required{Fields: []string{
				"effect",
				"value",
				"key",
			}},
			m.ReadOnly{Field: "timeAdded"},
		).
		MustImport(&Version, rketypes.ExtraEnv{}).
		MustImport(&Version, rketypes.ExtraVolume{}).
		MustImport(&Version, rketypes.ExtraVolumeMount{}).
		MustImport(&Version, rketypes.LinearAutoscalerParams{}).
		MustImport(&Version, rketypes.DeploymentStrategy{}).
		MustImport(&Version, rketypes.DaemonSetUpdateStrategy{})
}

func schemaTypes(schemas *types.Schemas) *types.Schemas {
	return schemas.
		MustImport(&Version, v3.DynamicSchema{})
}

func credTypes(schemas *types.Schemas) *types.Schemas {
	return schemas.
		AddMapperForType(&Version, v3.CloudCredential{},
			&m.DisplayName{},
			&mapper.CredentialMapper{},
			&m.AnnotationField{Field: "name"},
			&m.AnnotationField{Field: "description"},
			&m.Drop{Field: "namespaceId"}).
		MustImport(&Version, v3.CloudCredential{})
}

func mgmtSecretTypes(schemas *types.Schemas) *types.Schemas {
	return schemas.MustImportAndCustomize(&Version, v1.Secret{}, func(schema *types.Schema) {
		schema.ID = "managementSecret"
		schema.PluralName = "managementSecrets"
		schema.CodeName = "ManagementSecret"
		schema.CodeNamePlural = "ManagementSecrets"
		schema.MustCustomizeField("name", func(field types.Field) types.Field {
			field.Type = "hostname"
			field.Nullable = false
			field.Required = true
			return field
		})
	})
}

func driverMetadataTypes(schemas *types.Schemas) *types.Schemas {
	return schemas.
		AddMapperForType(&Version, v3.RkeK8sSystemImage{}, m.Drop{Field: "namespaceId"}).
		AddMapperForType(&Version, v3.RkeK8sServiceOption{}, m.Drop{Field: "namespaceId"}).
		AddMapperForType(&Version, v3.RkeAddon{}, m.Drop{Field: "namespaceId"}).
		MustImport(&Version, v3.RkeK8sSystemImage{}).
		MustImport(&Version, v3.RkeK8sServiceOption{}).
		MustImport(&Version, v3.RkeAddon{})
}

func driverMetadataCisTypes(schemas *types.Schemas) *types.Schemas {
	return schemas.
		AddMapperForType(&Version, v3.CisConfig{}, m.Drop{Field: "namespaceId"}).
		AddMapperForType(&Version, v3.CisBenchmarkVersion{}, m.Drop{Field: "namespaceId"}).
		MustImport(&Version, v3.CisConfig{}).
		MustImport(&Version, v3.CisBenchmarkVersion{})
}

func catalogTypes(schemas *types.Schemas) *types.Schemas {
	return schemas.
		AddMapperForType(&Version, v3.Catalog{},
			&m.Move{From: "catalogKind", To: "kind"},
			&m.Embed{Field: "status"},
			&m.Drop{Field: "helmVersionCommits"},
		).
		MustImport(&Version, v3.CatalogRefresh{}).
		MustImportAndCustomize(&Version, v3.Catalog{}, func(schema *types.Schema) {
			schema.ResourceActions = map[string]types.Action{
				"refresh": {Output: "catalogRefresh"},
			}
			schema.CollectionActions = map[string]types.Action{
				"refresh": {Output: "catalogRefresh"},
			}
		}).
		AddMapperForType(&Version, v3.Template{},
			m.DisplayName{},
		).
		MustImport(&Version, v3.Template{}, struct {
			VersionLinks map[string]string
		}{}).
		AddMapperForType(&Version, v3.CatalogTemplate{},
			m.DisplayName{},
			m.Drop{Field: "namespaceId"},
		).
		MustImport(&Version, v3.CatalogTemplate{}, struct {
			VersionLinks map[string]string
		}{}).
		AddMapperForType(&Version, v3.CatalogTemplateVersion{},
			m.Drop{Field: "namespaceId"},
		).
		MustImport(&Version, v3.CatalogTemplateVersion{}).
		MustImport(&Version, v3.TemplateVersion{}).
		MustImport(&Version, v3.TemplateContent{})
}

func nativeNodeTypes(schemas *types.Schemas) *types.Schemas {
	return schemas.
		TypeName("internalNodeStatus", v1.NodeStatus{}).
		TypeName("internalNodeSpec", v1.NodeSpec{}).
		AddMapperForType(&Version, v1.NodeStatus{},
			&mapper.NodeAddressMapper{},
			&mapper.OSInfo{},
			&m.Drop{Field: "addresses"},
			&m.Drop{Field: "daemonEndpoints"},
			&m.Drop{Field: "images"},
			&m.Drop{Field: "nodeInfo"},
			&m.Move{From: "conditions", To: "nodeConditions"},
			&m.Drop{Field: "phase"},
			&m.SliceToMap{Field: "volumesAttached", Key: "devicePath"},
		).
		AddMapperForType(&Version, v1.NodeSpec{},
			&m.Drop{Field: "externalID"},
			&m.Drop{Field: "configSource"},
			&m.Move{From: "providerID", To: "providerId"},
			&m.Move{From: "podCIDR", To: "podCidr"},
			&m.Move{From: "podCIDRs", To: "podCidrs"},
			m.Access{Fields: map[string]string{
				"podCidr":       "r",
				"podCidrs":      "r",
				"providerId":    "r",
				"taints":        "ru",
				"unschedulable": "ru",
			}}).
		AddMapperForType(&Version, v1.Node{},
			&mapper.NodeAddressAnnotationMapper{}).
		MustImportAndCustomize(&Version, v1.NodeSpec{}, func(schema *types.Schema) {
			schema.CodeName = "InternalNodeSpec"
			schema.CodeNamePlural = "InternalNodeSpecs"
		}).
		MustImportAndCustomize(&Version, v1.NodeStatus{}, func(schema *types.Schema) {
			schema.CodeName = "InternalNodeStatus"
			schema.CodeNamePlural = "InternalNodeStatuses"
		}, struct {
			IPAddress         string
			ExternalIPAddress string `json:"externalIpAddress,omitempty"`
			Hostname          string
			Info              NodeInfo
		}{})
}

func clusterTypes(schemas *types.Schemas) *types.Schemas {
	return schemas.
		AddMapperForType(&Version, v3.Cluster{},
			&m.Embed{Field: "status"},
			mapper.NewDropFromSchema("genericEngineConfig"),
			mapper.NewDropFromSchema("googleKubernetesEngineConfig"),
			mapper.NewDropFromSchema("azureKubernetesServiceConfig"),
			mapper.NewDropFromSchema("amazonElasticContainerServiceConfig"),
			m.DisplayName{},
		).
		AddMapperForType(&Version, v3.ClusterStatus{},
			m.Drop{Field: "serviceAccountToken"},
		).
		AddMapperForType(&Version, v3.ClusterRegistrationToken{},
			&m.Embed{Field: "status"},
		).
		AddMapperForType(&Version, rketypes.RancherKubernetesEngineConfig{},
			m.Drop{Field: "systemImages"},
		).
		MustImport(&Version, v3.Cluster{}).
		MustImport(&Version, v3.ClusterRegistrationToken{}).
		MustImport(&Version, v3.GenerateKubeConfigOutput{}).
		MustImport(&Version, v3.ImportClusterYamlInput{}).
		MustImport(&Version, v3.RotateCertificateInput{}).
		MustImport(&Version, v3.RotateCertificateOutput{}).
		MustImport(&Version, v3.RotateEncryptionKeyOutput{}).
		MustImport(&Version, v3.ImportYamlOutput{}).
		MustImport(&Version, v3.ExportOutput{}).
		MustImport(&Version, v3.MonitoringInput{}).
		MustImport(&Version, v3.MonitoringOutput{}).
		MustImport(&Version, v3.RestoreFromEtcdBackupInput{}).
		MustImport(&Version, v3.SaveAsTemplateInput{}).
		MustImport(&Version, v3.SaveAsTemplateOutput{}).
		AddMapperForType(&Version, v1.EnvVar{},
			&m.Move{
				From: "envVar",
				To:   "agentEnvVar",
			}).
		MustImportAndCustomize(&Version, rketypes.ETCDService{}, func(schema *types.Schema) {
			schema.MustCustomizeField("extraArgs", func(field types.Field) types.Field {
				field.Default = map[string]interface{}{
					"election-timeout":   "5000",
					"heartbeat-interval": "500"}
				return field
			})
		}).
		MustImportAndCustomize(&Version, gkev1.GKEClusterConfigSpec{}, func(schema *types.Schema) {
			schema.MustCustomizeField("labels", func(field types.Field) types.Field {
				field.Pointer = true
				return field
			})
			schema.MustCustomizeField("locations", func(field types.Field) types.Field {
				field.Pointer = true
				return field
			})
		}).
		MustImportAndCustomize(&Version, eksv1.EKSClusterConfigSpec{}, func(schema *types.Schema) {
			schema.MustCustomizeField("publicAccessSources", func(field types.Field) types.Field {
				field.Pointer = true
				return field
			})
			schema.MustCustomizeField("loggingTypes", func(field types.Field) types.Field {
				field.Pointer = true
				return field
			})
			schema.MustCustomizeField("subnets", func(field types.Field) types.Field {
				field.Pointer = true
				return field
			})
			schema.MustCustomizeField("securityGroups", func(field types.Field) types.Field {
				field.Pointer = true
				return field
			})
			schema.MustCustomizeField("tags", func(field types.Field) types.Field {
				field.Pointer = true
				return field
			})
		}).
		MustImportAndCustomize(&Version, eksv1.NodeGroup{}, func(schema *types.Schema) {
			schema.MustCustomizeField("labels", func(field types.Field) types.Field {
				field.Pointer = true
				return field
			})
			schema.MustCustomizeField("resourceTags", func(field types.Field) types.Field {
				field.Pointer = true
				return field
			})
			schema.MustCustomizeField("subnets", func(field types.Field) types.Field {
				field.Pointer = true
				return field
			})
			schema.MustCustomizeField("spotInstanceTypes", func(field types.Field) types.Field {
				field.Pointer = true
				return field
			})
			schema.MustCustomizeField("tags", func(field types.Field) types.Field {
				field.Pointer = true
				return field
			})
		}).
		MustImportAndCustomize(&Version, v3.Cluster{}, func(schema *types.Schema) {
			schema.MustCustomizeField("name", func(field types.Field) types.Field {
				field.Type = "dnsLabel"
				field.Nullable = true
				field.Required = false
				return field
			})
			schema.ResourceActions[v3.ClusterActionGenerateKubeconfig] = types.Action{
				Output: "generateKubeConfigOutput",
			}
			schema.ResourceActions[v3.ClusterActionImportYaml] = types.Action{
				Input:  "importClusterYamlInput",
				Output: "importYamlOutput",
			}
			schema.ResourceActions[v3.ClusterActionExportYaml] = types.Action{
				Output: "exportOutput",
			}
			schema.ResourceActions[v3.ClusterActionEnableMonitoring] = types.Action{
				Input: "monitoringInput",
			}
			schema.ResourceActions[v3.ClusterActionDisableMonitoring] = types.Action{}
			schema.ResourceActions[v3.ClusterActionViewMonitoring] = types.Action{
				Output: "monitoringOutput",
			}
			schema.ResourceActions[v3.ClusterActionEditMonitoring] = types.Action{
				Input: "monitoringInput",
			}
			schema.ResourceActions[v3.ClusterActionBackupEtcd] = types.Action{}
			schema.ResourceActions[v3.ClusterActionRestoreFromEtcdBackup] = types.Action{
				Input: "restoreFromEtcdBackupInput",
			}
			schema.ResourceActions[v3.ClusterActionRotateCertificates] = types.Action{
				Input:  "rotateCertificateInput",
				Output: "rotateCertificateOutput",
			}
			schema.ResourceActions[v3.ClusterActionRotateEncryptionKey] = types.Action{
				Output: "rotateEncryptionKeyOutput",
			}
			schema.ResourceActions[v3.ClusterActionSaveAsTemplate] = types.Action{
				Input:  "saveAsTemplateInput",
				Output: "saveAsTemplateOutput",
			}
		})
}

func authzTypes(schemas *types.Schemas) *types.Schemas {
	return schemas.
		MustImport(&Version, v3.ProjectStatus{}).
		AddMapperForType(&Version, v3.Project{},
			m.DisplayName{},
			&m.Embed{Field: "status"},
		).
		AddMapperForType(&Version, v3.GlobalRole{}, m.DisplayName{}).
		AddMapperForType(&Version, v3.RoleTemplate{}, m.DisplayName{}).
		AddMapperForType(&Version,
			v3.PodSecurityPolicyTemplateProjectBinding{},
			&mapper.NamespaceIDMapper{}).
		AddMapperForType(&Version, v3.ProjectRoleTemplateBinding{},
			&mapper.NamespaceIDMapper{},
		).
		MustImport(&Version, v3.SetPodSecurityPolicyTemplateInput{}).
		MustImport(&Version, v3.ImportYamlOutput{}).
		MustImport(&Version, v3.MonitoringInput{}).
		MustImport(&Version, v3.MonitoringOutput{}).
		MustImportAndCustomize(&Version, v3.Project{}, func(schema *types.Schema) {
			schema.ResourceActions = map[string]types.Action{
				"setpodsecuritypolicytemplate": {
					Input:  "setPodSecurityPolicyTemplateInput",
					Output: "project",
				},
				"exportYaml": {},
				"enableMonitoring": {
					Input: "monitoringInput",
				},
				"disableMonitoring": {},
				"viewMonitoring": {
					Output: "monitoringOutput",
				},
				"editMonitoring": {
					Input: "monitoringInput",
				},
			}
		}).
		MustImport(&Version, v3.GlobalRole{}).
		MustImport(&Version, v3.GlobalRoleBinding{}).
		MustImport(&Version, v3.RoleTemplate{}).
		MustImport(&Version, v3.PodSecurityPolicyTemplate{}).
		MustImportAndCustomize(&Version, v3.PodSecurityPolicyTemplateProjectBinding{}, func(schema *types.Schema) {
			schema.CollectionMethods = []string{http.MethodGet, http.MethodPost}
			schema.ResourceMethods = []string{}
		}).
		MustImport(&Version, v3.ClusterRoleTemplateBinding{}).
		MustImport(&Version, v3.ProjectRoleTemplateBinding{}).
		MustImport(&Version, v3.GlobalRoleBinding{})
}

func nodeTypes(schemas *types.Schemas) *types.Schemas {
	return schemas.
		AddMapperForType(&Version, v3.NodeSpec{}, &m.Embed{Field: "internalNodeSpec"}).
		AddMapperForType(&Version, v3.NodeStatus{},
			&m.Drop{Field: "nodeTemplateSpec"},
			&m.Embed{Field: "internalNodeStatus"},
			&m.Drop{Field: "config"},
			&m.SliceMerge{From: []string{"conditions", "nodeConditions"}, To: "conditions"}).
		AddMapperForType(&Version, v3.Node{},
			&m.Embed{Field: "status"},
			&m.Move{From: "rkeNode/user", To: "sshUser"},
			&m.ReadOnly{Field: "sshUser"},
			&m.Drop{Field: "rkeNode"},
			&m.Drop{Field: "labels"},
			&m.Drop{Field: "annotations"},
			&m.Move{From: "nodeLabels", To: "labels"},
			&m.Move{From: "nodeAnnotations", To: "annotations"},
			&m.Drop{Field: "desiredNodeTaints"},
			&m.Drop{Field: "metadataUpdate"},
			&m.Drop{Field: "updateTaintsFromAPI"},
			&m.Drop{Field: "desiredNodeUnschedulable"},
			&m.Drop{Field: "nodeDrainInput"},
			&m.AnnotationField{Field: "publicEndpoints", List: true},
			m.Copy{From: "namespaceId", To: "clusterName"},
			m.DisplayName{}).
		AddMapperForType(&Version, v3.NodeDriver{}, m.DisplayName{}).
		AddMapperForType(&Version, v3.NodeTemplate{}, m.DisplayName{}).
		MustImport(&Version, v3.PublicEndpoint{}).
		MustImportAndCustomize(&Version, v3.NodePool{}, func(schema *types.Schema) {
			schema.ResourceFields["driver"] = types.Field{
				Type:     "string",
				CodeName: "Driver",
				Create:   false,
				Update:   false,
			}
		}).
		MustImport(&Version, v3.NodeDrainInput{}).
		MustImportAndCustomize(&Version, v3.Node{}, func(schema *types.Schema) {
			labelField := schema.ResourceFields["labels"]
			labelField.Create = true
			labelField.Update = true
			schema.ResourceFields["labels"] = labelField
			annotationField := schema.ResourceFields["annotations"]
			annotationField.Create = true
			annotationField.Update = true
			schema.ResourceFields["annotations"] = annotationField
			unschedulable := schema.ResourceFields["unschedulable"]
			unschedulable.Create = false
			unschedulable.Update = false
			schema.ResourceFields["unschedulable"] = unschedulable
			clusterField := schema.ResourceFields["clusterId"]
			clusterField.Type = "reference[cluster]"
			schema.ResourceFields["clusterId"] = clusterField
			schema.ResourceActions["cordon"] = types.Action{}
			schema.ResourceActions["uncordon"] = types.Action{}
			schema.ResourceActions["stopDrain"] = types.Action{}
			schema.ResourceActions["scaledown"] = types.Action{}
			schema.ResourceActions["drain"] = types.Action{
				Input: "nodeDrainInput",
			}
		}, struct {
			PublicEndpoints string `json:"publicEndpoints" norman:"type=array[publicEndpoint],nocreate,noupdate"`
		}{}).
		MustImportAndCustomize(&Version, v3.NodeDriver{}, func(schema *types.Schema) {
			schema.ResourceActions["activate"] = types.Action{
				Output: "nodeDriver",
			}
			schema.ResourceActions["deactivate"] = types.Action{
				Output: "nodeDriver",
			}
		}).
		MustImportAndCustomize(&Version, v3.NodeTemplate{}, func(schema *types.Schema) {
			delete(schema.ResourceFields, "namespaceId")
		})
}

func tokens(schemas *types.Schemas) *types.Schemas {
	return schemas.
		MustImportAndCustomize(&Version, v3.Token{}, func(schema *types.Schema) {
			schema.CollectionActions = map[string]types.Action{
				"logout": {},
			}
		})
}

func authnTypes(schemas *types.Schemas) *types.Schemas {
	return schemas.
		AddMapperForType(&Version, v3.User{}, m.DisplayName{},
			&m.Embed{Field: "status"}).
		AddMapperForType(&Version, v3.Group{}, m.DisplayName{}).
		MustImport(&Version, v3.Group{}).
		MustImport(&Version, v3.GroupMember{}).
		MustImport(&Version, v3.SamlToken{}).
		AddMapperForType(&Version, v3.Principal{}, m.DisplayName{}).
		MustImportAndCustomize(&Version, v3.Principal{}, func(schema *types.Schema) {
			schema.CollectionMethods = []string{http.MethodGet}
			schema.ResourceMethods = []string{http.MethodGet}
			schema.CollectionActions = map[string]types.Action{
				"search": {
					Input:  "searchPrincipalsInput",
					Output: "collection",
				},
			}
		}).
		MustImport(&Version, v3.SearchPrincipalsInput{}).
		MustImport(&Version, v3.ChangePasswordInput{}).
		MustImport(&Version, v3.SetPasswordInput{}).
		MustImportAndCustomize(&Version, v3.User{}, func(schema *types.Schema) {
			schema.ResourceActions = map[string]types.Action{
				"setpassword": {
					Input:  "setPasswordInput",
					Output: "user",
				},
				"refreshauthprovideraccess": {},
			}
			schema.CollectionActions = map[string]types.Action{
				"changepassword": {
					Input: "changePasswordInput",
				},
				"refreshauthprovideraccess": {},
			}
		}).
		MustImportAndCustomize(&Version, v3.AuthConfig{}, func(schema *types.Schema) {
			schema.CollectionMethods = []string{http.MethodGet}
		}).
		// Local Config
		MustImportAndCustomize(&Version, v3.LocalConfig{}, func(schema *types.Schema) {
			schema.BaseType = "authConfig"
			schema.CollectionMethods = []string{}
			schema.ResourceMethods = []string{http.MethodGet}
		}).
		//Github Config
		MustImportAndCustomize(&Version, v3.GithubConfig{}, func(schema *types.Schema) {
			schema.BaseType = "authConfig"
			schema.ResourceActions = map[string]types.Action{
				"disable": {},
				"configureTest": {
					Input:  "githubConfig",
					Output: "githubConfigTestOutput",
				},
				"testAndApply": {
					Input: "githubConfigApplyInput",
				},
			}
			schema.CollectionMethods = []string{}
			schema.ResourceMethods = []string{http.MethodGet, http.MethodPut}
		}).
		MustImport(&Version, v3.GithubConfigTestOutput{}).
		MustImport(&Version, v3.GithubConfigApplyInput{}).
		//AzureAD Config
		MustImportAndCustomize(&Version, v3.AzureADConfig{}, func(schema *types.Schema) {
			schema.BaseType = "authConfig"
			schema.ResourceActions = map[string]types.Action{
				"disable": {},
				"configureTest": {
					Input:  "azureADConfig",
					Output: "azureADConfigTestOutput",
				},
				"testAndApply": {
					Input: "azureADConfigApplyInput",
				},
				"upgrade": {},
			}
			schema.CollectionMethods = []string{}
			schema.ResourceMethods = []string{http.MethodGet, http.MethodPut}
		}).
		MustImport(&Version, v3.AzureADConfigTestOutput{}).
		MustImport(&Version, v3.AzureADConfigApplyInput{}).
		// Active Directory Config
		MustImportAndCustomize(&Version, v3.ActiveDirectoryConfig{}, func(schema *types.Schema) {
			schema.BaseType = "authConfig"
			schema.ResourceActions = map[string]types.Action{
				"disable": {},
				"testAndApply": {
					Input: "activeDirectoryTestAndApplyInput",
				},
			}
			schema.CollectionMethods = []string{}
			schema.ResourceMethods = []string{http.MethodGet, http.MethodPut}
		}).
		MustImport(&Version, v3.ActiveDirectoryTestAndApplyInput{}).
		// OpenLdap Config
		MustImportAndCustomize(&Version, v3.OpenLdapConfig{}, func(schema *types.Schema) {
			schema.BaseType = "authConfig"
			schema.ResourceActions = map[string]types.Action{
				"disable": {},
				"testAndApply": {
					Input: "openLdapTestAndApplyInput",
				},
			}
			schema.CollectionMethods = []string{}
			schema.ResourceMethods = []string{http.MethodGet, http.MethodPut}
		}).
		MustImport(&Version, v3.OpenLdapTestAndApplyInput{}).
		// FreeIpa Config
		AddMapperForType(&Version, v3.FreeIpaConfig{}, m.Drop{Field: "nestedGroupMembershipEnabled"}).
		MustImportAndCustomize(&Version, v3.FreeIpaConfig{}, func(schema *types.Schema) {
			schema.BaseType = "authConfig"
			schema.ResourceActions = map[string]types.Action{
				"disable": {},
				"testAndApply": {
					Input: "freeIpaTestAndApplyInput",
				},
			}
			schema.CollectionMethods = []string{}
			schema.ResourceMethods = []string{http.MethodGet, http.MethodPut}
			schema.MustCustomizeField("groupObjectClass", func(f types.Field) types.Field {
				f.Default = "groupofnames"
				return f
			})
			schema.MustCustomizeField("userNameAttribute", func(f types.Field) types.Field {
				f.Default = "givenName"
				return f
			})
			schema.MustCustomizeField("userObjectClass", func(f types.Field) types.Field {
				f.Default = "inetorgperson"
				return f
			})
			schema.MustCustomizeField("groupDNAttribute", func(f types.Field) types.Field {
				f.Default = "entrydn"
				return f
			})
			schema.MustCustomizeField("groupMemberUserAttribute", func(f types.Field) types.Field {
				f.Default = "entrydn"
				return f
			})
		}).
		MustImport(&Version, v3.FreeIpaTestAndApplyInput{}).
		// Saml Config
		// Ping-Saml Config
		// KeyCloak-Saml Configs
		MustImportAndCustomize(&Version, v3.PingConfig{}, configSchema).
		MustImportAndCustomize(&Version, v3.ADFSConfig{}, configSchema).
		MustImportAndCustomize(&Version, v3.KeyCloakConfig{}, configSchema).
		MustImportAndCustomize(&Version, v3.OKTAConfig{}, configSchema).
		MustImportAndCustomize(&Version, v3.ShibbolethConfig{}, configSchema).
		MustImport(&Version, v3.SamlConfigTestInput{}).
		MustImport(&Version, v3.SamlConfigTestOutput{}).
		//GoogleOAuth Config
		MustImportAndCustomize(&Version, v3.GoogleOauthConfig{}, func(schema *types.Schema) {
			schema.BaseType = "authConfig"
			schema.ResourceActions = map[string]types.Action{
				"disable": {},
				"configureTest": {
					Input:  "googleOauthConfig",
					Output: "googleOauthConfigTestOutput",
				},
				"testAndApply": {
					Input: "googleOauthConfigApplyInput",
				},
			}
			schema.CollectionMethods = []string{}
			schema.ResourceMethods = []string{http.MethodGet, http.MethodPut}
		}).
		MustImport(&Version, v3.GoogleOauthConfigApplyInput{}).
		MustImport(&Version, v3.GoogleOauthConfigTestOutput{}).
		//OIDC Config
		MustImportAndCustomize(&Version, v3.OIDCConfig{}, func(schema *types.Schema) {
			schema.BaseType = "authConfig"
			schema.ResourceActions = map[string]types.Action{
				"disable": {},
				"configureTest": {
					Input:  "oidcConfig",
					Output: "oidcTestOutput",
				},
				"testAndApply": {
					Input: "oidcApplyInput",
				},
			}
			schema.CollectionMethods = []string{}
			schema.ResourceMethods = []string{http.MethodGet, http.MethodPut}
		}).
		MustImport(&Version, v3.OIDCApplyInput{}).
		MustImport(&Version, v3.OIDCTestOutput{}).
		//KeyCloakOIDC Config
		MustImportAndCustomize(&Version, v3.KeyCloakOIDCConfig{}, func(schema *types.Schema) {
			schema.BaseType = "authConfig"
			schema.ResourceActions = map[string]types.Action{
				"disable": {},
				"configureTest": {
					Input:  "keyCloakOidcConfig",
					Output: "keyCloakOidcTestOutput",
				},
				"testAndApply": {
					Input: "keyCloakOidcApplyInput",
				},
			}
			schema.CollectionMethods = []string{}
			schema.ResourceMethods = []string{http.MethodGet, http.MethodPut}
		})
}

func configSchema(schema *types.Schema) {
	schema.BaseType = "authConfig"
	schema.ResourceActions = map[string]types.Action{
		"disable": {},
		"testAndEnable": {
			Input:  "samlConfigTestInput",
			Output: "samlConfigTestOutput",
		},
	}
	schema.CollectionMethods = []string{}
	schema.ResourceMethods = []string{http.MethodGet, http.MethodPut}
}

func userTypes(schema *types.Schemas) *types.Schemas {
	return schema.
		MustImportAndCustomize(&Version, v3.Preference{}, func(schema *types.Schema) {
			schema.MustCustomizeField("name", func(f types.Field) types.Field {
				f.Required = true
				return f
			})
			schema.MustCustomizeField("namespaceId", func(f types.Field) types.Field {
				f.Required = false
				return f
			})
		}).
		MustImportAndCustomize(&Version, v3.UserAttribute{}, func(schema *types.Schema) {
			schema.CollectionMethods = []string{}
			schema.ResourceMethods = []string{}
		})
}

func projectNetworkPolicyTypes(schema *types.Schemas) *types.Schemas {
	return schema.
		MustImportAndCustomize(&Version, v3.ProjectNetworkPolicy{}, func(schema *types.Schema) {
			schema.CollectionMethods = []string{http.MethodGet}
			schema.ResourceMethods = []string{http.MethodGet}
		})
}

func logTypes(schema *types.Schemas) *types.Schemas {
	return schema.
		AddMapperForType(&Version, v3.ClusterLogging{},
			&m.Embed{Field: "status"},
			m.DisplayName{}).
		AddMapperForType(&Version, v3.ProjectLogging{},
			m.DisplayName{}).
		MustImport(&Version, v3.ClusterTestInput{}).
		MustImport(&Version, v3.ProjectTestInput{}).
		MustImportAndCustomize(&Version, v3.ClusterLogging{}, func(schema *types.Schema) {
			schema.CollectionActions = map[string]types.Action{
				"test": {
					Input: "clusterTestInput",
				},
				"dryRun": {
					Input: "clusterTestInput",
				},
			}
		}).
		MustImportAndCustomize(&Version, v3.ProjectLogging{}, func(schema *types.Schema) {
			schema.CollectionActions = map[string]types.Action{
				"test": {
					Input: "projectTestInput",
				},
				"dryRun": {
					Input: "projectTestInput",
				},
			}
		})
}

func globalTypes(schema *types.Schemas) *types.Schemas {
	return schema.
		MustImportAndCustomize(&Version, v3.Setting{}, func(schema *types.Schema) {
			schema.MustCustomizeField("name", func(f types.Field) types.Field {
				f.Required = true
				return f
			})
		}).
		MustImportAndCustomize(&Version, v3.Feature{}, func(schema *types.Schema) {
			schema.MustCustomizeField("name", func(f types.Field) types.Field {
				f.Required = true
				return f
			})
		})
}

func alertTypes(schema *types.Schemas) *types.Schemas {
	return schema.
		AddMapperForType(&Version, v3.Notifier{},
			&m.Embed{Field: "status"},
			m.DisplayName{}).
		MustImport(&Version, v3.ClusterAlert{}).
		MustImport(&Version, v3.ProjectAlert{}).
		MustImport(&Version, v3.Notification{}).
		MustImportAndCustomize(&Version, v3.Notifier{}, func(schema *types.Schema) {
			schema.CollectionActions = map[string]types.Action{
				"send": {
					Input: "notification",
				},
			}
			schema.ResourceActions = map[string]types.Action{
				"send": {
					Input: "notification",
				},
			}
		}).
		MustImport(&Version, v3.AlertStatus{}).
		AddMapperForType(&Version, v3.ClusterAlertGroup{},
			&m.Embed{Field: "status"},
			m.DisplayName{}).
		AddMapperForType(&Version, v3.ProjectAlertGroup{},
			&m.Embed{Field: "status"},
			m.DisplayName{}).
		AddMapperForType(&Version, v3.ClusterAlertRule{},
			&m.Embed{Field: "status"},
			m.DisplayName{}).
		AddMapperForType(&Version, v3.ProjectAlertRule{},
			&m.Embed{Field: "status"},
			m.DisplayName{}).
		MustImport(&Version, v3.ClusterAlertGroup{}).
		MustImport(&Version, v3.ProjectAlertGroup{}).
		MustImportAndCustomize(&Version, v3.ClusterAlertRule{}, func(schema *types.Schema) {
			schema.ResourceActions = map[string]types.Action{
				"activate":   {},
				"deactivate": {},
				"mute":       {},
				"unmute":     {},
			}
		}).
		MustImportAndCustomize(&Version, v3.ProjectAlertRule{}, func(schema *types.Schema) {
			schema.ResourceActions = map[string]types.Action{
				"activate":   {},
				"deactivate": {},
				"mute":       {},
				"unmute":     {},
			}
		})

}

func composeType(schemas *types.Schemas) *types.Schemas {
	return schemas.MustImport(&Version, v3.ComposeConfig{})
}

func projectCatalogTypes(schemas *types.Schemas) *types.Schemas {
	return schemas.
		AddMapperForType(&Version, v3.ProjectCatalog{},
			&m.Move{From: "catalogKind", To: "kind"},
			&m.Embed{Field: "status"},
			&m.Drop{Field: "helmVersionCommits"},
			&mapper.NamespaceIDMapper{}).
		MustImportAndCustomize(&Version, v3.ProjectCatalog{}, func(schema *types.Schema) {
			schema.ResourceActions = map[string]types.Action{
				"refresh": {Output: "catalogRefresh"},
			}
			schema.CollectionActions = map[string]types.Action{
				"refresh": {Output: "catalogRefresh"},
			}
		})
}

func clusterCatalogTypes(schemas *types.Schemas) *types.Schemas {
	return schemas.
		AddMapperForType(&Version, v3.ClusterCatalog{},
			&m.Move{From: "catalogKind", To: "kind"},
			&m.Embed{Field: "status"},
			&m.Drop{Field: "helmVersionCommits"},
			&mapper.NamespaceIDMapper{}).
		MustImportAndCustomize(&Version, v3.ClusterCatalog{}, func(schema *types.Schema) {
			schema.ResourceActions = map[string]types.Action{
				"refresh": {Output: "catalogRefresh"},
			}
			schema.CollectionActions = map[string]types.Action{
				"refresh": {Output: "catalogRefresh"},
			}
		})
}

func multiClusterAppTypes(schemas *types.Schemas) *types.Schemas {
	return schemas.
		AddMapperForType(&Version, v3.MultiClusterApp{}, m.Drop{Field: "namespaceId"}).
		AddMapperForType(&Version, v3.MultiClusterAppRevision{}, m.Drop{Field: "namespaceId"}).
		AddMapperForType(&Version, v3.Member{}, m.Drop{Field: "userName"}, m.Drop{Field: "displayName"}).
		MustImport(&Version, v3.MultiClusterApp{}).
		MustImport(&Version, v3.Target{}).
		MustImport(&Version, v3.UpgradeStrategy{}).
		MustImport(&Version, v3.MultiClusterAppRollbackInput{}).
		MustImport(&Version, v3.MultiClusterAppRevision{}).
		MustImport(&Version, v3.UpdateMultiClusterAppTargetsInput{}).
		MustImportAndCustomize(&Version, v3.MultiClusterApp{}, func(schema *types.Schema) {
			schema.ResourceActions = map[string]types.Action{
				"rollback": {
					Input: "multiClusterAppRollbackInput",
				},
				"addProjects": {
					Input: "updateMultiClusterAppTargetsInput",
				},
				"removeProjects": {
					Input: "updateMultiClusterAppTargetsInput",
				},
			}
		})
}

func globalDNSTypes(schemas *types.Schemas) *types.Schemas {
	return schemas.
		TypeName("globalDns", v3.GlobalDns{}).
		TypeName("globalDnsProvider", v3.GlobalDnsProvider{}).
		TypeName("globalDnsSpec", v3.GlobalDNSSpec{}).
		TypeName("globalDnsStatus", v3.GlobalDNSStatus{}).
		TypeName("globalDnsProviderSpec", v3.GlobalDNSProviderSpec{}).
		MustImport(&Version, v3.UpdateGlobalDNSTargetsInput{}).
		AddMapperForType(&Version, v3.GlobalDns{}, m.Drop{Field: "namespaceId"}).
		AddMapperForType(&Version, v3.GlobalDnsProvider{}, m.Drop{Field: "namespaceId"}).
		MustImportAndCustomize(&Version, v3.GlobalDns{}, func(schema *types.Schema) {
			schema.ResourceActions = map[string]types.Action{
				"addProjects": {
					Input: "updateGlobalDNSTargetsInput",
				},
				"removeProjects": {
					Input: "updateGlobalDNSTargetsInput",
				},
			}
		}).
		MustImportAndCustomize(&Version, v3.GlobalDnsProvider{}, func(schema *types.Schema) {
		})
}

func kontainerTypes(schemas *types.Schemas) *types.Schemas {
	return schemas.
		AddMapperForType(&Version, v3.KontainerDriver{},
			&m.Embed{Field: "status"},
			m.DisplayName{},
		).
		MustImportAndCustomize(&Version, v3.KontainerDriver{}, func(schema *types.Schema) {
			schema.ResourceActions = map[string]types.Action{
				"activate":   {},
				"deactivate": {},
			}
			schema.CollectionActions = map[string]types.Action{
				"refresh": {},
			}
		})
}

func monitorTypes(schemas *types.Schemas) *types.Schemas {
	return schemas.
		MustImport(&Version, v3.QueryGraphInput{}).
		MustImport(&Version, v3.QueryClusterGraphOutput{}).
		MustImport(&Version, v3.QueryProjectGraphOutput{}).
		MustImport(&Version, v3.QueryClusterMetricInput{}).
		MustImport(&Version, v3.QueryProjectMetricInput{}).
		MustImport(&Version, v3.QueryMetricOutput{}).
		MustImport(&Version, v3.ClusterMetricNamesInput{}).
		MustImport(&Version, v3.ProjectMetricNamesInput{}).
		MustImport(&Version, v3.MetricNamesOutput{}).
		MustImport(&Version, v3.TimeSeries{}).
		MustImportAndCustomize(&Version, v3.MonitorMetric{}, func(schema *types.Schema) {
			schema.CollectionActions = map[string]types.Action{
				"querycluster": {
					Input:  "queryClusterMetricInput",
					Output: "queryMetricOutput",
				},
				"listclustermetricname": {
					Input:  "clusterMetricNamesInput",
					Output: "metricNamesOutput",
				},
				"queryproject": {
					Input:  "queryProjectMetricInput",
					Output: "queryMetricOutput",
				},
				"listprojectmetricname": {
					Input:  "projectMetricNamesInput",
					Output: "metricNamesOutput",
				},
			}
		}).
		MustImportAndCustomize(&Version, v3.ClusterMonitorGraph{}, func(schema *types.Schema) {
			schema.CollectionActions = map[string]types.Action{
				"query": {
					Input:  "queryGraphInput",
					Output: "queryClusterGraphOutput",
				},
			}
		}).
		MustImportAndCustomize(&Version, v3.ProjectMonitorGraph{}, func(schema *types.Schema) {
			schema.CollectionActions = map[string]types.Action{
				"query": {
					Input:  "queryGraphInput",
					Output: "queryProjectGraphOutput",
				},
			}
		})
}

func etcdBackupTypes(schemas *types.Schemas) *types.Schemas {
	return schemas.MustImport(&Version, v3.EtcdBackup{})
}

func clusterTemplateTypes(schemas *types.Schemas) *types.Schemas {
	return schemas.
		TypeName("clusterTemplate", v3.ClusterTemplate{}).
		TypeName("clusterTemplateRevision", v3.ClusterTemplateRevision{}).
		AddMapperForType(&Version, v3.ClusterTemplate{}, m.Drop{Field: "namespaceId"}, m.DisplayName{}).
		AddMapperForType(&Version, v3.ClusterTemplateRevision{},
			m.Drop{Field: "namespaceId"},
			&m.Embed{Field: "status"},
			m.DisplayName{}).
		MustImport(&Version, v3.ClusterTemplateQuestionsOutput{}).
		MustImport(&Version, v3.ClusterTemplate{}).
		MustImportAndCustomize(&Version, v3.ClusterTemplateRevision{}, func(schema *types.Schema) {
			schema.ResourceActions = map[string]types.Action{
				"disable": {},
				"enable":  {},
			}
			schema.CollectionActions = map[string]types.Action{
				"listquestions": {
					Output: "clusterTemplateQuestionsOutput",
				},
			}
		})

}

func clusterScanTypes(schemas *types.Schemas) *types.Schemas {
	return schemas.MustImportAndCustomize(&Version, v3.ClusterScan{}, func(schema *types.Schema) {
		schema.CollectionMethods = []string{http.MethodGet}
		schema.ResourceMethods = []string{http.MethodGet, http.MethodDelete}
	})
}

func encryptionTypes(schemas *types.Schemas) *types.Schemas {
	return schemas.MustImport(&Version, rketypes.SecretsEncryptionConfig{}).
		MustImport(&Version, apiserverconfig.Key{}, struct {
			Secret string `norman:"type=password"`
		}{}).MustImport(&Version, apiserverconfig.KMSConfiguration{}, struct {
		Timeout string
	}{})
}

func notificationTypes(schemas *types.Schemas) *types.Schemas {
	return schemas.MustImport(&Version, v3.RancherUserNotification{})
}


text:
Wildlife detection
==================

A wildlife detection camera with Raspberry Pi. Either motion sensing based on the video stream (using OpenCV) or a PIR can be used to make wildlife images and videos.

Hardware
--------

Hardware (yes, some of it has newer and better versions) that is used to test this project:

* [character LCD display](https://www.adafruit.com/products/772)
* [wifi dongle](http://www.edimax.com/edimax/merchandise/merchandise_detail/data/edimax/global/wireless_adapters_n150/ew-7811un)
* [Raspberry Pi](https://www.raspberrypi.org/products/model-b/)
* [PIR sensor](https://www.adafruit.com/products/189)
* [NoIR camera](https://www.raspberrypi.org/products/pi-noir-camera/)

Installation
------------

### Precompiled OpenCV (recommended)

Before you can run the script, two things have to be done:

1. Install the dependencies
2. Enable I2C support

The above steps are performed by the `install.sh` script. First clone the repository, then run the script:

1. `git clone https://github.com/opieters/wcamera`
1. `chmod +x install.sh`
2. `sudo ./install.sh`

Finally, you need to reboot your Raspberry Pi to make sure all new settings are in effect.

After installing all packages (assuming there are no errors) and reboot, test the I2C: `sudo i2cdetect -y 1`. If you have connected your display (Adafruit CharLCD + I2C expander), you should see one address in use (replace 1 by 0 if you have the very first Raspberry Pi B model with 256MB RAM).

### Compile OpenCV on the Raspberry Pi (advanced)

Users who want to compile OpenCV themselves, should run the `install2.sh` script with is based on [this tutorial](http://www.pyimagesearch.com/2015/02/23/install-opencv-and-python-on-your-raspberry-pi-2-and-b/) but otherwise performs the same actions. Please mind that OpenCV is installed in a `virtualenv` for convenience.

### I2C failed to Install

Open `raspi-config`, select Advanced Options (9) and enable I2C. Alternatively, use [this guide](https://learn.adafruit.com/adafruits-raspberry-pi-lesson-4-gpio-setup/configuring-i2c).

### Camera

Before attempting to record anything, make sure you activated the camera in `raspi-config` and correctly connected the camera module to the Raspberry Pi board.

### Hotspot (Access Point Mode)

Setup access point mode using [this guide](http://elinux.org/RPI-Wireless-Hotspot), but do not apply the _at boot_ settings. These will be performed by the script.

If you are using the EDIMAX wifi dongle, update Hostapd with the version in [this guide](http://www.daveconroy.com/turn-your-raspberry-pi-into-a-wifi-hotspot-with-edimax-nano-usb-ew-7811un-rtl8188cus-chipset/) (you can skip everything else in this guide). Be sure to chance the driver settings in the `/etc/hostapd/hostapd.conf` file to `driver=rtl871xdrv`. Otherwise this will not work.

Usage
-----

Run the script using `python wcamera.py` and use the provided UI on the character LCD and mobile UI.

FAQ
---

### Why only Python2.7?

Currently, OpenCV 2 is used, which does not officially support Python3. Moving towards OpenCV 3 will resolve this issue, but OpenCV 3 is still very new and thus OpenCV 2 was preferred.

License
-------

© 2015-2016 Olivier Pieters, MIT license.


text:
function range(start,end){
	var array = [];

	for(var i = start; i <= end; i++){
		array.push(i);
	}

	return array;
}

array = range(10,20);
console.log(array);

// Next, write a sum function that takes an array of numbers and
// returns the sum of these numbers.

function sum(array){
	var result = null;

	for(var i = 0; i < array.length; i++){
		result += array[i];
	}

	return result;
}

var result = sum([20,30,50]);
console.log(result);

// Run the following program and check that it displays 55.

console.log(sum(range(1, 10)));


text:
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="cn.jamesli.example.at85notification" >

    <application
        android:allowBackup="true"
        android:icon="@mipmap/ic_launcher"
        android:label="@string/app_name"
        android:theme="@style/AppTheme" >
        <activity
            android:name=".NotificationStatusBarActivity"
            android:label="@string/app_name" >
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
        <activity android:name=".NotificationSubActivity" >
        </activity>
    </application>

</manifest>


text:
@class MapSourceDefinition;

@interface SourceNode : NSObject {

	NSString *title;
	NSMutableArray *childrenNodes;
	NSMutableArray *maps;
	NSString *code; //code for temporary folder for storing tiles
}

@property(nonatomic, retain) NSString *title;
@property(nonatomic, retain) NSString *code;
@property(nonatomic, retain) NSMutableArray *maps;

-(BOOL) isMap;
-(NSInteger) getNumberOfItems;
-(MapSourceDefinition*) getMap: (NSInteger) position;
-(SourceNode*) getChild: (NSInteger) position;
-(void) addNode:(SourceNode*)node;
-(void) addMap:(MapSourceDefinition*)map;
-(void) replaceMap:(MapSourceDefinition*)map atIndex:(NSInteger)index;

@end


text:
Path Traversal
==============

Often we will refer to a file on disk or other resource using a path. A
path traversal attack is when an attacker supplies input that gets used
with our path to access a file on the file system that we did not
intend. The input usually attempts to break out of the application's
working directory and access a file elsewhere on the file system. This
category of attack can be mitigated by restricting the scope of file
system access and reducing attack surface by using a restricted file
permission profile.

### Incorrect

A typical remote vector for path traversal in web applications might
involve serving or storing files on the file system. Consider the
following example:

```python

import os
from flask import Flask, redirect, request, send_file

app = Flask(__name__)

@app.route('/')
def cat_picture():
    image_name = request.args.get('image_name')
    if not image_name:
        return 404
    return send_file(os.path.join(os.getcwd(), image_name))

if __name__ == '__main__':
    app.run(debug=True)
```

As the attacker controls the input that is used directly in constructing
a path they are able to access any file on the system. For example
consider what happens if an attacker makes a request like:

```
curl http://example.com/?image_name=../../../../../../../../etc/passwd
```

Path traversal flaws also can happen when unpacking a compressed archive
of files. An example of where this has happened within OpenStack is
[OSSA-2011-001](http://security.openstack.org/ossa/OSSA-2011-001.html).
In this case a tar file from an untrusted source could be unpacked to
overwrite files on the host operating system.

```python

import tarfile

def untar_image(path, filename):
    tar_file = tarfile.open(filename, 'r|gz')
    tar_file.extract_all(path)
    image_file = tar_file.get_names()[0]
    tar_file.close()
    return os.path.join(path, image_file)
```

### Correct

The following example demonstrates how you can use python code to
restrict access to files within a specific directory. This can be used
as a mechanism to defeat path traversal.

```python
import os
import sys

def is_safe_path(basedir, path, follow_symlinks=True):
  # resolves symbolic links
  if follow_symlinks:
    return os.path.realpath(path).startswith(basedir)

  return os.path.abspath(path).startswith(basedir)

def main(args):
    for arg in args:
        if is_safe_path(os.getcwd(), path):
            print("safe: {}".format(arg))
        else:
            print("unsafe: {}".format(arg))

if __name__ == "__main__":
    main(sys.argv[1:])
```

Another approach to restricting file system access to maintain an
indirect mapping between a unique identifier and a file path that exists
on the operating system. This prevents users supplying malicious input
to access unintended files.

```python
localfiles = {
  "01" : "/var/www/img/001.png",
  "02" : "/var/www/img/002.png",
  "03" : "/var/www/img/003.png",
}

# Will raise an error if an invalid key is used.
def get_file(file_id):
  return open(localfiles[file_id])
```

### Consequences

Not validating file paths allows the attacker to read or write to any
file that the application has access to. This can lead to information
leakage and can be used to pivot to other more serious attacks like
remote code execution.

* [OSSA-2011-001](http://security.openstack.org/ossa/OSSA-2011-001.html)
* [OSSA-2014-041](http://security.openstack.org/ossa/OSSA-2014-041.html)
* [OSSA-2015-002](http://security.openstack.org/ossa/OSSA-2015-002.html)

### References

* [CWE-22: Improper Limitation of a Pathname to a Restricted
Directory](http://cwe.mitre.org/data/definitions/22.html)
* [OWASP: Path
Traversal](https://www.owasp.org/index.php/Path_Traversal)
* [Wikipedia: Directory traversal
attack](http://en.wikipedia.org/wiki/Directory_traversal_attack)


text:
<?php

namespace AlAdhanApi\Client\Exceptions;

/**
     * Class InvalidMonthException.
     */
    class InvalidMonthException extends \Exception
    {
    }


text:
package platforms;

import world.SimpleObject;

public class Bricks extends SimpleObject{

	public static final char ID = 15;

	public Bricks() {
		super(SimpleObject.NO_MOVES);
		this.setImage("../sprites/isocolors/greenBrick.png");
	}

	@Override
	public char id() {
		return ID;
	}

	@Override
	public void collision(SimpleObject s) {
		// TODO Auto-generated method stub

	}

	@Override
	public void update() {
		// TODO Auto-generated method stub

	}

}


text:
package activator

const (
	// Name is the name of the component.
	Name = "activator"
	// RevisionHeaderName is the header key for revision name.
	RevisionHeaderName = "Knative-Serving-Revision"
	// RevisionHeaderNamespace is the header key for revision's namespace.
	RevisionHeaderNamespace = "Knative-Serving-Namespace"
)

var (
	// RevisionHeaders are the headers the activator uses to identify the
	// revision. They are removed before reaching the user container.
	RevisionHeaders = []string{
		RevisionHeaderName,
		RevisionHeaderNamespace,
	}
)


text:
/*globals define, angular, alert*/

define([
    'angular',
    'text!./templates/propertyGridBody.html',
    'css!./styles/propertyGridBody.css',

    './propertyGroup'

], function (ng, template) {

    'use strict';

    angular.module(
        'isis.ui.propertyGridBody', [
            'isis.ui.propertyGroup'
        ]

    )
        .directive(
            'propertyGridBody',
            function () {

                return {
                    scope: {
                        propertyGroups: '=',
                        config: '='
                    },
                    restrict: 'E',
                    replace: true,
                    template: template

                };
            });

});